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