vimeo.py 48 KB

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