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.

1020 lines
41 KiB

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