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.

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