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.

338 lines
14 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/(?:.*?/)?(?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. try:
  180. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, u'view count'))
  181. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, u'like count'))
  182. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, u'comment count'))
  183. except RegexNotFoundError:
  184. # This info is only available in vimeo.com/{id} urls
  185. view_count = None
  186. like_count = None
  187. comment_count = None
  188. # Vimeo specific: extract request signature and timestamp
  189. sig = config['request']['signature']
  190. timestamp = config['request']['timestamp']
  191. # Vimeo specific: extract video codec and quality information
  192. # First consider quality, then codecs, then take everything
  193. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  194. files = {'hd': [], 'sd': [], 'other': []}
  195. config_files = config["video"].get("files") or config["request"].get("files")
  196. for codec_name, codec_extension in codecs:
  197. for quality in config_files.get(codec_name, []):
  198. format_id = '-'.join((codec_name, quality)).lower()
  199. key = quality if quality in files else 'other'
  200. video_url = None
  201. if isinstance(config_files[codec_name], dict):
  202. file_info = config_files[codec_name][quality]
  203. video_url = file_info.get('url')
  204. else:
  205. file_info = {}
  206. if video_url is None:
  207. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  208. %(video_id, sig, timestamp, quality, codec_name.upper())
  209. files[key].append({
  210. 'ext': codec_extension,
  211. 'url': video_url,
  212. 'format_id': format_id,
  213. 'width': file_info.get('width'),
  214. 'height': file_info.get('height'),
  215. })
  216. formats = []
  217. for key in ('other', 'sd', 'hd'):
  218. formats += files[key]
  219. if len(formats) == 0:
  220. raise ExtractorError(u'No known codec found')
  221. return {
  222. 'id': video_id,
  223. 'uploader': video_uploader,
  224. 'uploader_id': video_uploader_id,
  225. 'upload_date': video_upload_date,
  226. 'title': video_title,
  227. 'thumbnail': video_thumbnail,
  228. 'description': video_description,
  229. 'formats': formats,
  230. 'webpage_url': url,
  231. 'view_count': view_count,
  232. 'like_count': like_count,
  233. 'comment_count': comment_count,
  234. }
  235. class VimeoChannelIE(InfoExtractor):
  236. IE_NAME = u'vimeo:channel'
  237. _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
  238. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  239. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  240. def _page_url(self, base_url, pagenum):
  241. return '%s/videos/page:%d/' % (base_url, pagenum)
  242. def _extract_list_title(self, webpage):
  243. return self._html_search_regex(self._TITLE_RE, webpage, u'list title')
  244. def _extract_videos(self, list_id, base_url):
  245. video_ids = []
  246. for pagenum in itertools.count(1):
  247. webpage = self._download_webpage(
  248. self._page_url(base_url, pagenum) ,list_id,
  249. u'Downloading page %s' % pagenum)
  250. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  251. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  252. break
  253. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  254. for video_id in video_ids]
  255. return {'_type': 'playlist',
  256. 'id': list_id,
  257. 'title': self._extract_list_title(webpage),
  258. 'entries': entries,
  259. }
  260. def _real_extract(self, url):
  261. mobj = re.match(self._VALID_URL, url)
  262. channel_id = mobj.group('id')
  263. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  264. class VimeoUserIE(VimeoChannelIE):
  265. IE_NAME = u'vimeo:user'
  266. _VALID_URL = r'(?:https?://)?vimeo.\com/(?P<name>[^/]+)'
  267. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  268. @classmethod
  269. def suitable(cls, url):
  270. if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
  271. return False
  272. return super(VimeoUserIE, cls).suitable(url)
  273. def _real_extract(self, url):
  274. mobj = re.match(self._VALID_URL, url)
  275. name = mobj.group('name')
  276. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  277. class VimeoAlbumIE(VimeoChannelIE):
  278. IE_NAME = u'vimeo:album'
  279. _VALID_URL = r'(?:https?://)?vimeo.\com/album/(?P<id>\d+)'
  280. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  281. def _page_url(self, base_url, pagenum):
  282. return '%s/page:%d/' % (base_url, pagenum)
  283. def _real_extract(self, url):
  284. mobj = re.match(self._VALID_URL, url)
  285. album_id = mobj.group('id')
  286. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  287. class VimeoGroupsIE(VimeoAlbumIE):
  288. IE_NAME = u'vimeo:group'
  289. _VALID_URL = r'(?:https?://)?vimeo.\com/groups/(?P<name>[^/]+)'
  290. def _extract_list_title(self, webpage):
  291. return self._og_search_title(webpage)
  292. def _real_extract(self, url):
  293. mobj = re.match(self._VALID_URL, url)
  294. name = mobj.group('name')
  295. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)