2 from __future__ import unicode_literals
7 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/index.php'
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,
110 def _extract_url(webpage):
111 # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
115 kWidget\.(?:thumb)?[Ee]mbed\(
117 (?P<q1>['"])wid(?P=q1)\s*:\s*
118 (?P<q2>['"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
119 (?P<q3>['"])entry_?[Ii]d(?P=q3)\s*:\s*
120 (?P<q4>['"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
125 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
130 (?P<q2>["'])entry_?[Ii]d(?P=q2)
132 \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
134 (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
138 <iframe[^>]+src=(?P<q1>["'])
139 (?:https?:)?//(?:www\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)
141 [?&]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
146 embed_info = mobj.groupdict()
147 url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
148 escaped_pid = re.escape(embed_info['partner_id'])
149 service_url = re.search(
150 r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
153 url = smuggle_url(url, {'service_url': service_url.group(1)})
156 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
159 for i, a in enumerate(actions[1:], start=1):
160 for k, v in a.items():
161 params['%d:%s' % (i, k)] = v
163 data = self._download_json(
164 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
165 video_id, query=params, *args, **kwargs)
167 status = data if len(actions) == 1 else data[0]
168 if status.get('objectType') == 'KalturaAPIException':
169 raise ExtractorError(
170 '%s said: %s' % (self.IE_NAME, status['message']))
174 def _get_video_info(self, video_id, partner_id, service_url=None):
178 'apiVersion': '3.1.5',
179 'clientTag': 'kdp:v3.8.5',
180 'format': 1, # JSON, 2 = XML, 3 = PHP
181 'service': 'multirequest',
185 'service': 'session',
186 'action': 'startWidgetSession',
187 'widgetId': '_%s' % partner_id,
192 'service': 'baseentry',
193 'ks': '{1:result:ks}',
196 'action': 'getbyentryid',
198 'service': 'flavorAsset',
199 'ks': '{1:result:ks}',
203 'filter:entryIdEqual': video_id,
204 'service': 'caption_captionasset',
205 'ks': '{1:result:ks}',
208 return self._kaltura_api_call(
209 video_id, actions, service_url, note='Downloading video info JSON')
211 def _real_extract(self, url):
212 url, smuggled_data = unsmuggle_url(url, {})
214 mobj = re.match(self._VALID_URL, url)
215 partner_id, entry_id = mobj.group('partner_id', 'id')
218 if partner_id and entry_id:
219 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
221 path, query = mobj.group('path', 'query')
222 if not path and not query:
223 raise ExtractorError('Invalid URL', expected=True)
226 params = compat_parse_qs(query)
228 splitted_path = path.split('/')
229 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
231 partner_id = params['wid'][0][1:]
233 partner_id = params['p'][0]
234 elif 'partner_id' in params:
235 partner_id = params['partner_id'][0]
237 raise ExtractorError('Invalid URL', expected=True)
238 if 'entry_id' in params:
239 entry_id = params['entry_id'][0]
240 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
241 elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
242 reference_id = params['flashvars[referenceId]'][0]
243 webpage = self._download_webpage(url, reference_id)
244 entry_data = self._parse_json(self._search_regex(
245 r'window\.kalturaIframePackageData\s*=\s*({.*});',
246 webpage, 'kalturaIframePackageData'),
247 reference_id)['entryResult']
248 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
249 entry_id = info['id']
250 # Unfortunately, data returned in kalturaIframePackageData lacks
251 # captions so we will try requesting the complete data using
252 # regular approach since we now know the entry_id
254 _, info, flavor_assets, captions = self._get_video_info(
255 entry_id, partner_id)
256 except ExtractorError:
257 # Regular scenario failed but we already have everything
258 # extracted apart from captions and can process at least
262 raise ExtractorError('Invalid URL', expected=True)
263 ks = params.get('flashvars[ks]', [None])[0]
265 source_url = smuggled_data.get('source_url')
267 referrer = base64.b64encode(
268 '://'.join(compat_urlparse.urlparse(source_url)[:2])
269 .encode('utf-8')).decode('utf-8')
273 def sign_url(unsigned_url):
275 unsigned_url += '/ks/%s' % ks
277 unsigned_url += '?referrer=%s' % referrer
280 data_url = info['dataUrl']
281 if '/flvclipper/' in data_url:
282 data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
285 for f in flavor_assets:
286 # Continue if asset is not ready
287 if f.get('status') != 2:
289 # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
291 if f.get('fileExt') == 'chun':
293 # DRM-protected video, cannot be decrypted
294 if f.get('fileExt') == 'wvm':
296 if not f.get('fileExt'):
297 # QT indicates QuickTime; some videos have broken fileExt
298 if f.get('containerFormat') == 'qt':
302 video_url = sign_url(
303 '%s/flavorId/%s' % (data_url, f['id']))
304 # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
306 vcodec = 'none' if 'videoCodecId' not in f and f.get(
307 'frameRate') == 0 else f.get('videoCodecId')
309 'format_id': '%(fileExt)s-%(bitrate)s' % f,
310 'ext': f.get('fileExt'),
311 'tbr': int_or_none(f['bitrate']),
312 'fps': int_or_none(f.get('frameRate')),
313 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
314 'container': f.get('containerFormat'),
316 'height': int_or_none(f.get('height')),
317 'width': int_or_none(f.get('width')),
320 if '/playManifest/' in data_url:
321 m3u8_url = sign_url(data_url.replace(
322 'format/url', 'format/applehttp'))
323 formats.extend(self._extract_m3u8_formats(
324 m3u8_url, entry_id, 'mp4', 'm3u8_native',
325 m3u8_id='hls', fatal=False))
327 self._sort_formats(formats)
331 for caption in captions.get('objects', []):
332 # Continue if caption is not ready
333 if caption.get('status') != 2:
335 if not caption.get('id'):
337 caption_format = int_or_none(caption.get('format'))
338 subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
339 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
340 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
345 'title': info['name'],
347 'subtitles': subtitles,
348 'description': clean_html(info.get('description')),
349 'thumbnail': info.get('thumbnailUrl'),
350 'duration': info.get('duration'),
351 'timestamp': info.get('createdAt'),
352 'uploader_id': info.get('userId') if info.get('userId') != 'None' else None,
353 'view_count': info.get('plays'),