2
0

vimeo.py 47 KB

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