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.

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