vimeo.py 43 KB

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