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.

294 lines
12 KiB

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