vimeo.py 41 KB

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