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.

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