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.

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