You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

202 lines
8.9 KiB

  1. import json
  2. import re
  3. import itertools
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. compat_urllib_parse,
  7. compat_urllib_request,
  8. clean_html,
  9. get_element_by_attribute,
  10. ExtractorError,
  11. std_headers,
  12. )
  13. class VimeoIE(InfoExtractor):
  14. """Information extractor for vimeo.com."""
  15. # _VALID_URL matches Vimeo URLs
  16. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo(?P<pro>pro)?\.com/(?:(?:(?:groups|album)/[^/]+)|(?:.*?)/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)(?:[?].*)?$'
  17. _NETRC_MACHINE = 'vimeo'
  18. IE_NAME = u'vimeo'
  19. _TEST = {
  20. u'url': u'http://vimeo.com/56015672',
  21. u'file': u'56015672.mp4',
  22. u'md5': u'8879b6cc097e987f02484baf890129e5',
  23. u'info_dict': {
  24. u"upload_date": u"20121220",
  25. u"description": u"This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  26. u"uploader_id": u"user7108434",
  27. u"uploader": u"Filippo Valsorda",
  28. u"title": u"youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550"
  29. }
  30. }
  31. def _login(self):
  32. (username, password) = self._get_login_info()
  33. if username is None:
  34. return
  35. self.report_login()
  36. login_url = 'https://vimeo.com/log_in'
  37. webpage = self._download_webpage(login_url, None, False)
  38. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  39. data = compat_urllib_parse.urlencode({'email': username,
  40. 'password': password,
  41. 'action': 'login',
  42. 'service': 'vimeo',
  43. 'token': token,
  44. })
  45. login_request = compat_urllib_request.Request(login_url, data)
  46. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  47. login_request.add_header('Cookie', 'xsrft=%s' % token)
  48. self._download_webpage(login_request, None, False, u'Wrong login info')
  49. def _verify_video_password(self, url, video_id, webpage):
  50. password = self._downloader.params.get('videopassword', None)
  51. if password is None:
  52. raise ExtractorError(u'This video is protected by a password, use the --video-password option')
  53. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  54. data = compat_urllib_parse.urlencode({'password': password,
  55. 'token': token})
  56. # I didn't manage to use the password with https
  57. if url.startswith('https'):
  58. pass_url = url.replace('https','http')
  59. else:
  60. pass_url = url
  61. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  62. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  63. password_request.add_header('Cookie', 'xsrft=%s' % token)
  64. self._download_webpage(password_request, video_id,
  65. u'Verifying the password',
  66. u'Wrong password')
  67. def _real_initialize(self):
  68. self._login()
  69. def _real_extract(self, url, new_video=True):
  70. # Extract ID from URL
  71. mobj = re.match(self._VALID_URL, url)
  72. if mobj is None:
  73. raise ExtractorError(u'Invalid URL: %s' % url)
  74. video_id = mobj.group('id')
  75. if not mobj.group('proto'):
  76. url = 'https://' + url
  77. if mobj.group('direct_link') or mobj.group('pro'):
  78. url = 'https://vimeo.com/' + video_id
  79. # Retrieve video webpage to extract further information
  80. request = compat_urllib_request.Request(url, None, std_headers)
  81. webpage = self._download_webpage(request, video_id)
  82. # Now we begin extracting as much information as we can from what we
  83. # retrieved. First we extract the information common to all extractors,
  84. # and latter we extract those that are Vimeo specific.
  85. self.report_extraction(video_id)
  86. # Extract the config JSON
  87. try:
  88. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  89. config = json.loads(config)
  90. except:
  91. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  92. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  93. if re.search('If so please provide the correct password.', webpage):
  94. self._verify_video_password(url, video_id, webpage)
  95. return self._real_extract(url)
  96. else:
  97. raise ExtractorError(u'Unable to extract info section')
  98. # Extract title
  99. video_title = config["video"]["title"]
  100. # Extract uploader and uploader_id
  101. video_uploader = config["video"]["owner"]["name"]
  102. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  103. # Extract video thumbnail
  104. video_thumbnail = config["video"]["thumbnail"]
  105. # Extract video description
  106. video_description = get_element_by_attribute("itemprop", "description", webpage)
  107. if video_description: video_description = clean_html(video_description)
  108. else: video_description = u''
  109. # Extract upload date
  110. video_upload_date = None
  111. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  112. if mobj is not None:
  113. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  114. # Vimeo specific: extract request signature and timestamp
  115. sig = config['request']['signature']
  116. timestamp = config['request']['timestamp']
  117. # Vimeo specific: extract video codec and quality information
  118. # First consider quality, then codecs, then take everything
  119. # TODO bind to format param
  120. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  121. files = { 'hd': [], 'sd': [], 'other': []}
  122. for codec_name, codec_extension in codecs:
  123. if codec_name in config["video"]["files"]:
  124. if 'hd' in config["video"]["files"][codec_name]:
  125. files['hd'].append((codec_name, codec_extension, 'hd'))
  126. elif 'sd' in config["video"]["files"][codec_name]:
  127. files['sd'].append((codec_name, codec_extension, 'sd'))
  128. else:
  129. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  130. for quality in ('hd', 'sd', 'other'):
  131. if len(files[quality]) > 0:
  132. video_quality = files[quality][0][2]
  133. video_codec = files[quality][0][0]
  134. video_extension = files[quality][0][1]
  135. self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  136. break
  137. else:
  138. raise ExtractorError(u'No known codec found')
  139. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  140. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  141. return [{
  142. 'id': video_id,
  143. 'url': video_url,
  144. 'uploader': video_uploader,
  145. 'uploader_id': video_uploader_id,
  146. 'upload_date': video_upload_date,
  147. 'title': video_title,
  148. 'ext': video_extension,
  149. 'thumbnail': video_thumbnail,
  150. 'description': video_description,
  151. }]
  152. class VimeoChannelIE(InfoExtractor):
  153. IE_NAME = u'vimeo:channel'
  154. _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
  155. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  156. def _real_extract(self, url):
  157. mobj = re.match(self._VALID_URL, url)
  158. channel_id = mobj.group('id')
  159. video_ids = []
  160. for pagenum in itertools.count(1):
  161. webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
  162. channel_id, u'Downloading page %s' % pagenum)
  163. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  164. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  165. break
  166. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  167. for video_id in video_ids]
  168. channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
  169. webpage, u'channel title')
  170. return {'_type': 'playlist',
  171. 'id': channel_id,
  172. 'title': channel_title,
  173. 'entries': entries,
  174. }