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.

1131 lines
46 KiB

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