vimeo.py 42 KB

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