vimeo.py 48 KB

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