kaltura.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import base64
  2. import contextlib
  3. import json
  4. import re
  5. import urllib.parse
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. ExtractorError,
  9. clean_html,
  10. format_field,
  11. int_or_none,
  12. remove_start,
  13. smuggle_url,
  14. traverse_obj,
  15. unsmuggle_url,
  16. )
  17. class KalturaIE(InfoExtractor):
  18. _VALID_URL = r'''(?x)
  19. (?:
  20. kaltura:(?P<partner_id>\w+):(?P<id>\w+)(?::(?P<player_type>\w+))?|
  21. https?://
  22. (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/
  23. (?:
  24. (?:
  25. # flash player
  26. index\.php/(?:kwidget|extwidget/preview)|
  27. # html5 player
  28. html5/html5lib/[^/]+/mwEmbedFrame\.php
  29. )
  30. )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
  31. )
  32. '''
  33. _SERVICE_URL = 'http://cdnapi.kaltura.com'
  34. _SERVICE_BASE = '/api_v3/service/multirequest'
  35. # See https://github.com/kaltura/server/blob/master/plugins/content/caption/base/lib/model/enums/CaptionType.php
  36. _CAPTION_TYPES = {
  37. 1: 'srt',
  38. 2: 'ttml',
  39. 3: 'vtt',
  40. }
  41. _TESTS = [
  42. {
  43. 'url': 'kaltura:269692:1_1jc2y3e4',
  44. 'md5': '3adcbdb3dcc02d647539e53f284ba171',
  45. 'info_dict': {
  46. 'id': '1_1jc2y3e4',
  47. 'ext': 'mp4',
  48. 'title': 'Straight from the Heart',
  49. 'upload_date': '20131219',
  50. 'uploader_id': 'mlundberg@wolfgangsvault.com',
  51. 'description': 'The Allman Brothers Band, 12/16/1981',
  52. 'thumbnail': 're:^https?://.*/thumbnail/.*',
  53. 'timestamp': int,
  54. },
  55. 'skip': 'The access to this service is forbidden since the specified partner is blocked',
  56. },
  57. {
  58. 'url': 'http://www.kaltura.com/index.php/kwidget/cache_st/1300318621/wid/_269692/uiconf_id/3873291/entry_id/1_1jc2y3e4',
  59. 'only_matching': True,
  60. },
  61. {
  62. 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
  63. 'only_matching': True,
  64. },
  65. {
  66. 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.30.2/mwEmbedFrame.php/p/1337/uiconf_id/20540612/entry_id/1_sf5ovm7u?wid=_243342',
  67. 'only_matching': True,
  68. },
  69. {
  70. # video with subtitles
  71. 'url': 'kaltura:111032:1_cw786r8q',
  72. 'only_matching': True,
  73. },
  74. {
  75. # video with ttml subtitles (no fileExt)
  76. 'url': 'kaltura:1926081:0_l5ye1133',
  77. 'info_dict': {
  78. 'id': '0_l5ye1133',
  79. 'ext': 'mp4',
  80. 'title': 'What Can You Do With Python?',
  81. 'upload_date': '20160221',
  82. 'uploader_id': 'stork',
  83. 'thumbnail': 're:^https?://.*/thumbnail/.*',
  84. 'timestamp': int,
  85. 'subtitles': {
  86. 'en': [{
  87. 'ext': 'ttml',
  88. }],
  89. },
  90. },
  91. 'skip': 'Gone. Maybe https://www.safaribooksonline.com/library/tutorials/introduction-to-python-anon/3469/',
  92. 'params': {
  93. 'skip_download': True,
  94. },
  95. },
  96. {
  97. 'url': 'https://www.kaltura.com/index.php/extwidget/preview/partner_id/1770401/uiconf_id/37307382/entry_id/0_58u8kme7/embed/iframe?&flashvars[streamerType]=auto',
  98. 'only_matching': True,
  99. },
  100. {
  101. 'url': 'https://www.kaltura.com:443/index.php/extwidget/preview/partner_id/1770401/uiconf_id/37307382/entry_id/0_58u8kme7/embed/iframe?&flashvars[streamerType]=auto',
  102. 'only_matching': True,
  103. },
  104. {
  105. # unavailable source format
  106. 'url': 'kaltura:513551:1_66x4rg7o',
  107. 'only_matching': True,
  108. },
  109. {
  110. # html5lib URL using kwidget player
  111. 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.46/mwEmbedFrame.php/p/691292/uiconf_id/20499062/entry_id/0_c076mna6?wid=_691292&iframeembed=true&playerId=kaltura_player_1420508608&entry_id=0_c076mna6&flashvars%5BakamaiHD.loadingPolicy%5D=preInitialize&flashvars%5BakamaiHD.asyncInit%5D=true&flashvars%5BstreamerType%5D=hdnetwork',
  112. 'info_dict': {
  113. 'id': '0_c076mna6',
  114. 'ext': 'mp4',
  115. 'title': 'md5:4883e7acbcbf42583a2dddc97dee4855',
  116. 'duration': 3608,
  117. 'uploader_id': 'commons@swinburne.edu.au',
  118. 'timestamp': 1408086874,
  119. 'view_count': int,
  120. 'upload_date': '20140815',
  121. 'thumbnail': 'http://cfvod.kaltura.com/p/691292/sp/69129200/thumbnail/entry_id/0_c076mna6/version/100022',
  122. },
  123. },
  124. {
  125. # html5lib playlist URL using kwidget player
  126. 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.89/mwEmbedFrame.php/p/2019031/uiconf_id/40436601?wid=1_4j3m32cv&iframeembed=true&playerId=kaltura_player_&flashvars[playlistAPI.kpl0Id]=1_jovey5nu&flashvars[ks]=&&flashvars[imageDefaultDuration]=30&flashvars[localizationCode]=en&flashvars[leadWithHTML5]=true&flashvars[forceMobileHTML5]=true&flashvars[nextPrevBtn.plugin]=true&flashvars[hotspots.plugin]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&flashvars[playlistAPI.playlistUrl]=https://canvasgatechtest.kaf.kaltura.com/playlist/details/{playlistAPI.kpl0Id}/categoryid/126428551',
  127. 'info_dict': {
  128. 'id': '1_jovey5nu',
  129. 'title': '00-00 Introduction',
  130. },
  131. 'playlist': [
  132. {
  133. 'info_dict': {
  134. 'id': '1_b1y5hlvx',
  135. 'ext': 'mp4',
  136. 'title': 'CS7646_00-00 Introductio_Introduction',
  137. 'duration': 91,
  138. 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_b1y5hlvx/version/100001',
  139. 'view_count': int,
  140. 'timestamp': 1533154447,
  141. 'upload_date': '20180801',
  142. 'uploader_id': 'djoyner3',
  143. },
  144. }, {
  145. 'info_dict': {
  146. 'id': '1_jfb7mdpn',
  147. 'ext': 'mp4',
  148. 'title': 'CS7646_00-00 Introductio_Three parts to the course',
  149. 'duration': 63,
  150. 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_jfb7mdpn/version/100001',
  151. 'view_count': int,
  152. 'timestamp': 1533154489,
  153. 'upload_date': '20180801',
  154. 'uploader_id': 'djoyner3',
  155. },
  156. }, {
  157. 'info_dict': {
  158. 'id': '1_8xflxdp7',
  159. 'ext': 'mp4',
  160. 'title': 'CS7646_00-00 Introductio_Textbooks',
  161. 'duration': 37,
  162. 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_8xflxdp7/version/100001',
  163. 'view_count': int,
  164. 'timestamp': 1533154512,
  165. 'upload_date': '20180801',
  166. 'uploader_id': 'djoyner3',
  167. },
  168. }, {
  169. 'info_dict': {
  170. 'id': '1_3hqew8kn',
  171. 'ext': 'mp4',
  172. 'title': 'CS7646_00-00 Introductio_Prerequisites',
  173. 'duration': 49,
  174. 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_3hqew8kn/version/100001',
  175. 'view_count': int,
  176. 'timestamp': 1533154536,
  177. 'upload_date': '20180801',
  178. 'uploader_id': 'djoyner3',
  179. },
  180. },
  181. ],
  182. },
  183. ]
  184. @classmethod
  185. def _extract_embed_urls(cls, url, webpage):
  186. # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
  187. finditer = (
  188. list(re.finditer(
  189. r'''(?xs)
  190. kWidget\.(?:thumb)?[Ee]mbed\(
  191. \{.*?
  192. (?P<q1>['"])wid(?P=q1)\s*:\s*
  193. (?P<q2>['"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
  194. (?P<q3>['"])entry_?[Ii]d(?P=q3)\s*:\s*
  195. (?P<q4>['"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
  196. ''', webpage))
  197. or list(re.finditer(
  198. r'''(?xs)
  199. (?P<q1>["'])
  200. (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
  201. (?P=q1).*?
  202. (?:
  203. (?:
  204. entry_?[Ii]d|
  205. (?P<q2>["'])entry_?[Ii]d(?P=q2)
  206. )\s*:\s*|
  207. \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
  208. )
  209. (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
  210. ''', webpage))
  211. or list(re.finditer(
  212. r'''(?xs)
  213. <(?:iframe[^>]+src|meta[^>]+\bcontent)=(?P<q1>["'])\s*
  214. (?:https?:)?//(?:(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)
  215. (?:(?!(?P=q1)).)*
  216. [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
  217. (?:(?!(?P=q1)).)*
  218. (?P=q1)
  219. ''', webpage))
  220. )
  221. urls = []
  222. for mobj in finditer:
  223. embed_info = mobj.groupdict()
  224. for k, v in embed_info.items():
  225. if v:
  226. embed_info[k] = v.strip()
  227. embed_url = 'kaltura:{partner_id}:{id}'.format(**embed_info)
  228. escaped_pid = re.escape(embed_info['partner_id'])
  229. service_mobj = re.search(
  230. rf'<script[^>]+src=(["\'])(?P<id>(?:https?:)?//(?:(?!\1).)+)/p/{escaped_pid}/sp/{escaped_pid}00/embedIframeJs',
  231. webpage)
  232. if service_mobj:
  233. embed_url = smuggle_url(embed_url, {'service_url': service_mobj.group('id')})
  234. urls.append(embed_url)
  235. return urls
  236. def _kaltura_api_call(self, video_id, actions, service_url=None, **kwargs):
  237. params = actions[0]
  238. params.update(dict(enumerate(actions[1:], start=1)))
  239. data = self._download_json(
  240. (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
  241. video_id, data=json.dumps(params).encode(),
  242. headers={
  243. 'Content-Type': 'application/json',
  244. 'Accept-Encoding': 'gzip, deflate, br',
  245. }, **kwargs)
  246. for idx, status in enumerate(data):
  247. if not isinstance(status, dict):
  248. continue
  249. if status.get('objectType') == 'KalturaAPIException':
  250. raise ExtractorError(
  251. '{} said: {} ({})'.format(self.IE_NAME, status['message'], idx))
  252. data[1] = traverse_obj(data, (1, 'objects', 0))
  253. return data
  254. def _get_video_info(self, video_id, partner_id, service_url=None, player_type='html5'):
  255. assert player_type in ('html5', 'kwidget')
  256. if player_type == 'kwidget':
  257. return self._get_video_info_kwidget(video_id, partner_id, service_url)
  258. return self._get_video_info_html5(video_id, partner_id, service_url)
  259. def _get_video_info_html5(self, video_id, partner_id, service_url=None):
  260. actions = [
  261. {
  262. 'apiVersion': '3.3.0',
  263. 'clientTag': 'html5:v3.1.0',
  264. 'format': 1, # JSON, 2 = XML, 3 = PHP
  265. 'ks': '',
  266. 'partnerId': partner_id,
  267. },
  268. {
  269. 'expiry': 86400,
  270. 'service': 'session',
  271. 'action': 'startWidgetSession',
  272. 'widgetId': self._build_widget_id(partner_id),
  273. },
  274. # info
  275. {
  276. 'action': 'list',
  277. 'filter': {'redirectFromEntryId': video_id},
  278. 'service': 'baseentry',
  279. 'ks': '{1:result:ks}',
  280. 'responseProfile': {
  281. 'type': 1,
  282. 'fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId',
  283. },
  284. },
  285. # flavor_assets
  286. {
  287. 'action': 'getbyentryid',
  288. 'entryId': video_id,
  289. 'service': 'flavorAsset',
  290. 'ks': '{1:result:ks}',
  291. },
  292. # captions
  293. {
  294. 'action': 'list',
  295. 'filter:entryIdEqual': video_id,
  296. 'service': 'caption_captionasset',
  297. 'ks': '{1:result:ks}',
  298. },
  299. ]
  300. return self._kaltura_api_call(
  301. video_id, actions, service_url, note='Downloading video info JSON (Kaltura html5 player)')
  302. def _get_video_info_kwidget(self, video_id, partner_id, service_url=None):
  303. actions = [
  304. {
  305. 'service': 'multirequest',
  306. 'apiVersion': '3.1',
  307. 'expiry': 86400,
  308. 'clientTag': 'kwidget:v2.89',
  309. 'format': 1, # JSON, 2 = XML, 3 = PHP
  310. 'ignoreNull': 1,
  311. 'action': 'null',
  312. },
  313. # header
  314. {
  315. 'expiry': 86400,
  316. 'service': 'session',
  317. 'action': 'startWidgetSession',
  318. 'widgetId': self._build_widget_id(partner_id),
  319. },
  320. # (empty)
  321. {
  322. 'expiry': 86400,
  323. 'service': 'session',
  324. 'action': 'startwidgetsession',
  325. 'widgetId': self._build_widget_id(partner_id),
  326. 'format': 9,
  327. 'apiVersion': '3.1',
  328. 'clientTag': 'kwidget:v2.89',
  329. 'ignoreNull': 1,
  330. 'ks': '{1:result:ks}',
  331. },
  332. # info
  333. {
  334. 'action': 'list',
  335. 'filter': {'redirectFromEntryId': video_id},
  336. 'service': 'baseentry',
  337. 'ks': '{1:result:ks}',
  338. 'responseProfile': {
  339. 'type': 1,
  340. 'fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId',
  341. },
  342. },
  343. # flavor_assets
  344. {
  345. 'action': 'getbyentryid',
  346. 'entryId': video_id,
  347. 'service': 'flavorAsset',
  348. 'ks': '{1:result:ks}',
  349. },
  350. # captions
  351. {
  352. 'action': 'list',
  353. 'filter:entryIdEqual': video_id,
  354. 'service': 'caption_captionasset',
  355. 'ks': '{1:result:ks}',
  356. },
  357. ]
  358. # second object (representing the second start widget session) is None
  359. header, _, _info, flavor_assets, captions = self._kaltura_api_call(
  360. video_id, actions, service_url, note='Downloading video info JSON (Kaltura kwidget player)')
  361. info = _info['objects'][0]
  362. return header, info, flavor_assets, captions
  363. def _build_widget_id(self, partner_id):
  364. return partner_id if '_' in partner_id else f'_{partner_id}'
  365. IFRAME_PACKAGE_DATA_REGEX = r'window\.kalturaIframePackageData\s*='
  366. def _real_extract(self, url):
  367. url, smuggled_data = unsmuggle_url(url, {})
  368. mobj = self._match_valid_url(url)
  369. partner_id, entry_id, player_type = mobj.group('partner_id', 'id', 'player_type')
  370. ks, captions = None, None
  371. if not player_type:
  372. player_type = 'kwidget' if 'html5lib/v2' in url else 'html5'
  373. if partner_id and entry_id:
  374. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'), player_type=player_type)
  375. else:
  376. path, query = mobj.group('path', 'query')
  377. if not path and not query:
  378. raise ExtractorError('Invalid URL', expected=True)
  379. params = {}
  380. if query:
  381. params = urllib.parse.parse_qs(query)
  382. if path:
  383. splitted_path = path.split('/')
  384. params.update(dict(zip(splitted_path[::2], [[v] for v in splitted_path[1::2]])))
  385. if 'wid' in params:
  386. partner_id = remove_start(params['wid'][0], '_')
  387. elif 'p' in params:
  388. partner_id = params['p'][0]
  389. elif 'partner_id' in params:
  390. partner_id = params['partner_id'][0]
  391. else:
  392. raise ExtractorError('Invalid URL', expected=True)
  393. if 'entry_id' in params:
  394. entry_id = params['entry_id'][0]
  395. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, player_type=player_type)
  396. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  397. reference_id = params['flashvars[referenceId]'][0]
  398. webpage = self._download_webpage(url, reference_id)
  399. entry_data = self._search_json(
  400. self.IFRAME_PACKAGE_DATA_REGEX, webpage,
  401. 'kalturaIframePackageData', reference_id)['entryResult']
  402. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  403. entry_id = info['id']
  404. # Unfortunately, data returned in kalturaIframePackageData lacks
  405. # captions so we will try requesting the complete data using
  406. # regular approach since we now know the entry_id
  407. # Even if this fails we already have everything extracted
  408. # apart from captions and can process at least with this
  409. with contextlib.suppress(ExtractorError):
  410. _, info, flavor_assets, captions = self._get_video_info(
  411. entry_id, partner_id, player_type=player_type)
  412. elif 'uiconf_id' in params and 'flashvars[playlistAPI.kpl0Id]' in params:
  413. playlist_id = params['flashvars[playlistAPI.kpl0Id]'][0]
  414. webpage = self._download_webpage(url, playlist_id)
  415. playlist_data = self._search_json(
  416. self.IFRAME_PACKAGE_DATA_REGEX, webpage,
  417. 'kalturaIframePackageData', playlist_id)['playlistResult']
  418. return self.playlist_from_matches(
  419. traverse_obj(playlist_data, (playlist_id, 'items', ..., 'id')),
  420. playlist_id, traverse_obj(playlist_data, (playlist_id, 'name')),
  421. ie=KalturaIE, getter=lambda x: f'kaltura:{partner_id}:{x}:{player_type}')
  422. else:
  423. raise ExtractorError('Invalid URL', expected=True)
  424. ks = params.get('flashvars[ks]', [None])[0]
  425. return self._per_video_extract(smuggled_data, entry_id, info, ks, flavor_assets, captions)
  426. def _per_video_extract(self, smuggled_data, entry_id, info, ks, flavor_assets, captions):
  427. source_url = smuggled_data.get('source_url')
  428. if source_url:
  429. referrer = base64.b64encode(
  430. '://'.join(urllib.parse.urlparse(source_url)[:2])
  431. .encode()).decode('utf-8')
  432. else:
  433. referrer = None
  434. def sign_url(unsigned_url):
  435. if ks:
  436. unsigned_url += f'/ks/{ks}'
  437. if referrer:
  438. unsigned_url += f'?referrer={referrer}'
  439. return unsigned_url
  440. data_url = info['dataUrl']
  441. if '/flvclipper/' in data_url:
  442. data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
  443. formats = []
  444. subtitles = {}
  445. for f in flavor_assets:
  446. # Continue if asset is not ready
  447. if f.get('status') != 2:
  448. continue
  449. # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
  450. # skip for now.
  451. if f.get('fileExt') == 'chun':
  452. continue
  453. # DRM-protected video, cannot be decrypted
  454. if not self.get_param('allow_unplayable_formats') and f.get('fileExt') == 'wvm':
  455. continue
  456. if not f.get('fileExt'):
  457. # QT indicates QuickTime; some videos have broken fileExt
  458. if f.get('containerFormat') == 'qt':
  459. f['fileExt'] = 'mov'
  460. else:
  461. f['fileExt'] = 'mp4'
  462. video_url = sign_url(
  463. '{}/flavorId/{}'.format(data_url, f['id']))
  464. format_id = '{fileExt}-{bitrate}'.format(**f)
  465. # Source format may not be available (e.g. kaltura:513551:1_66x4rg7o)
  466. if f.get('isOriginal') is True and not self._is_valid_url(
  467. video_url, entry_id, format_id):
  468. continue
  469. # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
  470. # -f mp4-56)
  471. vcodec = 'none' if 'videoCodecId' not in f and f.get(
  472. 'frameRate') == 0 else f.get('videoCodecId')
  473. formats.append({
  474. 'format_id': format_id,
  475. 'ext': f.get('fileExt'),
  476. 'tbr': int_or_none(f['bitrate']),
  477. 'fps': int_or_none(f.get('frameRate')),
  478. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  479. 'container': f.get('containerFormat'),
  480. 'vcodec': vcodec,
  481. 'height': int_or_none(f.get('height')),
  482. 'width': int_or_none(f.get('width')),
  483. 'url': video_url,
  484. })
  485. if '/playManifest/' in data_url:
  486. m3u8_url = sign_url(data_url.replace(
  487. 'format/url', 'format/applehttp'))
  488. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  489. m3u8_url, entry_id, 'mp4', 'm3u8_native',
  490. m3u8_id='hls', fatal=False)
  491. formats.extend(fmts)
  492. self._merge_subtitles(subs, target=subtitles)
  493. if captions:
  494. for caption in captions.get('objects', []):
  495. # Continue if caption is not ready
  496. if caption.get('status') != 2:
  497. continue
  498. if not caption.get('id'):
  499. continue
  500. caption_format = int_or_none(caption.get('format'))
  501. subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
  502. 'url': '{}/api_v3/service/caption_captionasset/action/serve/captionAssetId/{}'.format(self._SERVICE_URL, caption['id']),
  503. 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
  504. })
  505. return {
  506. 'id': entry_id,
  507. 'title': info['name'],
  508. 'formats': formats,
  509. 'subtitles': subtitles,
  510. 'description': clean_html(info.get('description')),
  511. 'thumbnail': info.get('thumbnailUrl'),
  512. 'duration': info.get('duration'),
  513. 'timestamp': info.get('createdAt'),
  514. 'uploader_id': format_field(info, 'userId', ignore=('None', None)),
  515. 'view_count': int_or_none(info.get('plays')),
  516. }