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.

986 lines
40 KiB

8 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import itertools
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_HTTPError,
  9. compat_str,
  10. compat_urlparse,
  11. )
  12. from ..utils import (
  13. determine_ext,
  14. ExtractorError,
  15. InAdvancePagedList,
  16. int_or_none,
  17. NO_DEFAULT,
  18. RegexNotFoundError,
  19. sanitized_Request,
  20. smuggle_url,
  21. std_headers,
  22. unified_strdate,
  23. unsmuggle_url,
  24. urlencode_postdata,
  25. unescapeHTML,
  26. parse_filesize,
  27. try_get,
  28. )
  29. class VimeoBaseInfoExtractor(InfoExtractor):
  30. _NETRC_MACHINE = 'vimeo'
  31. _LOGIN_REQUIRED = False
  32. _LOGIN_URL = 'https://vimeo.com/log_in'
  33. def _login(self):
  34. (username, password) = self._get_login_info()
  35. if username is None:
  36. if self._LOGIN_REQUIRED:
  37. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  38. return
  39. self.report_login()
  40. webpage = self._download_webpage(self._LOGIN_URL, None, False)
  41. token, vuid = self._extract_xsrft_and_vuid(webpage)
  42. data = urlencode_postdata({
  43. 'action': 'login',
  44. 'email': username,
  45. 'password': password,
  46. 'service': 'vimeo',
  47. 'token': token,
  48. })
  49. login_request = sanitized_Request(self._LOGIN_URL, data)
  50. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  51. login_request.add_header('Referer', self._LOGIN_URL)
  52. self._set_vimeo_cookie('vuid', vuid)
  53. self._download_webpage(login_request, None, False, 'Wrong login info')
  54. def _verify_video_password(self, url, video_id, webpage):
  55. password = self._downloader.params.get('videopassword')
  56. if password is None:
  57. raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
  58. token, vuid = self._extract_xsrft_and_vuid(webpage)
  59. data = urlencode_postdata({
  60. 'password': password,
  61. 'token': token,
  62. })
  63. if url.startswith('http://'):
  64. # vimeo only supports https now, but the user can give an http url
  65. url = url.replace('http://', 'https://')
  66. password_request = sanitized_Request(url + '/password', data)
  67. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  68. password_request.add_header('Referer', url)
  69. self._set_vimeo_cookie('vuid', vuid)
  70. return self._download_webpage(
  71. password_request, video_id,
  72. 'Verifying the password', 'Wrong password')
  73. def _extract_xsrft_and_vuid(self, webpage):
  74. xsrft = self._search_regex(
  75. r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
  76. webpage, 'login token', group='xsrft')
  77. vuid = self._search_regex(
  78. r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
  79. webpage, 'vuid', group='vuid')
  80. return xsrft, vuid
  81. def _set_vimeo_cookie(self, name, value):
  82. self._set_cookie('vimeo.com', name, value)
  83. def _vimeo_sort_formats(self, formats):
  84. # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
  85. # at the same time without actual units specified. This lead to wrong sorting.
  86. self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'tbr', 'format_id'))
  87. def _parse_config(self, config, video_id):
  88. video_data = config['video']
  89. # Extract title
  90. video_title = video_data['title']
  91. # Extract uploader, uploader_url and uploader_id
  92. video_uploader = video_data.get('owner', {}).get('name')
  93. video_uploader_url = video_data.get('owner', {}).get('url')
  94. video_uploader_id = video_uploader_url.split('/')[-1] if video_uploader_url else None
  95. # Extract video thumbnail
  96. video_thumbnail = video_data.get('thumbnail')
  97. if video_thumbnail is None:
  98. video_thumbs = video_data.get('thumbs')
  99. if video_thumbs and isinstance(video_thumbs, dict):
  100. _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
  101. # Extract video duration
  102. video_duration = int_or_none(video_data.get('duration'))
  103. formats = []
  104. config_files = video_data.get('files') or config['request'].get('files', {})
  105. for f in config_files.get('progressive', []):
  106. video_url = f.get('url')
  107. if not video_url:
  108. continue
  109. formats.append({
  110. 'url': video_url,
  111. 'format_id': 'http-%s' % f.get('quality'),
  112. 'width': int_or_none(f.get('width')),
  113. 'height': int_or_none(f.get('height')),
  114. 'fps': int_or_none(f.get('fps')),
  115. 'tbr': int_or_none(f.get('bitrate')),
  116. })
  117. for files_type in ('hls', 'dash'):
  118. for cdn_name, cdn_data in config_files.get(files_type, {}).get('cdns', {}).items():
  119. manifest_url = cdn_data.get('url')
  120. if not manifest_url:
  121. continue
  122. format_id = '%s-%s' % (files_type, cdn_name)
  123. if files_type == 'hls':
  124. formats.extend(self._extract_m3u8_formats(
  125. manifest_url, video_id, 'mp4',
  126. 'm3u8_native', m3u8_id=format_id,
  127. note='Downloading %s m3u8 information' % cdn_name,
  128. fatal=False))
  129. elif files_type == 'dash':
  130. formats.extend(self._extract_mpd_formats(
  131. manifest_url.replace('/master.json', '/master.mpd'), video_id, format_id,
  132. 'Downloading %s MPD information' % cdn_name,
  133. fatal=False))
  134. subtitles = {}
  135. text_tracks = config['request'].get('text_tracks')
  136. if text_tracks:
  137. for tt in text_tracks:
  138. subtitles[tt['lang']] = [{
  139. 'ext': 'vtt',
  140. 'url': 'https://vimeo.com' + tt['url'],
  141. }]
  142. return {
  143. 'title': video_title,
  144. 'uploader': video_uploader,
  145. 'uploader_id': video_uploader_id,
  146. 'uploader_url': video_uploader_url,
  147. 'thumbnail': video_thumbnail,
  148. 'duration': video_duration,
  149. 'formats': formats,
  150. 'subtitles': subtitles,
  151. }
  152. class VimeoIE(VimeoBaseInfoExtractor):
  153. """Information extractor for vimeo.com."""
  154. # _VALID_URL matches Vimeo URLs
  155. _VALID_URL = r'''(?x)
  156. https?://
  157. (?:
  158. (?:
  159. www|
  160. (?P<player>player)
  161. )
  162. \.
  163. )?
  164. vimeo(?P<pro>pro)?\.com/
  165. (?!(?:channels|album)/[^/?#]+/?(?:$|[?#])|[^/]+/review/|ondemand/)
  166. (?:.*?/)?
  167. (?:
  168. (?:
  169. play_redirect_hls|
  170. moogaloop\.swf)\?clip_id=
  171. )?
  172. (?:videos?/)?
  173. (?P<id>[0-9]+)
  174. (?:/[\da-f]+)?
  175. /?(?:[?&].*)?(?:[#].*)?$
  176. '''
  177. IE_NAME = 'vimeo'
  178. _TESTS = [
  179. {
  180. 'url': 'http://vimeo.com/56015672#at=0',
  181. 'md5': '8879b6cc097e987f02484baf890129e5',
  182. 'info_dict': {
  183. 'id': '56015672',
  184. 'ext': 'mp4',
  185. 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  186. 'description': 'md5:2d3305bad981a06ff79f027f19865021',
  187. 'upload_date': '20121220',
  188. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user7108434',
  189. 'uploader_id': 'user7108434',
  190. 'uploader': 'Filippo Valsorda',
  191. 'duration': 10,
  192. },
  193. },
  194. {
  195. 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
  196. 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
  197. 'note': 'Vimeo Pro video (#1197)',
  198. 'info_dict': {
  199. 'id': '68093876',
  200. 'ext': 'mp4',
  201. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/openstreetmapus',
  202. 'uploader_id': 'openstreetmapus',
  203. 'uploader': 'OpenStreetMap US',
  204. 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
  205. 'description': 'md5:fd69a7b8d8c34a4e1d2ec2e4afd6ec30',
  206. 'duration': 1595,
  207. },
  208. },
  209. {
  210. 'url': 'http://player.vimeo.com/video/54469442',
  211. 'md5': '619b811a4417aa4abe78dc653becf511',
  212. 'note': 'Videos that embed the url in the player page',
  213. 'info_dict': {
  214. 'id': '54469442',
  215. 'ext': 'mp4',
  216. 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
  217. 'uploader': 'The BLN & Business of Software',
  218. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/theblnbusinessofsoftware',
  219. 'uploader_id': 'theblnbusinessofsoftware',
  220. 'duration': 3610,
  221. 'description': None,
  222. },
  223. },
  224. {
  225. 'url': 'http://vimeo.com/68375962',
  226. 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
  227. 'note': 'Video protected with password',
  228. 'info_dict': {
  229. 'id': '68375962',
  230. 'ext': 'mp4',
  231. 'title': 'youtube-dl password protected test video',
  232. 'upload_date': '20130614',
  233. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
  234. 'uploader_id': 'user18948128',
  235. 'uploader': 'Jaime Marquínez Ferrándiz',
  236. 'duration': 10,
  237. 'description': 'md5:dca3ea23adb29ee387127bc4ddfce63f',
  238. },
  239. 'params': {
  240. 'videopassword': 'youtube-dl',
  241. },
  242. },
  243. {
  244. 'url': 'http://vimeo.com/channels/keypeele/75629013',
  245. 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
  246. 'info_dict': {
  247. 'id': '75629013',
  248. 'ext': 'mp4',
  249. 'title': 'Key & Peele: Terrorist Interrogation',
  250. 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
  251. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/atencio',
  252. 'uploader_id': 'atencio',
  253. 'uploader': 'Peter Atencio',
  254. 'upload_date': '20130927',
  255. 'duration': 187,
  256. },
  257. },
  258. {
  259. 'url': 'http://vimeo.com/76979871',
  260. 'note': 'Video with subtitles',
  261. 'info_dict': {
  262. 'id': '76979871',
  263. 'ext': 'mp4',
  264. 'title': 'The New Vimeo Player (You Know, For Videos)',
  265. 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
  266. 'upload_date': '20131015',
  267. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/staff',
  268. 'uploader_id': 'staff',
  269. 'uploader': 'Vimeo Staff',
  270. 'duration': 62,
  271. }
  272. },
  273. {
  274. # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
  275. 'url': 'https://player.vimeo.com/video/98044508',
  276. 'note': 'The js code contains assignments to the same variable as the config',
  277. 'info_dict': {
  278. 'id': '98044508',
  279. 'ext': 'mp4',
  280. 'title': 'Pier Solar OUYA Official Trailer',
  281. 'uploader': 'Tulio Gonçalves',
  282. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user28849593',
  283. 'uploader_id': 'user28849593',
  284. },
  285. },
  286. {
  287. # contains original format
  288. 'url': 'https://vimeo.com/33951933',
  289. 'md5': '53c688fa95a55bf4b7293d37a89c5c53',
  290. 'info_dict': {
  291. 'id': '33951933',
  292. 'ext': 'mp4',
  293. 'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
  294. 'uploader': 'The DMCI',
  295. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/dmci',
  296. 'uploader_id': 'dmci',
  297. 'upload_date': '20111220',
  298. 'description': 'md5:ae23671e82d05415868f7ad1aec21147',
  299. },
  300. },
  301. {
  302. # only available via https://vimeo.com/channels/tributes/6213729 and
  303. # not via https://vimeo.com/6213729
  304. 'url': 'https://vimeo.com/channels/tributes/6213729',
  305. 'info_dict': {
  306. 'id': '6213729',
  307. 'ext': 'mov',
  308. 'title': 'Vimeo Tribute: The Shining',
  309. 'uploader': 'Casey Donahue',
  310. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/caseydonahue',
  311. 'uploader_id': 'caseydonahue',
  312. 'upload_date': '20090821',
  313. 'description': 'md5:bdbf314014e58713e6e5b66eb252f4a6',
  314. },
  315. 'params': {
  316. 'skip_download': True,
  317. },
  318. 'expected_warnings': ['Unable to download JSON metadata'],
  319. },
  320. {
  321. # redirects to ondemand extractor and should be passed through it
  322. # for successful extraction
  323. 'url': 'https://vimeo.com/73445910',
  324. 'info_dict': {
  325. 'id': '73445910',
  326. 'ext': 'mp4',
  327. 'title': 'The Reluctant Revolutionary',
  328. 'uploader': '10Ft Films',
  329. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/tenfootfilms',
  330. 'uploader_id': 'tenfootfilms',
  331. },
  332. 'params': {
  333. 'skip_download': True,
  334. },
  335. },
  336. {
  337. 'url': 'http://vimeo.com/moogaloop.swf?clip_id=2539741',
  338. 'only_matching': True,
  339. },
  340. {
  341. 'url': 'https://vimeo.com/109815029',
  342. 'note': 'Video not completely processed, "failed" seed status',
  343. 'only_matching': True,
  344. },
  345. {
  346. 'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
  347. 'only_matching': True,
  348. },
  349. {
  350. 'url': 'https://vimeo.com/album/2632481/video/79010983',
  351. 'only_matching': True,
  352. },
  353. {
  354. # source file returns 403: Forbidden
  355. 'url': 'https://vimeo.com/7809605',
  356. 'only_matching': True,
  357. },
  358. {
  359. 'url': 'https://vimeo.com/160743502/abd0e13fb4',
  360. 'only_matching': True,
  361. }
  362. ]
  363. @staticmethod
  364. def _smuggle_referrer(url, referrer_url):
  365. return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
  366. @staticmethod
  367. def _extract_urls(url, webpage):
  368. urls = []
  369. # Look for embedded (iframe) Vimeo player
  370. for mobj in re.finditer(
  371. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1',
  372. webpage):
  373. urls.append(VimeoIE._smuggle_referrer(unescapeHTML(mobj.group('url')), url))
  374. PLAIN_EMBED_RE = (
  375. # Look for embedded (swf embed) Vimeo player
  376. r'<embed[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)\1',
  377. # Look more for non-standard embedded Vimeo player
  378. r'<video[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/[0-9]+)\1',
  379. )
  380. for embed_re in PLAIN_EMBED_RE:
  381. for mobj in re.finditer(embed_re, webpage):
  382. urls.append(mobj.group('url'))
  383. return urls
  384. @staticmethod
  385. def _extract_url(url, webpage):
  386. urls = VimeoIE._extract_urls(url, webpage)
  387. return urls[0] if urls else None
  388. def _verify_player_video_password(self, url, video_id):
  389. password = self._downloader.params.get('videopassword')
  390. if password is None:
  391. raise ExtractorError('This video is protected by a password, use the --video-password option')
  392. data = urlencode_postdata({'password': password})
  393. pass_url = url + '/check-password'
  394. password_request = sanitized_Request(pass_url, data)
  395. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  396. password_request.add_header('Referer', url)
  397. return self._download_json(
  398. password_request, video_id,
  399. 'Verifying the password', 'Wrong password')
  400. def _real_initialize(self):
  401. self._login()
  402. def _real_extract(self, url):
  403. url, data = unsmuggle_url(url, {})
  404. headers = std_headers.copy()
  405. if 'http_headers' in data:
  406. headers.update(data['http_headers'])
  407. if 'Referer' not in headers:
  408. headers['Referer'] = url
  409. # Extract ID from URL
  410. mobj = re.match(self._VALID_URL, url)
  411. video_id = mobj.group('id')
  412. orig_url = url
  413. if mobj.group('pro') or mobj.group('player'):
  414. url = 'https://player.vimeo.com/video/' + video_id
  415. elif any(p in url for p in ('play_redirect_hls', 'moogaloop.swf')):
  416. url = 'https://vimeo.com/' + video_id
  417. # Retrieve video webpage to extract further information
  418. request = sanitized_Request(url, headers=headers)
  419. try:
  420. webpage, urlh = self._download_webpage_handle(request, video_id)
  421. # Some URLs redirect to ondemand can't be extracted with
  422. # this extractor right away thus should be passed through
  423. # ondemand extractor (e.g. https://vimeo.com/73445910)
  424. if VimeoOndemandIE.suitable(urlh.geturl()):
  425. return self.url_result(urlh.geturl(), VimeoOndemandIE.ie_key())
  426. except ExtractorError as ee:
  427. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  428. errmsg = ee.cause.read()
  429. if b'Because of its privacy settings, this video cannot be played here' in errmsg:
  430. raise ExtractorError(
  431. 'Cannot download embed-only video without embedding '
  432. 'URL. Please call youtube-dl with the URL of the page '
  433. 'that embeds this video.',
  434. expected=True)
  435. raise
  436. # Now we begin extracting as much information as we can from what we
  437. # retrieved. First we extract the information common to all extractors,
  438. # and latter we extract those that are Vimeo specific.
  439. self.report_extraction(video_id)
  440. vimeo_config = self._search_regex(
  441. r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));', webpage,
  442. 'vimeo config', default=None)
  443. if vimeo_config:
  444. seed_status = self._parse_json(vimeo_config, video_id).get('seed_status', {})
  445. if seed_status.get('state') == 'failed':
  446. raise ExtractorError(
  447. '%s said: %s' % (self.IE_NAME, seed_status['title']),
  448. expected=True)
  449. # Extract the config JSON
  450. try:
  451. try:
  452. config_url = self._html_search_regex(
  453. r' data-config-url="(.+?)"', webpage,
  454. 'config URL', default=None)
  455. if not config_url:
  456. # Sometimes new react-based page is served instead of old one that require
  457. # different config URL extraction approach (see
  458. # https://github.com/rg3/youtube-dl/pull/7209)
  459. vimeo_clip_page_config = self._search_regex(
  460. r'vimeo\.clip_page_config\s*=\s*({.+?});', webpage,
  461. 'vimeo clip page config')
  462. config_url = self._parse_json(
  463. vimeo_clip_page_config, video_id)['player']['config_url']
  464. config_json = self._download_webpage(config_url, video_id)
  465. config = json.loads(config_json)
  466. except RegexNotFoundError:
  467. # For pro videos or player.vimeo.com urls
  468. # We try to find out to which variable is assigned the config dic
  469. m_variable_name = re.search(r'(\w)\.video\.id', webpage)
  470. if m_variable_name is not None:
  471. config_re = r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))
  472. else:
  473. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  474. config = self._search_regex(config_re, webpage, 'info section',
  475. flags=re.DOTALL)
  476. config = json.loads(config)
  477. except Exception as e:
  478. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  479. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  480. if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
  481. if '_video_password_verified' in data:
  482. raise ExtractorError('video password verification failed!')
  483. self._verify_video_password(url, video_id, webpage)
  484. return self._real_extract(
  485. smuggle_url(url, {'_video_password_verified': 'verified'}))
  486. else:
  487. raise ExtractorError('Unable to extract info section',
  488. cause=e)
  489. else:
  490. if config.get('view') == 4:
  491. config = self._verify_player_video_password(url, video_id)
  492. def is_rented():
  493. if '>You rented this title.<' in webpage:
  494. return True
  495. if config.get('user', {}).get('purchased'):
  496. return True
  497. label = try_get(
  498. config, lambda x: x['video']['vod']['purchase_options'][0]['label_string'], compat_str)
  499. if label and label.startswith('You rented this'):
  500. return True
  501. return False
  502. if is_rented():
  503. feature_id = config.get('video', {}).get('vod', {}).get('feature_id')
  504. if feature_id and not data.get('force_feature_id', False):
  505. return self.url_result(smuggle_url(
  506. 'https://player.vimeo.com/player/%s' % feature_id,
  507. {'force_feature_id': True}), 'Vimeo')
  508. # Extract video description
  509. video_description = self._html_search_regex(
  510. r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
  511. webpage, 'description', default=None)
  512. if not video_description:
  513. video_description = self._html_search_meta(
  514. 'description', webpage, default=None)
  515. if not video_description and mobj.group('pro'):
  516. orig_webpage = self._download_webpage(
  517. orig_url, video_id,
  518. note='Downloading webpage for description',
  519. fatal=False)
  520. if orig_webpage:
  521. video_description = self._html_search_meta(
  522. 'description', orig_webpage, default=None)
  523. if not video_description and not mobj.group('player'):
  524. self._downloader.report_warning('Cannot find video description')
  525. # Extract upload date
  526. video_upload_date = None
  527. mobj = re.search(r'<time[^>]+datetime="([^"]+)"', webpage)
  528. if mobj is not None:
  529. video_upload_date = unified_strdate(mobj.group(1))
  530. try:
  531. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  532. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  533. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  534. except RegexNotFoundError:
  535. # This info is only available in vimeo.com/{id} urls
  536. view_count = None
  537. like_count = None
  538. comment_count = None
  539. formats = []
  540. download_request = sanitized_Request('https://vimeo.com/%s?action=load_download_config' % video_id, headers={
  541. 'X-Requested-With': 'XMLHttpRequest'})
  542. download_data = self._download_json(download_request, video_id, fatal=False)
  543. if download_data:
  544. source_file = download_data.get('source_file')
  545. if isinstance(source_file, dict):
  546. download_url = source_file.get('download_url')
  547. if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
  548. source_name = source_file.get('public_name', 'Original')
  549. if self._is_valid_url(download_url, video_id, '%s video' % source_name):
  550. ext = source_file.get('extension', determine_ext(download_url)).lower()
  551. formats.append({
  552. 'url': download_url,
  553. 'ext': ext,
  554. 'width': int_or_none(source_file.get('width')),
  555. 'height': int_or_none(source_file.get('height')),
  556. 'filesize': parse_filesize(source_file.get('size')),
  557. 'format_id': source_name,
  558. 'preference': 1,
  559. })
  560. info_dict = self._parse_config(config, video_id)
  561. formats.extend(info_dict['formats'])
  562. self._vimeo_sort_formats(formats)
  563. info_dict.update({
  564. 'id': video_id,
  565. 'formats': formats,
  566. 'upload_date': video_upload_date,
  567. 'description': video_description,
  568. 'webpage_url': url,
  569. 'view_count': view_count,
  570. 'like_count': like_count,
  571. 'comment_count': comment_count,
  572. })
  573. return info_dict
  574. class VimeoOndemandIE(VimeoBaseInfoExtractor):
  575. IE_NAME = 'vimeo:ondemand'
  576. _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
  577. _TESTS = [{
  578. # ondemand video not available via https://vimeo.com/id
  579. 'url': 'https://vimeo.com/ondemand/20704',
  580. 'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
  581. 'info_dict': {
  582. 'id': '105442900',
  583. 'ext': 'mp4',
  584. 'title': 'המעבדה - במאי יותם פלדמן',
  585. 'uploader': 'גם סרטים',
  586. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
  587. 'uploader_id': 'gumfilms',
  588. },
  589. 'params': {
  590. 'format': 'best[protocol=https]',
  591. },
  592. }, {
  593. # requires Referer to be passed along with og:video:url
  594. 'url': 'https://vimeo.com/ondemand/36938/126682985',
  595. 'info_dict': {
  596. 'id': '126682985',
  597. 'ext': 'mp4',
  598. 'title': 'Rävlock, rätt läte på rätt plats',
  599. 'uploader': 'Lindroth & Norin',
  600. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user14430847',
  601. 'uploader_id': 'user14430847',
  602. },
  603. 'params': {
  604. 'skip_download': True,
  605. },
  606. }, {
  607. 'url': 'https://vimeo.com/ondemand/nazmaalik',
  608. 'only_matching': True,
  609. }, {
  610. 'url': 'https://vimeo.com/ondemand/141692381',
  611. 'only_matching': True,
  612. }, {
  613. 'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
  614. 'only_matching': True,
  615. }]
  616. def _real_extract(self, url):
  617. video_id = self._match_id(url)
  618. webpage = self._download_webpage(url, video_id)
  619. return self.url_result(
  620. # Some videos require Referer to be passed along with og:video:url
  621. # similarly to generic vimeo embeds (e.g.
  622. # https://vimeo.com/ondemand/36938/126682985).
  623. VimeoIE._smuggle_referrer(self._og_search_video_url(webpage), url),
  624. VimeoIE.ie_key())
  625. class VimeoChannelIE(VimeoBaseInfoExtractor):
  626. IE_NAME = 'vimeo:channel'
  627. _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
  628. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  629. _TITLE = None
  630. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  631. _TESTS = [{
  632. 'url': 'https://vimeo.com/channels/tributes',
  633. 'info_dict': {
  634. 'id': 'tributes',
  635. 'title': 'Vimeo Tributes',
  636. },
  637. 'playlist_mincount': 25,
  638. }]
  639. def _page_url(self, base_url, pagenum):
  640. return '%s/videos/page:%d/' % (base_url, pagenum)
  641. def _extract_list_title(self, webpage):
  642. return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  643. def _login_list_password(self, page_url, list_id, webpage):
  644. login_form = self._search_regex(
  645. r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
  646. webpage, 'login form', default=None)
  647. if not login_form:
  648. return webpage
  649. password = self._downloader.params.get('videopassword')
  650. if password is None:
  651. raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
  652. fields = self._hidden_inputs(login_form)
  653. token, vuid = self._extract_xsrft_and_vuid(webpage)
  654. fields['token'] = token
  655. fields['password'] = password
  656. post = urlencode_postdata(fields)
  657. password_path = self._search_regex(
  658. r'action="([^"]+)"', login_form, 'password URL')
  659. password_url = compat_urlparse.urljoin(page_url, password_path)
  660. password_request = sanitized_Request(password_url, post)
  661. password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
  662. self._set_vimeo_cookie('vuid', vuid)
  663. self._set_vimeo_cookie('xsrft', token)
  664. return self._download_webpage(
  665. password_request, list_id,
  666. 'Verifying the password', 'Wrong password')
  667. def _title_and_entries(self, list_id, base_url):
  668. for pagenum in itertools.count(1):
  669. page_url = self._page_url(base_url, pagenum)
  670. webpage = self._download_webpage(
  671. page_url, list_id,
  672. 'Downloading page %s' % pagenum)
  673. if pagenum == 1:
  674. webpage = self._login_list_password(page_url, list_id, webpage)
  675. yield self._extract_list_title(webpage)
  676. # Try extracting href first since not all videos are available via
  677. # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
  678. clips = re.findall(
  679. r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
  680. if clips:
  681. for video_id, video_url, video_title in clips:
  682. yield self.url_result(
  683. compat_urlparse.urljoin(base_url, video_url),
  684. VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
  685. # More relaxed fallback
  686. else:
  687. for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
  688. yield self.url_result(
  689. 'https://vimeo.com/%s' % video_id,
  690. VimeoIE.ie_key(), video_id=video_id)
  691. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  692. break
  693. def _extract_videos(self, list_id, base_url):
  694. title_and_entries = self._title_and_entries(list_id, base_url)
  695. list_title = next(title_and_entries)
  696. return self.playlist_result(title_and_entries, list_id, list_title)
  697. def _real_extract(self, url):
  698. mobj = re.match(self._VALID_URL, url)
  699. channel_id = mobj.group('id')
  700. return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
  701. class VimeoUserIE(VimeoChannelIE):
  702. IE_NAME = 'vimeo:user'
  703. _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
  704. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  705. _TESTS = [{
  706. 'url': 'https://vimeo.com/nkistudio/videos',
  707. 'info_dict': {
  708. 'title': 'Nki',
  709. 'id': 'nkistudio',
  710. },
  711. 'playlist_mincount': 66,
  712. }]
  713. def _real_extract(self, url):
  714. mobj = re.match(self._VALID_URL, url)
  715. name = mobj.group('name')
  716. return self._extract_videos(name, 'https://vimeo.com/%s' % name)
  717. class VimeoAlbumIE(VimeoChannelIE):
  718. IE_NAME = 'vimeo:album'
  719. _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)(?:$|[?#]|/(?!video))'
  720. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  721. _TESTS = [{
  722. 'url': 'https://vimeo.com/album/2632481',
  723. 'info_dict': {
  724. 'id': '2632481',
  725. 'title': 'Staff Favorites: November 2013',
  726. },
  727. 'playlist_mincount': 13,
  728. }, {
  729. 'note': 'Password-protected album',
  730. 'url': 'https://vimeo.com/album/3253534',
  731. 'info_dict': {
  732. 'title': 'test',
  733. 'id': '3253534',
  734. },
  735. 'playlist_count': 1,
  736. 'params': {
  737. 'videopassword': 'youtube-dl',
  738. }
  739. }, {
  740. 'url': 'https://vimeo.com/album/2632481/sort:plays/format:thumbnail',
  741. 'only_matching': True,
  742. }, {
  743. # TODO: respect page number
  744. 'url': 'https://vimeo.com/album/2632481/page:2/sort:plays/format:thumbnail',
  745. 'only_matching': True,
  746. }]
  747. def _page_url(self, base_url, pagenum):
  748. return '%s/page:%d/' % (base_url, pagenum)
  749. def _real_extract(self, url):
  750. album_id = self._match_id(url)
  751. return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
  752. class VimeoGroupsIE(VimeoAlbumIE):
  753. IE_NAME = 'vimeo:group'
  754. _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
  755. _TESTS = [{
  756. 'url': 'https://vimeo.com/groups/rolexawards',
  757. 'info_dict': {
  758. 'id': 'rolexawards',
  759. 'title': 'Rolex Awards for Enterprise',
  760. },
  761. 'playlist_mincount': 73,
  762. }]
  763. def _extract_list_title(self, webpage):
  764. return self._og_search_title(webpage)
  765. def _real_extract(self, url):
  766. mobj = re.match(self._VALID_URL, url)
  767. name = mobj.group('name')
  768. return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
  769. class VimeoReviewIE(VimeoBaseInfoExtractor):
  770. IE_NAME = 'vimeo:review'
  771. IE_DESC = 'Review pages on vimeo'
  772. _VALID_URL = r'https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  773. _TESTS = [{
  774. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  775. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  776. 'info_dict': {
  777. 'id': '75524534',
  778. 'ext': 'mp4',
  779. 'title': "DICK HARDWICK 'Comedian'",
  780. 'uploader': 'Richard Hardwick',
  781. 'uploader_id': 'user21297594',
  782. }
  783. }, {
  784. 'note': 'video player needs Referer',
  785. 'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
  786. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  787. 'info_dict': {
  788. 'id': '91613211',
  789. 'ext': 'mp4',
  790. 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
  791. 'uploader': 'DevWeek Events',
  792. 'duration': 2773,
  793. 'thumbnail': r're:^https?://.*\.jpg$',
  794. 'uploader_id': 'user22258446',
  795. }
  796. }, {
  797. 'note': 'Password protected',
  798. 'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
  799. 'info_dict': {
  800. 'id': '138823582',
  801. 'ext': 'mp4',
  802. 'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
  803. 'uploader': 'TMB',
  804. 'uploader_id': 'user37284429',
  805. },
  806. 'params': {
  807. 'videopassword': 'holygrail',
  808. },
  809. 'skip': 'video gone',
  810. }]
  811. def _real_initialize(self):
  812. self._login()
  813. def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
  814. webpage = self._download_webpage(webpage_url, video_id)
  815. data = self._parse_json(self._search_regex(
  816. r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
  817. default=NO_DEFAULT if video_password_verified else '{}'), video_id)
  818. config_url = data.get('vimeo_esi', {}).get('config', {}).get('configUrl')
  819. if config_url is None:
  820. self._verify_video_password(webpage_url, video_id, webpage)
  821. config_url = self._get_config_url(
  822. webpage_url, video_id, video_password_verified=True)
  823. return config_url
  824. def _real_extract(self, url):
  825. video_id = self._match_id(url)
  826. config_url = self._get_config_url(url, video_id)
  827. config = self._download_json(config_url, video_id)
  828. info_dict = self._parse_config(config, video_id)
  829. self._vimeo_sort_formats(info_dict['formats'])
  830. info_dict['id'] = video_id
  831. return info_dict
  832. class VimeoWatchLaterIE(VimeoChannelIE):
  833. IE_NAME = 'vimeo:watchlater'
  834. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  835. _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
  836. _TITLE = 'Watch Later'
  837. _LOGIN_REQUIRED = True
  838. _TESTS = [{
  839. 'url': 'https://vimeo.com/watchlater',
  840. 'only_matching': True,
  841. }]
  842. def _real_initialize(self):
  843. self._login()
  844. def _page_url(self, base_url, pagenum):
  845. url = '%s/page:%d/' % (base_url, pagenum)
  846. request = sanitized_Request(url)
  847. # Set the header to get a partial html page with the ids,
  848. # the normal page doesn't contain them.
  849. request.add_header('X-Requested-With', 'XMLHttpRequest')
  850. return request
  851. def _real_extract(self, url):
  852. return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
  853. class VimeoLikesIE(InfoExtractor):
  854. _VALID_URL = r'https://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
  855. IE_NAME = 'vimeo:likes'
  856. IE_DESC = 'Vimeo user likes'
  857. _TEST = {
  858. 'url': 'https://vimeo.com/user755559/likes/',
  859. 'playlist_mincount': 293,
  860. 'info_dict': {
  861. 'id': 'user755559_likes',
  862. 'description': 'See all the videos urza likes',
  863. 'title': 'Videos urza likes',
  864. },
  865. }
  866. def _real_extract(self, url):
  867. user_id = self._match_id(url)
  868. webpage = self._download_webpage(url, user_id)
  869. page_count = self._int(
  870. self._search_regex(
  871. r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
  872. .*?</a></li>\s*<li\s+class="pagination_next">
  873. ''', webpage, 'page count'),
  874. 'page count', fatal=True)
  875. PAGE_SIZE = 12
  876. title = self._html_search_regex(
  877. r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
  878. description = self._html_search_meta('description', webpage)
  879. def _get_page(idx):
  880. page_url = 'https://vimeo.com/user%s/likes/page:%d/sort:date' % (
  881. user_id, idx + 1)
  882. webpage = self._download_webpage(
  883. page_url, user_id,
  884. note='Downloading page %d/%d' % (idx + 1, page_count))
  885. video_list = self._search_regex(
  886. r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
  887. webpage, 'video content')
  888. paths = re.findall(
  889. r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
  890. for path in paths:
  891. yield {
  892. '_type': 'url',
  893. 'url': compat_urlparse.urljoin(page_url, path),
  894. }
  895. pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
  896. return {
  897. '_type': 'playlist',
  898. 'id': 'user%s_likes' % user_id,
  899. 'title': title,
  900. 'description': description,
  901. 'entries': pl,
  902. }