5 from .common
import InfoExtractor
21 class KalturaIE(InfoExtractor
):
24 kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)|
26 (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/
30 index\.php/(?:kwidget|extwidget/preview)|
32 html5/html5lib/[^/]+/mwEmbedFrame\.php
34 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
37 _SERVICE_URL
= 'http://cdnapi.kaltura.com'
38 _SERVICE_BASE
= '/api_v3/service/multirequest'
39 # See https://github.com/kaltura/server/blob/master/plugins/content/caption/base/lib/model/enums/CaptionType.php
47 'url': 'kaltura:269692:1_1jc2y3e4',
48 'md5': '3adcbdb3dcc02d647539e53f284ba171',
52 'title': 'Straight from the Heart',
53 'upload_date': '20131219',
54 'uploader_id': 'mlundberg@wolfgangsvault.com',
55 'description': 'The Allman Brothers Band, 12/16/1981',
56 'thumbnail': 're:^https?://.*/thumbnail/.*',
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,
115 def _extract_url(webpage
):
116 urls
= KalturaIE
._extract
_urls
(webpage
)
117 return urls
[0] if urls
else None
120 def _extract_urls(webpage
):
121 # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
125 kWidget\.(?:thumb)?[Ee]mbed\(
127 (?P<q1>['"])wid(?P=q1)\s*:\s*
128 (?P<q2>['"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
129 (?P<q3>['"])entry_?[Ii]d(?P=q3)\s*:\s*
130 (?P<q4>['"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
135 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
140 (?P<q2>["'])entry_?[Ii]d(?P=q2)
142 \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
144 (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
148 <(?:iframe[^>]+src|meta[^>]+\bcontent)=(?P<q1>["'])\s*
149 (?:https?:)?//(?:(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)
151 [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
157 for mobj
in finditer
:
158 embed_info
= mobj
.groupdict()
159 for k
, v
in embed_info
.items():
161 embed_info
[k
] = v
.strip()
162 url
= 'kaltura:%(partner_id)s:%(id)s' % embed_info
163 escaped_pid
= re
.escape(embed_info
['partner_id'])
164 service_mobj
= re
.search(
165 r
'<script[^>]+src=(["\'])(?P
<id>(?
:https?
:)?
//(?
:(?
!\
1).)+)/p
/%s/sp
/%s00/embedIframeJs
' % (escaped_pid, escaped_pid),
168 url = smuggle_url(url, {'service_url': service_mobj.group('id')})
172 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
174 params.update({i: a for i, a in enumerate(actions[1:], start=1)})
176 data = self._download_json(
177 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
178 video_id, data=json.dumps(params).encode('utf
-8'),
180 'Content
-Type
': 'application
/json
',
181 'Accept
-Encoding
': 'gzip
, deflate
, br
',
184 for idx, status in enumerate(data):
185 if not isinstance(status, dict):
187 if status.get('objectType
') == 'KalturaAPIException
':
188 raise ExtractorError(
189 '%s said
: %s (%d)' % (self.IE_NAME, status['message
'], idx))
191 data[1] = traverse_obj(data, (1, 'objects
', 0))
195 def _get_video_info(self, video_id, partner_id, service_url=None):
198 'apiVersion
': '3.3.0',
199 'clientTag
': 'html5
:v3
.1
.0',
200 'format
': 1, # JSON, 2 = XML, 3 = PHP
202 'partnerId
': partner_id,
206 'service
': 'session
',
207 'action
': 'startWidgetSession
',
208 'widgetId
': '_
%s' % partner_id,
212 'filter': {'redirectFromEntryId': video_id},
213 'service
': 'baseentry
',
214 'ks
': '{1:result:ks}
',
217 'fields
': 'createdAt
,dataUrl
,duration
,name
,plays
,thumbnailUrl
,userId
',
221 'action
': 'getbyentryid
',
223 'service
': 'flavorAsset
',
224 'ks
': '{1:result:ks}
',
228 'filter:entryIdEqual
': video_id,
229 'service
': 'caption_captionasset
',
230 'ks
': '{1:result:ks}
',
233 return self._kaltura_api_call(
234 video_id, actions, service_url, note='Downloading video info JSON
')
236 def _real_extract(self, url):
237 url, smuggled_data = unsmuggle_url(url, {})
239 mobj = self._match_valid_url(url)
240 partner_id, entry_id = mobj.group('partner_id
', 'id')
243 if partner_id and entry_id:
244 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url
'))
246 path, query = mobj.group('path
', 'query
')
247 if not path and not query:
248 raise ExtractorError('Invalid URL
', expected=True)
251 params = compat_parse_qs(query)
253 splitted_path = path.split('/')
254 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
256 partner_id = params['wid
'][0][1:]
258 partner_id = params['p
'][0]
259 elif 'partner_id
' in params:
260 partner_id = params['partner_id
'][0]
262 raise ExtractorError('Invalid URL
', expected=True)
263 if 'entry_id
' in params:
264 entry_id = params['entry_id
'][0]
265 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
266 elif 'uiconf_id
' in params and 'flashvars
[referenceId
]' in params:
267 reference_id = params['flashvars
[referenceId
]'][0]
268 webpage = self._download_webpage(url, reference_id)
269 entry_data = self._parse_json(self._search_regex(
270 r'window\
.kalturaIframePackageData\s
*=\s
*({.*}
);',
271 webpage, 'kalturaIframePackageData
'),
272 reference_id)['entryResult
']
273 info, flavor_assets = entry_data['meta
'], entry_data['contextData
']['flavorAssets
']
274 entry_id = info['id']
275 # Unfortunately, data returned in kalturaIframePackageData lacks
276 # captions so we will try requesting the complete data using
277 # regular approach since we now know the entry_id
279 _, info, flavor_assets, captions = self._get_video_info(
280 entry_id, partner_id)
281 except ExtractorError:
282 # Regular scenario failed but we already have everything
283 # extracted apart from captions and can process at least
287 raise ExtractorError('Invalid URL
', expected=True)
288 ks = params.get('flashvars
[ks
]', [None])[0]
290 source_url = smuggled_data.get('source_url
')
292 referrer = base64.b64encode(
293 '://'.join(compat_urlparse.urlparse(source_url)[:2])
294 .encode('utf
-8')).decode('utf
-8')
298 def sign_url(unsigned_url):
300 unsigned_url += '/ks
/%s' % ks
302 unsigned_url += '?referrer
=%s' % referrer
305 data_url = info['dataUrl
']
306 if '/flvclipper
/' in data_url:
307 data_url = re.sub(r'/flvclipper
/.*', '/serveFlavor
', data_url)
311 for f in flavor_assets:
312 # Continue if asset is not ready
313 if f.get('status
') != 2:
315 # Original format that's
not available (e
.g
. kaltura
:1926081:0_c
03e
1b
5g
)
317 if f
.get('fileExt') == 'chun':
319 # DRM-protected video, cannot be decrypted
320 if not self
.get_param('allow_unplayable_formats') and f
.get('fileExt') == 'wvm':
322 if not f
.get('fileExt'):
323 # QT indicates QuickTime; some videos have broken fileExt
324 if f
.get('containerFormat') == 'qt':
328 video_url
= sign_url(
329 '%s/flavorId/%s' % (data_url
, f
['id']))
330 format_id
= '%(fileExt)s-%(bitrate)s' % f
331 # Source format may not be available (e.g. kaltura:513551:1_66x4rg7o)
332 if f
.get('isOriginal') is True and not self
._is
_valid
_url
(
333 video_url
, entry_id
, format_id
):
335 # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
337 vcodec
= 'none' if 'videoCodecId' not in f
and f
.get(
338 'frameRate') == 0 else f
.get('videoCodecId')
340 'format_id': format_id
,
341 'ext': f
.get('fileExt'),
342 'tbr': int_or_none(f
['bitrate']),
343 'fps': int_or_none(f
.get('frameRate')),
344 'filesize_approx': int_or_none(f
.get('size'), invscale
=1024),
345 'container': f
.get('containerFormat'),
347 'height': int_or_none(f
.get('height')),
348 'width': int_or_none(f
.get('width')),
351 if '/playManifest/' in data_url
:
352 m3u8_url
= sign_url(data_url
.replace(
353 'format/url', 'format/applehttp'))
354 fmts
, subs
= self
._extract
_m
3u8_formats
_and
_subtitles
(
355 m3u8_url
, entry_id
, 'mp4', 'm3u8_native',
356 m3u8_id
='hls', fatal
=False)
358 self
._merge
_subtitles
(subs
, target
=subtitles
)
360 self
._sort
_formats
(formats
)
363 for caption
in captions
.get('objects', []):
364 # Continue if caption is not ready
365 if caption
.get('status') != 2:
367 if not caption
.get('id'):
369 caption_format
= int_or_none(caption
.get('format'))
370 subtitles
.setdefault(caption
.get('languageCode') or caption
.get('language'), []).append({
371 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self
._SERVICE
_URL
, caption
['id']),
372 'ext': caption
.get('fileExt') or self
._CAPTION
_TYPES
.get(caption_format
) or 'ttml',
377 'title': info
['name'],
379 'subtitles': subtitles
,
380 'description': clean_html(info
.get('description')),
381 'thumbnail': info
.get('thumbnailUrl'),
382 'duration': info
.get('duration'),
383 'timestamp': info
.get('createdAt'),
384 'uploader_id': format_field(info
, 'userId', ignore
=('None', None)),
385 'view_count': info
.get('plays'),