vimeo.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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_re.append(r'\bconfig\s*=\s*({.+?})\s*;')
  522. config = self._search_regex(config_re, webpage, 'info section',
  523. flags=re.DOTALL)
  524. config = json.loads(config)
  525. except Exception as e:
  526. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  527. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  528. if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
  529. if '_video_password_verified' in data:
  530. raise ExtractorError('video password verification failed!')
  531. self._verify_video_password(redirect_url, video_id, webpage)
  532. return self._real_extract(
  533. smuggle_url(redirect_url, {'_video_password_verified': 'verified'}))
  534. else:
  535. raise ExtractorError('Unable to extract info section',
  536. cause=e)
  537. else:
  538. if config.get('view') == 4:
  539. config = self._verify_player_video_password(redirect_url, video_id)
  540. vod = config.get('video', {}).get('vod', {})
  541. def is_rented():
  542. if '>You rented this title.<' in webpage:
  543. return True
  544. if config.get('user', {}).get('purchased'):
  545. return True
  546. for purchase_option in vod.get('purchase_options', []):
  547. if purchase_option.get('purchased'):
  548. return True
  549. label = purchase_option.get('label_string')
  550. if label and (label.startswith('You rented this') or label.endswith(' remaining')):
  551. return True
  552. return False
  553. if is_rented() and vod.get('is_trailer'):
  554. feature_id = vod.get('feature_id')
  555. if feature_id and not data.get('force_feature_id', False):
  556. return self.url_result(smuggle_url(
  557. 'https://player.vimeo.com/player/%s' % feature_id,
  558. {'force_feature_id': True}), 'Vimeo')
  559. # Extract video description
  560. video_description = self._html_search_regex(
  561. r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
  562. webpage, 'description', default=None)
  563. if not video_description:
  564. video_description = self._html_search_meta(
  565. 'description', webpage, default=None)
  566. if not video_description and mobj.group('pro'):
  567. orig_webpage = self._download_webpage(
  568. orig_url, video_id,
  569. note='Downloading webpage for description',
  570. fatal=False)
  571. if orig_webpage:
  572. video_description = self._html_search_meta(
  573. 'description', orig_webpage, default=None)
  574. if not video_description and not mobj.group('player'):
  575. self._downloader.report_warning('Cannot find video description')
  576. # Extract upload date
  577. if not timestamp:
  578. timestamp = self._search_regex(
  579. r'<time[^>]+datetime="([^"]+)"', webpage,
  580. 'timestamp', default=None)
  581. try:
  582. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  583. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  584. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  585. except RegexNotFoundError:
  586. # This info is only available in vimeo.com/{id} urls
  587. view_count = None
  588. like_count = None
  589. comment_count = None
  590. formats = []
  591. download_request = sanitized_Request('https://vimeo.com/%s?action=load_download_config' % video_id, headers={
  592. 'X-Requested-With': 'XMLHttpRequest'})
  593. download_data = self._download_json(download_request, video_id, fatal=False)
  594. if download_data:
  595. source_file = download_data.get('source_file')
  596. if isinstance(source_file, dict):
  597. download_url = source_file.get('download_url')
  598. if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
  599. source_name = source_file.get('public_name', 'Original')
  600. if self._is_valid_url(download_url, video_id, '%s video' % source_name):
  601. ext = (try_get(
  602. source_file, lambda x: x['extension'],
  603. compat_str) or determine_ext(
  604. download_url, None) or 'mp4').lower()
  605. formats.append({
  606. 'url': download_url,
  607. 'ext': ext,
  608. 'width': int_or_none(source_file.get('width')),
  609. 'height': int_or_none(source_file.get('height')),
  610. 'filesize': parse_filesize(source_file.get('size')),
  611. 'format_id': source_name,
  612. 'preference': 1,
  613. })
  614. info_dict_config = self._parse_config(config, video_id)
  615. formats.extend(info_dict_config['formats'])
  616. self._vimeo_sort_formats(formats)
  617. json_ld = self._search_json_ld(webpage, video_id, default={})
  618. if not cc_license:
  619. cc_license = self._search_regex(
  620. r'<link[^>]+rel=["\']license["\'][^>]+href=(["\'])(?P<license>(?:(?!\1).)+)\1',
  621. webpage, 'license', default=None, group='license')
  622. channel_url = 'https://vimeo.com/channels/%s' % channel_id if channel_id else None
  623. info_dict = {
  624. 'id': video_id,
  625. 'formats': formats,
  626. 'timestamp': unified_timestamp(timestamp),
  627. 'description': video_description,
  628. 'webpage_url': url,
  629. 'view_count': view_count,
  630. 'like_count': like_count,
  631. 'comment_count': comment_count,
  632. 'license': cc_license,
  633. 'channel_id': channel_id,
  634. 'channel_url': channel_url,
  635. }
  636. info_dict = merge_dicts(info_dict, info_dict_config, json_ld)
  637. return info_dict
  638. class VimeoOndemandIE(VimeoBaseInfoExtractor):
  639. IE_NAME = 'vimeo:ondemand'
  640. _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
  641. _TESTS = [{
  642. # ondemand video not available via https://vimeo.com/id
  643. 'url': 'https://vimeo.com/ondemand/20704',
  644. 'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
  645. 'info_dict': {
  646. 'id': '105442900',
  647. 'ext': 'mp4',
  648. 'title': 'המעבדה - במאי יותם פלדמן',
  649. 'uploader': 'גם סרטים',
  650. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
  651. 'uploader_id': 'gumfilms',
  652. },
  653. 'params': {
  654. 'format': 'best[protocol=https]',
  655. },
  656. }, {
  657. # requires Referer to be passed along with og:video:url
  658. 'url': 'https://vimeo.com/ondemand/36938/126682985',
  659. 'info_dict': {
  660. 'id': '126682985',
  661. 'ext': 'mp4',
  662. 'title': 'Rävlock, rätt läte på rätt plats',
  663. 'uploader': 'Lindroth & Norin',
  664. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user14430847',
  665. 'uploader_id': 'user14430847',
  666. },
  667. 'params': {
  668. 'skip_download': True,
  669. },
  670. }, {
  671. 'url': 'https://vimeo.com/ondemand/nazmaalik',
  672. 'only_matching': True,
  673. }, {
  674. 'url': 'https://vimeo.com/ondemand/141692381',
  675. 'only_matching': True,
  676. }, {
  677. 'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
  678. 'only_matching': True,
  679. }]
  680. def _real_extract(self, url):
  681. video_id = self._match_id(url)
  682. webpage = self._download_webpage(url, video_id)
  683. return self.url_result(
  684. # Some videos require Referer to be passed along with og:video:url
  685. # similarly to generic vimeo embeds (e.g.
  686. # https://vimeo.com/ondemand/36938/126682985).
  687. VimeoIE._smuggle_referrer(self._og_search_video_url(webpage), url),
  688. VimeoIE.ie_key())
  689. class VimeoChannelIE(VimeoBaseInfoExtractor):
  690. IE_NAME = 'vimeo:channel'
  691. _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
  692. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  693. _TITLE = None
  694. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  695. _TESTS = [{
  696. 'url': 'https://vimeo.com/channels/tributes',
  697. 'info_dict': {
  698. 'id': 'tributes',
  699. 'title': 'Vimeo Tributes',
  700. },
  701. 'playlist_mincount': 25,
  702. }]
  703. def _page_url(self, base_url, pagenum):
  704. return '%s/videos/page:%d/' % (base_url, pagenum)
  705. def _extract_list_title(self, webpage):
  706. return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  707. def _login_list_password(self, page_url, list_id, webpage):
  708. login_form = self._search_regex(
  709. r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
  710. webpage, 'login form', default=None)
  711. if not login_form:
  712. return webpage
  713. password = self._downloader.params.get('videopassword')
  714. if password is None:
  715. raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
  716. fields = self._hidden_inputs(login_form)
  717. token, vuid = self._extract_xsrft_and_vuid(webpage)
  718. fields['token'] = token
  719. fields['password'] = password
  720. post = urlencode_postdata(fields)
  721. password_path = self._search_regex(
  722. r'action="([^"]+)"', login_form, 'password URL')
  723. password_url = compat_urlparse.urljoin(page_url, password_path)
  724. password_request = sanitized_Request(password_url, post)
  725. password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
  726. self._set_vimeo_cookie('vuid', vuid)
  727. self._set_vimeo_cookie('xsrft', token)
  728. return self._download_webpage(
  729. password_request, list_id,
  730. 'Verifying the password', 'Wrong password')
  731. def _title_and_entries(self, list_id, base_url):
  732. for pagenum in itertools.count(1):
  733. page_url = self._page_url(base_url, pagenum)
  734. webpage = self._download_webpage(
  735. page_url, list_id,
  736. 'Downloading page %s' % pagenum)
  737. if pagenum == 1:
  738. webpage = self._login_list_password(page_url, list_id, webpage)
  739. yield self._extract_list_title(webpage)
  740. # Try extracting href first since not all videos are available via
  741. # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
  742. clips = re.findall(
  743. r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
  744. if clips:
  745. for video_id, video_url, video_title in clips:
  746. yield self.url_result(
  747. compat_urlparse.urljoin(base_url, video_url),
  748. VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
  749. # More relaxed fallback
  750. else:
  751. for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
  752. yield self.url_result(
  753. 'https://vimeo.com/%s' % video_id,
  754. VimeoIE.ie_key(), video_id=video_id)
  755. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  756. break
  757. def _extract_videos(self, list_id, base_url):
  758. title_and_entries = self._title_and_entries(list_id, base_url)
  759. list_title = next(title_and_entries)
  760. return self.playlist_result(title_and_entries, list_id, list_title)
  761. def _real_extract(self, url):
  762. mobj = re.match(self._VALID_URL, url)
  763. channel_id = mobj.group('id')
  764. return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
  765. class VimeoUserIE(VimeoChannelIE):
  766. IE_NAME = 'vimeo:user'
  767. _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
  768. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  769. _TESTS = [{
  770. 'url': 'https://vimeo.com/nkistudio/videos',
  771. 'info_dict': {
  772. 'title': 'Nki',
  773. 'id': 'nkistudio',
  774. },
  775. 'playlist_mincount': 66,
  776. }]
  777. def _real_extract(self, url):
  778. mobj = re.match(self._VALID_URL, url)
  779. name = mobj.group('name')
  780. return self._extract_videos(name, 'https://vimeo.com/%s' % name)
  781. class VimeoAlbumIE(VimeoChannelIE):
  782. IE_NAME = 'vimeo:album'
  783. _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)(?:$|[?#]|/(?!video))'
  784. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  785. _TESTS = [{
  786. 'url': 'https://vimeo.com/album/2632481',
  787. 'info_dict': {
  788. 'id': '2632481',
  789. 'title': 'Staff Favorites: November 2013',
  790. },
  791. 'playlist_mincount': 13,
  792. }, {
  793. 'note': 'Password-protected album',
  794. 'url': 'https://vimeo.com/album/3253534',
  795. 'info_dict': {
  796. 'title': 'test',
  797. 'id': '3253534',
  798. },
  799. 'playlist_count': 1,
  800. 'params': {
  801. 'videopassword': 'youtube-dl',
  802. }
  803. }, {
  804. 'url': 'https://vimeo.com/album/2632481/sort:plays/format:thumbnail',
  805. 'only_matching': True,
  806. }, {
  807. # TODO: respect page number
  808. 'url': 'https://vimeo.com/album/2632481/page:2/sort:plays/format:thumbnail',
  809. 'only_matching': True,
  810. }]
  811. def _page_url(self, base_url, pagenum):
  812. return '%s/page:%d/' % (base_url, pagenum)
  813. def _real_extract(self, url):
  814. album_id = self._match_id(url)
  815. return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
  816. class VimeoGroupsIE(VimeoAlbumIE):
  817. IE_NAME = 'vimeo:group'
  818. _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
  819. _TESTS = [{
  820. 'url': 'https://vimeo.com/groups/rolexawards',
  821. 'info_dict': {
  822. 'id': 'rolexawards',
  823. 'title': 'Rolex Awards for Enterprise',
  824. },
  825. 'playlist_mincount': 73,
  826. }]
  827. def _extract_list_title(self, webpage):
  828. return self._og_search_title(webpage)
  829. def _real_extract(self, url):
  830. mobj = re.match(self._VALID_URL, url)
  831. name = mobj.group('name')
  832. return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
  833. class VimeoReviewIE(VimeoBaseInfoExtractor):
  834. IE_NAME = 'vimeo:review'
  835. IE_DESC = 'Review pages on vimeo'
  836. _VALID_URL = r'https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  837. _TESTS = [{
  838. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  839. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  840. 'info_dict': {
  841. 'id': '75524534',
  842. 'ext': 'mp4',
  843. 'title': "DICK HARDWICK 'Comedian'",
  844. 'uploader': 'Richard Hardwick',
  845. 'uploader_id': 'user21297594',
  846. }
  847. }, {
  848. 'note': 'video player needs Referer',
  849. 'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
  850. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  851. 'info_dict': {
  852. 'id': '91613211',
  853. 'ext': 'mp4',
  854. 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
  855. 'uploader': 'DevWeek Events',
  856. 'duration': 2773,
  857. 'thumbnail': r're:^https?://.*\.jpg$',
  858. 'uploader_id': 'user22258446',
  859. }
  860. }, {
  861. 'note': 'Password protected',
  862. 'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
  863. 'info_dict': {
  864. 'id': '138823582',
  865. 'ext': 'mp4',
  866. 'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
  867. 'uploader': 'TMB',
  868. 'uploader_id': 'user37284429',
  869. },
  870. 'params': {
  871. 'videopassword': 'holygrail',
  872. },
  873. 'skip': 'video gone',
  874. }]
  875. def _real_initialize(self):
  876. self._login()
  877. def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
  878. webpage = self._download_webpage(webpage_url, video_id)
  879. config_url = self._html_search_regex(
  880. r'data-config-url=(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
  881. 'config URL', default=None, group='url')
  882. if not config_url:
  883. data = self._parse_json(self._search_regex(
  884. r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
  885. default=NO_DEFAULT if video_password_verified else '{}'), video_id)
  886. config_url = data.get('vimeo_esi', {}).get('config', {}).get('configUrl')
  887. if config_url is None:
  888. self._verify_video_password(webpage_url, video_id, webpage)
  889. config_url = self._get_config_url(
  890. webpage_url, video_id, video_password_verified=True)
  891. return config_url
  892. def _real_extract(self, url):
  893. video_id = self._match_id(url)
  894. config_url = self._get_config_url(url, video_id)
  895. config = self._download_json(config_url, video_id)
  896. info_dict = self._parse_config(config, video_id)
  897. self._vimeo_sort_formats(info_dict['formats'])
  898. info_dict['id'] = video_id
  899. return info_dict
  900. class VimeoWatchLaterIE(VimeoChannelIE):
  901. IE_NAME = 'vimeo:watchlater'
  902. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  903. _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
  904. _TITLE = 'Watch Later'
  905. _LOGIN_REQUIRED = True
  906. _TESTS = [{
  907. 'url': 'https://vimeo.com/watchlater',
  908. 'only_matching': True,
  909. }]
  910. def _real_initialize(self):
  911. self._login()
  912. def _page_url(self, base_url, pagenum):
  913. url = '%s/page:%d/' % (base_url, pagenum)
  914. request = sanitized_Request(url)
  915. # Set the header to get a partial html page with the ids,
  916. # the normal page doesn't contain them.
  917. request.add_header('X-Requested-With', 'XMLHttpRequest')
  918. return request
  919. def _real_extract(self, url):
  920. return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
  921. class VimeoLikesIE(InfoExtractor):
  922. _VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
  923. IE_NAME = 'vimeo:likes'
  924. IE_DESC = 'Vimeo user likes'
  925. _TESTS = [{
  926. 'url': 'https://vimeo.com/user755559/likes/',
  927. 'playlist_mincount': 293,
  928. 'info_dict': {
  929. 'id': 'user755559_likes',
  930. 'description': 'See all the videos urza likes',
  931. 'title': 'Videos urza likes',
  932. },
  933. }, {
  934. 'url': 'https://vimeo.com/stormlapse/likes',
  935. 'only_matching': True,
  936. }]
  937. def _real_extract(self, url):
  938. user_id = self._match_id(url)
  939. webpage = self._download_webpage(url, user_id)
  940. page_count = self._int(
  941. self._search_regex(
  942. r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
  943. .*?</a></li>\s*<li\s+class="pagination_next">
  944. ''', webpage, 'page count', default=1),
  945. 'page count', fatal=True)
  946. PAGE_SIZE = 12
  947. title = self._html_search_regex(
  948. r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
  949. description = self._html_search_meta('description', webpage)
  950. def _get_page(idx):
  951. page_url = 'https://vimeo.com/%s/likes/page:%d/sort:date' % (
  952. user_id, idx + 1)
  953. webpage = self._download_webpage(
  954. page_url, user_id,
  955. note='Downloading page %d/%d' % (idx + 1, page_count))
  956. video_list = self._search_regex(
  957. r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
  958. webpage, 'video content')
  959. paths = re.findall(
  960. r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
  961. for path in paths:
  962. yield {
  963. '_type': 'url',
  964. 'url': compat_urlparse.urljoin(page_url, path),
  965. }
  966. pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
  967. return {
  968. '_type': 'playlist',
  969. 'id': '%s_likes' % user_id,
  970. 'title': title,
  971. 'description': description,
  972. 'entries': pl,
  973. }