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.

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