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.

274 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|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 not mobj.group('proto'):
  122. url = 'https://' + url
  123. elif mobj.group('pro'):
  124. url = 'http://player.vimeo.com/video/' + video_id
  125. elif mobj.group('direct_link'):
  126. url = 'https://vimeo.com/' + video_id
  127. # Retrieve video webpage to extract further information
  128. request = compat_urllib_request.Request(url, None, headers)
  129. webpage = self._download_webpage(request, video_id)
  130. # Now we begin extracting as much information as we can from what we
  131. # retrieved. First we extract the information common to all extractors,
  132. # and latter we extract those that are Vimeo specific.
  133. self.report_extraction(video_id)
  134. # Extract the config JSON
  135. try:
  136. try:
  137. config_url = self._html_search_regex(
  138. r' data-config-url="(.+?)"', webpage, u'config URL')
  139. config_json = self._download_webpage(config_url, video_id)
  140. config = json.loads(config_json)
  141. except RegexNotFoundError:
  142. # For pro videos or player.vimeo.com urls
  143. config = self._search_regex([r' = {config:({.+?}),assets:', r'c=({.+?);'],
  144. webpage, u'info section', flags=re.DOTALL)
  145. config = json.loads(config)
  146. except Exception as e:
  147. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  148. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  149. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  150. self._verify_video_password(url, video_id, webpage)
  151. return self._real_extract(url)
  152. else:
  153. raise ExtractorError(u'Unable to extract info section',
  154. cause=e)
  155. # Extract title
  156. video_title = config["video"]["title"]
  157. # Extract uploader and uploader_id
  158. video_uploader = config["video"]["owner"]["name"]
  159. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  160. # Extract video thumbnail
  161. video_thumbnail = config["video"].get("thumbnail")
  162. if video_thumbnail is None:
  163. _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
  164. # Extract video description
  165. video_description = None
  166. try:
  167. video_description = get_element_by_attribute("itemprop", "description", webpage)
  168. if video_description: video_description = clean_html(video_description)
  169. except AssertionError as err:
  170. # On some pages like (http://player.vimeo.com/video/54469442) the
  171. # html tags are not closed, python 2.6 cannot handle it
  172. if err.args[0] == 'we should not get here!':
  173. pass
  174. else:
  175. raise
  176. # Extract upload date
  177. video_upload_date = None
  178. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  179. if mobj is not None:
  180. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  181. # Vimeo specific: extract request signature and timestamp
  182. sig = config['request']['signature']
  183. timestamp = config['request']['timestamp']
  184. # Vimeo specific: extract video codec and quality information
  185. # First consider quality, then codecs, then take everything
  186. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  187. files = { 'hd': [], 'sd': [], 'other': []}
  188. config_files = config["video"].get("files") or config["request"].get("files")
  189. for codec_name, codec_extension in codecs:
  190. for quality in config_files.get(codec_name, []):
  191. format_id = '-'.join((codec_name, quality)).lower()
  192. key = quality if quality in files else 'other'
  193. video_url = None
  194. if isinstance(config_files[codec_name], dict):
  195. file_info = config_files[codec_name][quality]
  196. video_url = file_info.get('url')
  197. else:
  198. file_info = {}
  199. if video_url is None:
  200. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  201. %(video_id, sig, timestamp, quality, codec_name.upper())
  202. files[key].append({
  203. 'ext': codec_extension,
  204. 'url': video_url,
  205. 'format_id': format_id,
  206. 'width': file_info.get('width'),
  207. 'height': file_info.get('height'),
  208. })
  209. formats = []
  210. for key in ('other', 'sd', 'hd'):
  211. formats += files[key]
  212. if len(formats) == 0:
  213. raise ExtractorError(u'No known codec found')
  214. return [{
  215. 'id': video_id,
  216. 'uploader': video_uploader,
  217. 'uploader_id': video_uploader_id,
  218. 'upload_date': video_upload_date,
  219. 'title': video_title,
  220. 'thumbnail': video_thumbnail,
  221. 'description': video_description,
  222. 'formats': formats,
  223. }]
  224. class VimeoChannelIE(InfoExtractor):
  225. IE_NAME = u'vimeo:channel'
  226. _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
  227. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  228. def _real_extract(self, url):
  229. mobj = re.match(self._VALID_URL, url)
  230. channel_id = mobj.group('id')
  231. video_ids = []
  232. for pagenum in itertools.count(1):
  233. webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
  234. channel_id, u'Downloading page %s' % pagenum)
  235. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  236. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  237. break
  238. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  239. for video_id in video_ids]
  240. channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
  241. webpage, u'channel title')
  242. return {'_type': 'playlist',
  243. 'id': channel_id,
  244. 'title': channel_title,
  245. 'entries': entries,
  246. }