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.

243 lines
11 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. u'url': u'http://player.vimeo.com/video/54469442',
  45. u'file': u'54469442.mp4',
  46. u'md5': u'619b811a4417aa4abe78dc653becf511',
  47. u'note': u'Videos that embed the url in the player page',
  48. u'info_dict': {
  49. u'title': u'Kathy Sierra: Building the minimum Badass User, Business of Software',
  50. u'uploader': u'The BLN & Business of Software',
  51. },
  52. },
  53. ]
  54. def _login(self):
  55. (username, password) = self._get_login_info()
  56. if username is None:
  57. return
  58. self.report_login()
  59. login_url = 'https://vimeo.com/log_in'
  60. webpage = self._download_webpage(login_url, None, False)
  61. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  62. data = compat_urllib_parse.urlencode({'email': username,
  63. 'password': password,
  64. 'action': 'login',
  65. 'service': 'vimeo',
  66. 'token': token,
  67. })
  68. login_request = compat_urllib_request.Request(login_url, data)
  69. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  70. login_request.add_header('Cookie', 'xsrft=%s' % token)
  71. self._download_webpage(login_request, None, False, u'Wrong login info')
  72. def _verify_video_password(self, url, video_id, webpage):
  73. password = self._downloader.params.get('videopassword', None)
  74. if password is None:
  75. raise ExtractorError(u'This video is protected by a password, use the --video-password option')
  76. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  77. data = compat_urllib_parse.urlencode({'password': password,
  78. 'token': token})
  79. # I didn't manage to use the password with https
  80. if url.startswith('https'):
  81. pass_url = url.replace('https','http')
  82. else:
  83. pass_url = url
  84. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  85. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  86. password_request.add_header('Cookie', 'xsrft=%s' % token)
  87. self._download_webpage(password_request, video_id,
  88. u'Verifying the password',
  89. u'Wrong password')
  90. def _real_initialize(self):
  91. self._login()
  92. def _real_extract(self, url, new_video=True):
  93. # Extract ID from URL
  94. mobj = re.match(self._VALID_URL, url)
  95. if mobj is None:
  96. raise ExtractorError(u'Invalid URL: %s' % url)
  97. video_id = mobj.group('id')
  98. if not mobj.group('proto'):
  99. url = 'https://' + url
  100. elif mobj.group('pro'):
  101. url = 'http://player.vimeo.com/video/' + video_id
  102. elif mobj.group('direct_link'):
  103. url = 'https://vimeo.com/' + video_id
  104. # Retrieve video webpage to extract further information
  105. request = compat_urllib_request.Request(url, None, std_headers)
  106. webpage = self._download_webpage(request, video_id)
  107. # Now we begin extracting as much information as we can from what we
  108. # retrieved. First we extract the information common to all extractors,
  109. # and latter we extract those that are Vimeo specific.
  110. self.report_extraction(video_id)
  111. # Extract the config JSON
  112. try:
  113. config = self._search_regex([r' = {config:({.+?}),assets:', r'c=({.+?);'],
  114. webpage, u'info section', flags=re.DOTALL)
  115. config = json.loads(config)
  116. except:
  117. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  118. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  119. if re.search('If so please provide the correct password.', webpage):
  120. self._verify_video_password(url, video_id, webpage)
  121. return self._real_extract(url)
  122. else:
  123. raise ExtractorError(u'Unable to extract info section')
  124. # Extract title
  125. video_title = config["video"]["title"]
  126. # Extract uploader and uploader_id
  127. video_uploader = config["video"]["owner"]["name"]
  128. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  129. # Extract video thumbnail
  130. video_thumbnail = config["video"].get("thumbnail")
  131. if video_thumbnail is None:
  132. _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
  133. # Extract video description
  134. video_description = None
  135. try:
  136. video_description = get_element_by_attribute("itemprop", "description", webpage)
  137. if video_description: video_description = clean_html(video_description)
  138. except AssertionError as err:
  139. # On some pages like (http://player.vimeo.com/video/54469442) the
  140. # html tags are not closed, python 2.6 cannot handle it
  141. if err.args[0] == 'we should not get here!':
  142. pass
  143. else:
  144. raise
  145. # Extract upload date
  146. video_upload_date = None
  147. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  148. if mobj is not None:
  149. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  150. # Vimeo specific: extract request signature and timestamp
  151. sig = config['request']['signature']
  152. timestamp = config['request']['timestamp']
  153. # Vimeo specific: extract video codec and quality information
  154. # First consider quality, then codecs, then take everything
  155. # TODO bind to format param
  156. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  157. files = { 'hd': [], 'sd': [], 'other': []}
  158. config_files = config["video"].get("files") or config["request"].get("files")
  159. for codec_name, codec_extension in codecs:
  160. if codec_name in config_files:
  161. if 'hd' in config_files[codec_name]:
  162. files['hd'].append((codec_name, codec_extension, 'hd'))
  163. elif 'sd' in config_files[codec_name]:
  164. files['sd'].append((codec_name, codec_extension, 'sd'))
  165. else:
  166. files['other'].append((codec_name, codec_extension, config_files[codec_name][0]))
  167. for quality in ('hd', 'sd', 'other'):
  168. if len(files[quality]) > 0:
  169. video_quality = files[quality][0][2]
  170. video_codec = files[quality][0][0]
  171. video_extension = files[quality][0][1]
  172. self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  173. break
  174. else:
  175. raise ExtractorError(u'No known codec found')
  176. video_url = None
  177. if isinstance(config_files[video_codec], dict):
  178. video_url = config_files[video_codec][video_quality].get("url")
  179. if video_url is None:
  180. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  181. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  182. return [{
  183. 'id': video_id,
  184. 'url': video_url,
  185. 'uploader': video_uploader,
  186. 'uploader_id': video_uploader_id,
  187. 'upload_date': video_upload_date,
  188. 'title': video_title,
  189. 'ext': video_extension,
  190. 'thumbnail': video_thumbnail,
  191. 'description': video_description,
  192. }]
  193. class VimeoChannelIE(InfoExtractor):
  194. IE_NAME = u'vimeo:channel'
  195. _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
  196. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  197. def _real_extract(self, url):
  198. mobj = re.match(self._VALID_URL, url)
  199. channel_id = mobj.group('id')
  200. video_ids = []
  201. for pagenum in itertools.count(1):
  202. webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
  203. channel_id, u'Downloading page %s' % pagenum)
  204. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  205. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  206. break
  207. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  208. for video_id in video_ids]
  209. channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
  210. webpage, u'channel title')
  211. return {'_type': 'playlist',
  212. 'id': channel_id,
  213. 'title': channel_title,
  214. 'entries': entries,
  215. }