Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1200 lines
48KB

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