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.

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