kaltura.py 24 KB

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