vimeo.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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(
  759. self._TITLE_RE, webpage, 'list title', fatal=False)
  760. def _login_list_password(self, page_url, list_id, webpage):
  761. login_form = self._search_regex(
  762. r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
  763. webpage, 'login form', default=None)
  764. if not login_form:
  765. return webpage
  766. password = self._downloader.params.get('videopassword')
  767. if password is None:
  768. raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
  769. fields = self._hidden_inputs(login_form)
  770. token, vuid = self._extract_xsrft_and_vuid(webpage)
  771. fields['token'] = token
  772. fields['password'] = password
  773. post = urlencode_postdata(fields)
  774. password_path = self._search_regex(
  775. r'action="([^"]+)"', login_form, 'password URL')
  776. password_url = compat_urlparse.urljoin(page_url, password_path)
  777. password_request = sanitized_Request(password_url, post)
  778. password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
  779. self._set_vimeo_cookie('vuid', vuid)
  780. self._set_vimeo_cookie('xsrft', token)
  781. return self._download_webpage(
  782. password_request, list_id,
  783. 'Verifying the password', 'Wrong password')
  784. def _title_and_entries(self, list_id, base_url):
  785. for pagenum in itertools.count(1):
  786. page_url = self._page_url(base_url, pagenum)
  787. webpage = self._download_webpage(
  788. page_url, list_id,
  789. 'Downloading page %s' % pagenum)
  790. if pagenum == 1:
  791. webpage = self._login_list_password(page_url, list_id, webpage)
  792. yield self._extract_list_title(webpage)
  793. # Try extracting href first since not all videos are available via
  794. # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
  795. clips = re.findall(
  796. r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
  797. if clips:
  798. for video_id, video_url, video_title in clips:
  799. yield self.url_result(
  800. compat_urlparse.urljoin(base_url, video_url),
  801. VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
  802. # More relaxed fallback
  803. else:
  804. for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
  805. yield self.url_result(
  806. 'https://vimeo.com/%s' % video_id,
  807. VimeoIE.ie_key(), video_id=video_id)
  808. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  809. break
  810. def _extract_videos(self, list_id, base_url):
  811. title_and_entries = self._title_and_entries(list_id, base_url)
  812. list_title = next(title_and_entries)
  813. return self.playlist_result(title_and_entries, list_id, list_title)
  814. def _real_extract(self, url):
  815. mobj = re.match(self._VALID_URL, url)
  816. channel_id = mobj.group('id')
  817. return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
  818. class VimeoUserIE(VimeoChannelIE):
  819. IE_NAME = 'vimeo:user'
  820. _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
  821. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  822. _TESTS = [{
  823. 'url': 'https://vimeo.com/nkistudio/videos',
  824. 'info_dict': {
  825. 'title': 'Nki',
  826. 'id': 'nkistudio',
  827. },
  828. 'playlist_mincount': 66,
  829. }]
  830. def _real_extract(self, url):
  831. mobj = re.match(self._VALID_URL, url)
  832. name = mobj.group('name')
  833. return self._extract_videos(name, 'https://vimeo.com/%s' % name)
  834. class VimeoAlbumIE(VimeoChannelIE):
  835. IE_NAME = 'vimeo:album'
  836. _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)(?:$|[?#]|/(?!video))'
  837. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  838. _TESTS = [{
  839. 'url': 'https://vimeo.com/album/2632481',
  840. 'info_dict': {
  841. 'id': '2632481',
  842. 'title': 'Staff Favorites: November 2013',
  843. },
  844. 'playlist_mincount': 13,
  845. }, {
  846. 'note': 'Password-protected album',
  847. 'url': 'https://vimeo.com/album/3253534',
  848. 'info_dict': {
  849. 'title': 'test',
  850. 'id': '3253534',
  851. },
  852. 'playlist_count': 1,
  853. 'params': {
  854. 'videopassword': 'youtube-dl',
  855. }
  856. }, {
  857. 'url': 'https://vimeo.com/album/2632481/sort:plays/format:thumbnail',
  858. 'only_matching': True,
  859. }, {
  860. # TODO: respect page number
  861. 'url': 'https://vimeo.com/album/2632481/page:2/sort:plays/format:thumbnail',
  862. 'only_matching': True,
  863. }]
  864. def _page_url(self, base_url, pagenum):
  865. return '%s/page:%d/' % (base_url, pagenum)
  866. def _real_extract(self, url):
  867. album_id = self._match_id(url)
  868. return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
  869. class VimeoGroupsIE(VimeoAlbumIE):
  870. IE_NAME = 'vimeo:group'
  871. _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
  872. _TESTS = [{
  873. 'url': 'https://vimeo.com/groups/rolexawards',
  874. 'info_dict': {
  875. 'id': 'rolexawards',
  876. 'title': 'Rolex Awards for Enterprise',
  877. },
  878. 'playlist_mincount': 73,
  879. }]
  880. def _extract_list_title(self, webpage):
  881. return self._og_search_title(webpage, fatal=False)
  882. def _real_extract(self, url):
  883. mobj = re.match(self._VALID_URL, url)
  884. name = mobj.group('name')
  885. return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
  886. class VimeoReviewIE(VimeoBaseInfoExtractor):
  887. IE_NAME = 'vimeo:review'
  888. IE_DESC = 'Review pages on vimeo'
  889. _VALID_URL = r'(?P<url>https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)/[0-9a-f]{10})'
  890. _TESTS = [{
  891. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  892. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  893. 'info_dict': {
  894. 'id': '75524534',
  895. 'ext': 'mp4',
  896. 'title': "DICK HARDWICK 'Comedian'",
  897. 'uploader': 'Richard Hardwick',
  898. 'uploader_id': 'user21297594',
  899. }
  900. }, {
  901. 'note': 'video player needs Referer',
  902. 'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
  903. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  904. 'info_dict': {
  905. 'id': '91613211',
  906. 'ext': 'mp4',
  907. 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
  908. 'uploader': 'DevWeek Events',
  909. 'duration': 2773,
  910. 'thumbnail': r're:^https?://.*\.jpg$',
  911. 'uploader_id': 'user22258446',
  912. }
  913. }, {
  914. 'note': 'Password protected',
  915. 'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
  916. 'info_dict': {
  917. 'id': '138823582',
  918. 'ext': 'mp4',
  919. 'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
  920. 'uploader': 'TMB',
  921. 'uploader_id': 'user37284429',
  922. },
  923. 'params': {
  924. 'videopassword': 'holygrail',
  925. },
  926. 'skip': 'video gone',
  927. }]
  928. def _real_initialize(self):
  929. self._login()
  930. def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
  931. webpage = self._download_webpage(webpage_url, video_id)
  932. config_url = self._html_search_regex(
  933. r'data-config-url=(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
  934. 'config URL', default=None, group='url')
  935. if not config_url:
  936. data = self._parse_json(self._search_regex(
  937. r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
  938. default=NO_DEFAULT if video_password_verified else '{}'), video_id)
  939. config = data.get('vimeo_esi', {}).get('config', {})
  940. config_url = config.get('configUrl') or try_get(config, lambda x: x['clipData']['configUrl'])
  941. if config_url is None:
  942. self._verify_video_password(webpage_url, video_id, webpage)
  943. config_url = self._get_config_url(
  944. webpage_url, video_id, video_password_verified=True)
  945. return config_url
  946. def _real_extract(self, url):
  947. page_url, video_id = re.match(self._VALID_URL, url).groups()
  948. config_url = self._get_config_url(url, video_id)
  949. config = self._download_json(config_url, video_id)
  950. info_dict = self._parse_config(config, video_id)
  951. source_format = self._extract_original_format(page_url, video_id)
  952. if source_format:
  953. info_dict['formats'].append(source_format)
  954. self._vimeo_sort_formats(info_dict['formats'])
  955. info_dict['id'] = video_id
  956. return info_dict
  957. class VimeoWatchLaterIE(VimeoChannelIE):
  958. IE_NAME = 'vimeo:watchlater'
  959. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  960. _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
  961. _TITLE = 'Watch Later'
  962. _LOGIN_REQUIRED = True
  963. _TESTS = [{
  964. 'url': 'https://vimeo.com/watchlater',
  965. 'only_matching': True,
  966. }]
  967. def _real_initialize(self):
  968. self._login()
  969. def _page_url(self, base_url, pagenum):
  970. url = '%s/page:%d/' % (base_url, pagenum)
  971. request = sanitized_Request(url)
  972. # Set the header to get a partial html page with the ids,
  973. # the normal page doesn't contain them.
  974. request.add_header('X-Requested-With', 'XMLHttpRequest')
  975. return request
  976. def _real_extract(self, url):
  977. return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
  978. class VimeoLikesIE(VimeoChannelIE):
  979. _VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
  980. IE_NAME = 'vimeo:likes'
  981. IE_DESC = 'Vimeo user likes'
  982. _TESTS = [{
  983. 'url': 'https://vimeo.com/user755559/likes/',
  984. 'playlist_mincount': 293,
  985. 'info_dict': {
  986. 'id': 'user755559',
  987. 'title': 'urza’s Likes',
  988. },
  989. }, {
  990. 'url': 'https://vimeo.com/stormlapse/likes',
  991. 'only_matching': True,
  992. }]
  993. def _page_url(self, base_url, pagenum):
  994. return '%s/page:%d/' % (base_url, pagenum)
  995. def _real_extract(self, url):
  996. user_id = self._match_id(url)
  997. return self._extract_videos(user_id, 'https://vimeo.com/%s/likes' % user_id)
  998. class VHXEmbedIE(InfoExtractor):
  999. IE_NAME = 'vhx:embed'
  1000. _VALID_URL = r'https?://embed\.vhx\.tv/videos/(?P<id>\d+)'
  1001. def _call_api(self, video_id, access_token, path='', query=None):
  1002. return self._download_json(
  1003. 'https://api.vhx.tv/videos/' + video_id + path, video_id, headers={
  1004. 'Authorization': 'Bearer ' + access_token,
  1005. }, query=query)
  1006. def _real_extract(self, url):
  1007. video_id = self._match_id(url)
  1008. webpage = self._download_webpage(url, video_id)
  1009. credentials = self._parse_json(self._search_regex(
  1010. r'(?s)credentials\s*:\s*({.+?}),', webpage,
  1011. 'config'), video_id, js_to_json)
  1012. access_token = credentials['access_token']
  1013. query = {}
  1014. for k, v in credentials.items():
  1015. if k in ('authorization', 'authUserToken', 'ticket') and v and v != 'undefined':
  1016. if k == 'authUserToken':
  1017. query['auth_user_token'] = v
  1018. else:
  1019. query[k] = v
  1020. files = self._call_api(video_id, access_token, '/files', query)
  1021. formats = []
  1022. for f in files:
  1023. href = try_get(f, lambda x: x['_links']['source']['href'])
  1024. if not href:
  1025. continue
  1026. method = f.get('method')
  1027. if method == 'hls':
  1028. formats.extend(self._extract_m3u8_formats(
  1029. href, video_id, 'mp4', 'm3u8_native',
  1030. m3u8_id='hls', fatal=False))
  1031. elif method == 'dash':
  1032. formats.extend(self._extract_mpd_formats(
  1033. href, video_id, mpd_id='dash', fatal=False))
  1034. else:
  1035. fmt = {
  1036. 'filesize': int_or_none(try_get(f, lambda x: x['size']['bytes'])),
  1037. 'format_id': 'http',
  1038. 'preference': 1,
  1039. 'url': href,
  1040. 'vcodec': f.get('codec'),
  1041. }
  1042. quality = f.get('quality')
  1043. if quality:
  1044. fmt.update({
  1045. 'format_id': 'http-' + quality,
  1046. 'height': int_or_none(self._search_regex(r'(\d+)p', quality, 'height', default=None)),
  1047. })
  1048. formats.append(fmt)
  1049. self._sort_formats(formats)
  1050. video_data = self._call_api(video_id, access_token)
  1051. title = video_data.get('title') or video_data['name']
  1052. subtitles = {}
  1053. for subtitle in try_get(video_data, lambda x: x['tracks']['subtitles'], list) or []:
  1054. lang = subtitle.get('srclang') or subtitle.get('label')
  1055. for _link in subtitle.get('_links', {}).values():
  1056. href = _link.get('href')
  1057. if not href:
  1058. continue
  1059. subtitles.setdefault(lang, []).append({
  1060. 'url': href,
  1061. })
  1062. q = qualities(['small', 'medium', 'large', 'source'])
  1063. thumbnails = []
  1064. for thumbnail_id, thumbnail_url in video_data.get('thumbnail', {}).items():
  1065. thumbnails.append({
  1066. 'id': thumbnail_id,
  1067. 'url': thumbnail_url,
  1068. 'preference': q(thumbnail_id),
  1069. })
  1070. return {
  1071. 'id': video_id,
  1072. 'title': title,
  1073. 'description': video_data.get('description'),
  1074. 'duration': int_or_none(try_get(video_data, lambda x: x['duration']['seconds'])),
  1075. 'formats': formats,
  1076. 'subtitles': subtitles,
  1077. 'thumbnails': thumbnails,
  1078. 'timestamp': unified_timestamp(video_data.get('created_at')),
  1079. 'view_count': int_or_none(video_data.get('plays_count')),
  1080. }