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.

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