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/
32 html5/html5lib/[^/]+/mwEmbedFrame\.php
34 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
37 _SERVICE_URL = 'http://cdnapi.kaltura.com'
38 _SERVICE_BASE = '/api_v3/index.php'
41 'url': 'kaltura:269692:1_1jc2y3e4',
42 'md5': '3adcbdb3dcc02d647539e53f284ba171',
46 'title': 'Straight from the Heart',
47 'upload_date': '20131219',
48 'uploader_id': 'mlundberg@wolfgangsvault.com',
49 'description': 'The Allman Brothers Band, 12/16/1981',
50 'thumbnail': 're:^https?://.*/thumbnail/.*',
55 'url': 'http://www.kaltura.com/index.php/kwidget/cache_st/1300318621/wid/_269692/uiconf_id/3873291/entry_id/1_1jc2y3e4',
56 'only_matching': True,
59 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
60 'only_matching': True,
63 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.30.2/mwEmbedFrame.php/p/1337/uiconf_id/20540612/entry_id/1_sf5ovm7u?wid=_243342',
64 'only_matching': True,
67 # video with subtitles
68 'url': 'kaltura:111032:1_cw786r8q',
69 'only_matching': True,
72 # video with ttml subtitles (no fileExt)
73 'url': 'kaltura:1926081:0_l5ye1133',
77 'title': 'What Can You Do With Python?',
78 'upload_date': '20160221',
79 'uploader_id': 'stork',
80 'thumbnail': 're:^https?://.*/thumbnail/.*',
89 'skip_download': True,
95 def _extract_url(webpage):
99 kWidget\.(?:thumb)?[Ee]mbed\(
101 (?P<q1>['\"])wid(?P=q1)\s*:\s*
102 (?P<q2>['\"])_?(?P<partner_id>[^'\"]+)(?P=q2),.*?
103 (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
104 (?P<q4>['\"])(?P<id>[^'\"]+)(?P=q4),
109 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com/.*?(?:p|partner_id)/(?P<partner_id>\d+).*?
113 (?P<q2>["\'])entry_?[Ii]d(?P=q2)
115 (?P<q3>["\'])(?P<id>.+?)(?P=q3)
118 embed_info = mobj.groupdict()
119 url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
120 escaped_pid = re.escape(embed_info['partner_id'])
121 service_url = re.search(
122 r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
125 url = smuggle_url(url, {'service_url': service_url.group(1)})
128 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
131 for i, a in enumerate(actions[1:], start=1):
132 for k, v in a.items():
133 params['%d:%s' % (i, k)] = v
135 data = self._download_json(
136 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
137 video_id, query=params, *args, **kwargs)
139 status = data if len(actions) == 1 else data[0]
140 if status.get('objectType') == 'KalturaAPIException':
141 raise ExtractorError(
142 '%s said: %s' % (self.IE_NAME, status['message']))
146 def _get_video_info(self, video_id, partner_id, service_url=None):
150 'apiVersion': '3.1.5',
151 'clientTag': 'kdp:v3.8.5',
152 'format': 1, # JSON, 2 = XML, 3 = PHP
153 'service': 'multirequest',
157 'service': 'session',
158 'action': 'startWidgetSession',
159 'widgetId': '_%s' % partner_id,
164 'service': 'baseentry',
165 'ks': '{1:result:ks}',
168 'action': 'getbyentryid',
170 'service': 'flavorAsset',
171 'ks': '{1:result:ks}',
175 'filter:entryIdEqual': video_id,
176 'service': 'caption_captionasset',
177 'ks': '{1:result:ks}',
180 return self._kaltura_api_call(
181 video_id, actions, service_url, note='Downloading video info JSON')
183 def _real_extract(self, url):
184 url, smuggled_data = unsmuggle_url(url, {})
186 mobj = re.match(self._VALID_URL, url)
187 partner_id, entry_id = mobj.group('partner_id', 'id')
190 if partner_id and entry_id:
191 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
193 path, query = mobj.group('path', 'query')
194 if not path and not query:
195 raise ExtractorError('Invalid URL', expected=True)
198 params = compat_parse_qs(query)
200 splitted_path = path.split('/')
201 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
203 partner_id = params['wid'][0][1:]
205 partner_id = params['p'][0]
207 raise ExtractorError('Invalid URL', expected=True)
208 if 'entry_id' in params:
209 entry_id = params['entry_id'][0]
210 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
211 elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
212 reference_id = params['flashvars[referenceId]'][0]
213 webpage = self._download_webpage(url, reference_id)
214 entry_data = self._parse_json(self._search_regex(
215 r'window\.kalturaIframePackageData\s*=\s*({.*});',
216 webpage, 'kalturaIframePackageData'),
217 reference_id)['entryResult']
218 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
219 entry_id = info['id']
220 # Unfortunately, data returned in kalturaIframePackageData lacks
221 # captions so we will try requesting the complete data using
222 # regular approach since we now know the entry_id
224 _, info, flavor_assets, captions = self._get_video_info(
225 entry_id, partner_id)
226 except ExtractorError:
227 # Regular scenario failed but we already have everything
228 # extracted apart from captions and can process at least
232 raise ExtractorError('Invalid URL', expected=True)
233 ks = params.get('flashvars[ks]', [None])[0]
235 source_url = smuggled_data.get('source_url')
237 referrer = base64.b64encode(
238 '://'.join(compat_urlparse.urlparse(source_url)[:2])
239 .encode('utf-8')).decode('utf-8')
243 def sign_url(unsigned_url):
245 unsigned_url += '/ks/%s' % ks
247 unsigned_url += '?referrer=%s' % referrer
250 data_url = info['dataUrl']
251 if '/flvclipper/' in data_url:
252 data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
255 for f in flavor_assets:
256 # Continue if asset is not ready
257 if f.get('status') != 2:
259 video_url = sign_url(
260 '%s/flavorId/%s' % (data_url, f['id']))
262 'format_id': '%(fileExt)s-%(bitrate)s' % f,
263 'ext': f.get('fileExt'),
264 'tbr': int_or_none(f['bitrate']),
265 'fps': int_or_none(f.get('frameRate')),
266 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
267 'container': f.get('containerFormat'),
268 'vcodec': f.get('videoCodecId'),
269 'height': int_or_none(f.get('height')),
270 'width': int_or_none(f.get('width')),
273 if '/playManifest/' in data_url:
274 m3u8_url = sign_url(data_url.replace(
275 'format/url', 'format/applehttp'))
276 formats.extend(self._extract_m3u8_formats(
277 m3u8_url, entry_id, 'mp4', 'm3u8_native',
278 m3u8_id='hls', fatal=False))
280 self._sort_formats(formats)
284 for caption in captions.get('objects', []):
285 # Continue if caption is not ready
286 if f.get('status') != 2:
288 subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
289 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
290 'ext': caption.get('fileExt', 'ttml'),
295 'title': info['name'],
297 'subtitles': subtitles,
298 'description': clean_html(info.get('description')),
299 'thumbnail': info.get('thumbnailUrl'),
300 'duration': info.get('duration'),
301 'timestamp': info.get('createdAt'),
302 'uploader_id': info.get('userId'),
303 'view_count': info.get('plays'),