7 from .common
import InfoExtractor
20 class KalturaIE(InfoExtractor
):
23 kaltura:(?P<partner_id>\w+):(?P<id>\w+)(?::(?P<player_type>\w+))?|
25 (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/
29 index\.php/(?:kwidget|extwidget/preview)|
31 html5/html5lib/[^/]+/mwEmbedFrame\.php
33 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
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
46 'url': 'kaltura:269692:1_1jc2y3e4',
47 'md5': '3adcbdb3dcc02d647539e53f284ba171',
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/.*',
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',
83 'title': 'What Can You Do With Python?',
84 'upload_date': '20160221',
85 'uploader_id': 'stork',
86 'thumbnail': 're:^https?://.*/thumbnail/.*',
94 'skip': 'Gone. Maybe https://www.safaribooksonline.com/library/tutorials/introduction-to-python-anon/3469/',
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',
118 'title': 'md5:4883e7acbcbf42583a2dddc97dee4855',
120 'uploader_id': 'commons@swinburne.edu.au',
121 'timestamp': 1408086874,
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',
132 'title': '00-00 Introduction',
139 'title': 'CS7646_00-00 Introductio_Introduction',
141 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_b1y5hlvx/version/100001',
143 'timestamp': 1533154447,
144 'upload_date': '20180801',
145 'uploader_id': 'djoyner3',
151 'title': 'CS7646_00-00 Introductio_Three parts to the course',
153 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_jfb7mdpn/version/100001',
155 'timestamp': 1533154489,
156 'upload_date': '20180801',
157 'uploader_id': 'djoyner3',
163 'title': 'CS7646_00-00 Introductio_Textbooks',
165 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_8xflxdp7/version/100001',
167 'timestamp': 1533154512,
168 'upload_date': '20180801',
169 'uploader_id': 'djoyner3',
175 'title': 'CS7646_00-00 Introductio_Prerequisites',
177 'thumbnail': 'http://cfvod.kaltura.com/p/2019031/sp/201903100/thumbnail/entry_id/1_3hqew8kn/version/100001',
179 'timestamp': 1533154536,
180 'upload_date': '20180801',
181 'uploader_id': 'djoyner3',
189 def _extract_embed_urls(cls
, url
, webpage
):
190 # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
194 kWidget\.(?:thumb)?[Ee]mbed\(
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*\})
204 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
209 (?P<q2>["'])entry_?[Ii]d(?P=q2)
211 \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
213 (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
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+)
220 [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
226 for mobj
in finditer
:
227 embed_info
= mobj
.groupdict()
228 for k
, v
in embed_info
.items():
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',
237 embed_url
= smuggle_url(embed_url
, {'service_url': service_mobj
.group('id')})
238 urls
.append(embed_url
)
241 def _kaltura_api_call(self
, video_id
, actions
, service_url
=None, **kwargs
):
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(),
249 'Content-Type': 'application/json',
250 'Accept-Encoding': 'gzip, deflate, br',
253 for idx
, status
in enumerate(data
):
254 if not isinstance(status
, dict):
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))
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
_html
5(video_id
, partner_id
, service_url
)
271 def _get_video_info_html5(self
, video_id
, partner_id
, service_url
=None):
274 'apiVersion': '3.3.0',
275 'clientTag': 'html5:v3.1.0',
276 'format': 1, # JSON, 2 = XML, 3 = PHP
278 'partnerId': partner_id
,
282 'service': 'session',
283 'action': 'startWidgetSession',
284 'widgetId': self
._build
_widget
_id
(partner_id
),
289 'filter': {'redirectFromEntryId': video_id
},
290 'service': 'baseentry',
291 'ks': '{1:result:ks}',
294 'fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId',
299 'action': 'getbyentryid',
301 'service': 'flavorAsset',
302 'ks': '{1:result:ks}',
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):
318 'service': 'multirequest',
321 'clientTag': 'kwidget:v2.89',
322 'format': 1, # JSON, 2 = XML, 3 = PHP
329 'service': 'session',
330 'action': 'startWidgetSession',
331 'widgetId': self
._build
_widget
_id
(partner_id
),
336 'service': 'session',
337 'action': 'startwidgetsession',
338 'widgetId': self
._build
_widget
_id
(partner_id
),
341 'clientTag': 'kwidget:v2.89',
343 'ks': '{1:result:ks}',
348 'filter': {'redirectFromEntryId': video_id
},
349 'service': 'baseentry',
350 'ks': '{1:result:ks}',
353 'fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId',
358 'action': 'getbyentryid',
360 'service': 'flavorAsset',
361 'ks': '{1:result:ks}',
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
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
)
393 path
, query
= mobj
.group('path', 'query')
394 if not path
and not query
:
395 raise ExtractorError('Invalid URL', expected
=True)
398 params
= urllib
.parse
.parse_qs(query
)
400 splitted_path
= path
.split('/')
401 params
.update(dict(zip(splitted_path
[::2], [[v
] for v
in splitted_path
[1::2]])))
403 partner_id
= remove_start(params
['wid'][0], '_')
405 partner_id
= params
['p'][0]
406 elif 'partner_id' in params
:
407 partner_id
= params
['partner_id'][0]
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}')
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')
448 referrer
= base64
.b64encode(
449 '://'.join(urllib
.parse
.urlparse(source_url
)[:2])
450 .encode()).decode('utf-8')
454 def sign_url(unsigned_url
):
456 unsigned_url
+= f
'/ks/{ks}'
458 unsigned_url
+= f
'?referrer={referrer}'
461 data_url
= info
['dataUrl']
462 if '/flvclipper/' in data_url
:
463 data_url
= re
.sub(r
'/flvclipper/.*', '/serveFlavor', data_url
)
467 for f
in flavor_assets
:
468 # Continue if asset is not ready
469 if f
.get('status') != 2:
471 # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
473 if f
.get('fileExt') == 'chun':
475 # DRM-protected video, cannot be decrypted
476 if not self
.get_param('allow_unplayable_formats') and f
.get('fileExt') == 'wvm':
478 if not f
.get('fileExt'):
479 # QT indicates QuickTime; some videos have broken fileExt
480 if f
.get('containerFormat') == 'qt':
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
):
491 # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
493 vcodec
= 'none' if 'videoCodecId' not in f
and f
.get(
494 'frameRate') == 0 else f
.get('videoCodecId')
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'),
503 'height': int_or_none(f
.get('height')),
504 'width': int_or_none(f
.get('width')),
507 if '/playManifest/' in data_url
:
508 m3u8_url
= sign_url(data_url
.replace(
509 'format/url', 'format/applehttp'))
510 fmts
, subs
= self
._extract
_m
3u8_formats
_and
_subtitles
(
511 m3u8_url
, entry_id
, 'mp4', 'm3u8_native',
512 m3u8_id
='hls', fatal
=False)
514 self
._merge
_subtitles
(subs
, target
=subtitles
)
517 for caption
in captions
.get('objects', []):
518 # Continue if caption is not ready
519 if caption
.get('status') != 2:
521 if not caption
.get('id'):
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',
531 'title': info
['name'],
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')),