]>
Commit | Line | Data |
---|---|---|
01b06aed | 1 | import base64 |
5747d4f4 M |
2 | import json |
3 | import re | |
0d97ef43 NJ |
4 | |
5 | from .common import InfoExtractor | |
01b06aed | 6 | from ..compat import ( |
01b06aed | 7 | compat_urlparse, |
fac7e792 | 8 | compat_parse_qs, |
01b06aed | 9 | ) |
0d97ef43 | 10 | from ..utils import ( |
bdceea7a | 11 | clean_html, |
0d97ef43 | 12 | ExtractorError, |
e0ddbd02 | 13 | format_field, |
0d97ef43 | 14 | int_or_none, |
01b06aed | 15 | unsmuggle_url, |
81953d1a | 16 | smuggle_url, |
5747d4f4 | 17 | traverse_obj, |
0d97ef43 NJ |
18 | ) |
19 | ||
20 | ||
21 | class KalturaIE(InfoExtractor): | |
22 | _VALID_URL = r'''(?x) | |
ee3ec091 | 23 | (?: |
fac7e792 | 24 | kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)| |
ee3ec091 | 25 | https?:// |
ff24261b | 26 | (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/ |
ee3ec091 S |
27 | (?: |
28 | (?: | |
29 | # flash player | |
37084f66 | 30 | index\.php/(?:kwidget|extwidget/preview)| |
b184f944 | 31 | # html5 player |
fac7e792 | 32 | html5/html5lib/[^/]+/mwEmbedFrame\.php |
ae6a8021 | 33 | ) |
fac7e792 | 34 | )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))? |
ee3ec091 S |
35 | ) |
36 | ''' | |
81953d1a | 37 | _SERVICE_URL = 'http://cdnapi.kaltura.com' |
5747d4f4 | 38 | _SERVICE_BASE = '/api_v3/service/multirequest' |
92d4cfa3 S |
39 | # See https://github.com/kaltura/server/blob/master/plugins/content/caption/base/lib/model/enums/CaptionType.php |
40 | _CAPTION_TYPES = { | |
41 | 1: 'srt', | |
42 | 2: 'ttml', | |
43 | 3: 'vtt', | |
44 | } | |
0d97ef43 NJ |
45 | _TESTS = [ |
46 | { | |
47 | 'url': 'kaltura:269692:1_1jc2y3e4', | |
48 | 'md5': '3adcbdb3dcc02d647539e53f284ba171', | |
49 | 'info_dict': { | |
50 | 'id': '1_1jc2y3e4', | |
51 | 'ext': 'mp4', | |
bb4b8c57 | 52 | 'title': 'Straight from the Heart', |
0d97ef43 NJ |
53 | 'upload_date': '20131219', |
54 | 'uploader_id': 'mlundberg@wolfgangsvault.com', | |
55 | 'description': 'The Allman Brothers Band, 12/16/1981', | |
56 | 'thumbnail': 're:^https?://.*/thumbnail/.*', | |
57 | 'timestamp': int, | |
58 | }, | |
59 | }, | |
60 | { | |
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, | |
63 | }, | |
bd3749ed S |
64 | { |
65 | 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3', | |
66 | 'only_matching': True, | |
67 | }, | |
ef49b590 | 68 | { |
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, | |
1094074c RA |
71 | }, |
72 | { | |
73 | # video with subtitles | |
74 | 'url': 'kaltura:111032:1_cw786r8q', | |
75 | 'only_matching': True, | |
2c6acdfd S |
76 | }, |
77 | { | |
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 | }], | |
92 | }, | |
93 | }, | |
a01825a5 | 94 | 'skip': 'Gone. Maybe https://www.safaribooksonline.com/library/tutorials/introduction-to-python-anon/3469/', |
2c6acdfd S |
95 | 'params': { |
96 | 'skip_download': True, | |
97 | }, | |
37084f66 RA |
98 | }, |
99 | { | |
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, | |
ff24261b S |
102 | }, |
103 | { | |
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, | |
799756a3 S |
106 | }, |
107 | { | |
108 | # unavailable source format | |
109 | 'url': 'kaltura:513551:1_66x4rg7o', | |
110 | 'only_matching': True, | |
ef49b590 | 111 | } |
0d97ef43 NJ |
112 | ] |
113 | ||
9ea5c04c S |
114 | @staticmethod |
115 | def _extract_url(webpage): | |
562de77f S |
116 | urls = KalturaIE._extract_urls(webpage) |
117 | return urls[0] if urls else None | |
118 | ||
119 | @staticmethod | |
120 | def _extract_urls(webpage): | |
78280352 | 121 | # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site |
562de77f | 122 | finditer = ( |
41d1cca3 | 123 | list(re.finditer( |
9ea5c04c S |
124 | r"""(?xs) |
125 | kWidget\.(?:thumb)?[Ee]mbed\( | |
126 | \{.*? | |
78280352 S |
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*\}) | |
41d1cca3 | 131 | """, webpage)) |
132 | or list(re.finditer( | |
9ea5c04c | 133 | r'''(?xs) |
78280352 | 134 | (?P<q1>["']) |
ff24261b | 135 | (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)* |
9ea5c04c S |
136 | (?P=q1).*? |
137 | (?: | |
69d69da9 S |
138 | (?: |
139 | entry_?[Ii]d| | |
140 | (?P<q2>["'])entry_?[Ii]d(?P=q2) | |
141 | )\s*:\s*| | |
c2f2f8b1 | 142 | \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s* |
69d69da9 | 143 | ) |
78280352 | 144 | (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3) |
41d1cca3 | 145 | ''', webpage)) |
146 | or list(re.finditer( | |
a01825a5 | 147 | r'''(?xs) |
41d1cca3 | 148 | <(?:iframe[^>]+src|meta[^>]+\bcontent)=(?P<q1>["'])\s* |
c21692fa | 149 | (?:https?:)?//(?:(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+) |
a01825a5 | 150 | (?:(?!(?P=q1)).)* |
e30991f9 | 151 | [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+) |
c21692fa | 152 | (?:(?!(?P=q1)).)* |
a01825a5 | 153 | (?P=q1) |
41d1cca3 | 154 | ''', webpage)) |
a01825a5 | 155 | ) |
562de77f S |
156 | urls = [] |
157 | for mobj in finditer: | |
81953d1a | 158 | embed_info = mobj.groupdict() |
5ca34598 | 159 | for k, v in embed_info.items(): |
1907f06e S |
160 | if v: |
161 | embed_info[k] = v.strip() | |
81953d1a | 162 | url = 'kaltura:%(partner_id)s:%(id)s' % embed_info |
d9163ae3 | 163 | escaped_pid = re.escape(embed_info['partner_id']) |
07b50f61 S |
164 | service_mobj = re.search( |
165 | r'<script[^>]+src=(["\'])(?P<id>(?:https?:)?//(?:(?!\1).)+)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid), | |
81953d1a | 166 | webpage) |
07b50f61 S |
167 | if service_mobj: |
168 | url = smuggle_url(url, {'service_url': service_mobj.group('id')}) | |
562de77f S |
169 | urls.append(url) |
170 | return urls | |
9ea5c04c | 171 | |
d9163ae3 | 172 | def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs): |
0d97ef43 | 173 | params = actions[0] |
5747d4f4 | 174 | params.update({i: a for i, a in enumerate(actions[1:], start=1)}) |
0d97ef43 | 175 | |
81953d1a | 176 | data = self._download_json( |
d9163ae3 | 177 | (service_url or self._SERVICE_URL) + self._SERVICE_BASE, |
5747d4f4 M |
178 | video_id, data=json.dumps(params).encode('utf-8'), |
179 | headers={ | |
180 | 'Content-Type': 'application/json', | |
181 | 'Accept-Encoding': 'gzip, deflate, br', | |
182 | }, *args, **kwargs) | |
183 | ||
184 | for idx, status in enumerate(data): | |
185 | if not isinstance(status, dict): | |
186 | continue | |
187 | if status.get('objectType') == 'KalturaAPIException': | |
188 | raise ExtractorError( | |
189 | '%s said: %s (%d)' % (self.IE_NAME, status['message'], idx)) | |
0d97ef43 | 190 | |
5747d4f4 | 191 | data[1] = traverse_obj(data, (1, 'objects', 0)) |
0d97ef43 NJ |
192 | |
193 | return data | |
194 | ||
d9163ae3 | 195 | def _get_video_info(self, video_id, partner_id, service_url=None): |
0d97ef43 NJ |
196 | actions = [ |
197 | { | |
5747d4f4 M |
198 | 'apiVersion': '3.3.0', |
199 | 'clientTag': 'html5:v3.1.0', | |
0d97ef43 | 200 | 'format': 1, # JSON, 2 = XML, 3 = PHP |
5747d4f4 M |
201 | 'ks': '', |
202 | 'partnerId': partner_id, | |
1094074c RA |
203 | }, |
204 | { | |
205 | 'expiry': 86400, | |
206 | 'service': 'session', | |
207 | 'action': 'startWidgetSession', | |
208 | 'widgetId': '_%s' % partner_id, | |
0d97ef43 NJ |
209 | }, |
210 | { | |
5747d4f4 M |
211 | 'action': 'list', |
212 | 'filter': {'redirectFromEntryId': video_id}, | |
0d97ef43 | 213 | 'service': 'baseentry', |
1094074c | 214 | 'ks': '{1:result:ks}', |
5747d4f4 M |
215 | 'responseProfile': { |
216 | 'type': 1, | |
217 | 'fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId', | |
218 | }, | |
0d97ef43 NJ |
219 | }, |
220 | { | |
bb4b8c57 | 221 | 'action': 'getbyentryid', |
0d97ef43 | 222 | 'entryId': video_id, |
bb4b8c57 | 223 | 'service': 'flavorAsset', |
1094074c RA |
224 | 'ks': '{1:result:ks}', |
225 | }, | |
226 | { | |
227 | 'action': 'list', | |
228 | 'filter:entryIdEqual': video_id, | |
229 | 'service': 'caption_captionasset', | |
230 | 'ks': '{1:result:ks}', | |
0d97ef43 NJ |
231 | }, |
232 | ] | |
233 | return self._kaltura_api_call( | |
d9163ae3 | 234 | video_id, actions, service_url, note='Downloading video info JSON') |
0d97ef43 NJ |
235 | |
236 | def _real_extract(self, url): | |
01b06aed S |
237 | url, smuggled_data = unsmuggle_url(url, {}) |
238 | ||
5ad28e7f | 239 | mobj = self._match_valid_url(url) |
fac7e792 | 240 | partner_id, entry_id = mobj.group('partner_id', 'id') |
9dce3c09 | 241 | ks = None |
1094074c | 242 | captions = None |
fac7e792 | 243 | if partner_id and entry_id: |
1094074c | 244 | _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url')) |
fac7e792 | 245 | else: |
246 | path, query = mobj.group('path', 'query') | |
247 | if not path and not query: | |
248 | raise ExtractorError('Invalid URL', expected=True) | |
249 | params = {} | |
250 | if query: | |
251 | params = compat_parse_qs(query) | |
252 | if path: | |
253 | splitted_path = path.split('/') | |
e5a2e17a | 254 | params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]])))) |
fac7e792 | 255 | if 'wid' in params: |
256 | partner_id = params['wid'][0][1:] | |
257 | elif 'p' in params: | |
258 | partner_id = params['p'][0] | |
37084f66 RA |
259 | elif 'partner_id' in params: |
260 | partner_id = params['partner_id'][0] | |
fac7e792 | 261 | else: |
262 | raise ExtractorError('Invalid URL', expected=True) | |
263 | if 'entry_id' in params: | |
264 | entry_id = params['entry_id'][0] | |
1094074c | 265 | _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id) |
fac7e792 | 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'] | |
a8094467 S |
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 | |
278 | try: | |
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 | |
284 | # with this | |
285 | pass | |
fac7e792 | 286 | else: |
287 | raise ExtractorError('Invalid URL', expected=True) | |
9dce3c09 | 288 | ks = params.get('flashvars[ks]', [None])[0] |
0d97ef43 | 289 | |
01b06aed S |
290 | source_url = smuggled_data.get('source_url') |
291 | if source_url: | |
292 | referrer = base64.b64encode( | |
293 | '://'.join(compat_urlparse.urlparse(source_url)[:2]) | |
294 | .encode('utf-8')).decode('utf-8') | |
295 | else: | |
296 | referrer = None | |
297 | ||
9dce3c09 S |
298 | def sign_url(unsigned_url): |
299 | if ks: | |
300 | unsigned_url += '/ks/%s' % ks | |
301 | if referrer: | |
302 | unsigned_url += '?referrer=%s' % referrer | |
303 | return unsigned_url | |
304 | ||
81953d1a RA |
305 | data_url = info['dataUrl'] |
306 | if '/flvclipper/' in data_url: | |
307 | data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url) | |
308 | ||
01b06aed | 309 | formats = [] |
3f047fc4 | 310 | subtitles = {} |
bb4b8c57 | 311 | for f in flavor_assets: |
312 | # Continue if asset is not ready | |
1094074c | 313 | if f.get('status') != 2: |
bb4b8c57 | 314 | continue |
e8bcd982 S |
315 | # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g) |
316 | # skip for now. | |
317 | if f.get('fileExt') == 'chun': | |
318 | continue | |
c0bddd6d | 319 | # DRM-protected video, cannot be decrypted |
a06916d9 | 320 | if not self.get_param('allow_unplayable_formats') and f.get('fileExt') == 'wvm': |
c0bddd6d | 321 | continue |
ab6f6aee | 322 | if not f.get('fileExt'): |
8ab7e6c4 | 323 | # QT indicates QuickTime; some videos have broken fileExt |
ab6f6aee S |
324 | if f.get('containerFormat') == 'qt': |
325 | f['fileExt'] = 'mov' | |
326 | else: | |
327 | f['fileExt'] = 'mp4' | |
81953d1a RA |
328 | video_url = sign_url( |
329 | '%s/flavorId/%s' % (data_url, f['id'])) | |
799756a3 S |
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): | |
334 | continue | |
1d16035b S |
335 | # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g |
336 | # -f mp4-56) | |
337 | vcodec = 'none' if 'videoCodecId' not in f and f.get( | |
338 | 'frameRate') == 0 else f.get('videoCodecId') | |
01b06aed | 339 | formats.append({ |
799756a3 | 340 | 'format_id': format_id, |
d80a39ce S |
341 | 'ext': f.get('fileExt'), |
342 | 'tbr': int_or_none(f['bitrate']), | |
343 | 'fps': int_or_none(f.get('frameRate')), | |
01b06aed S |
344 | 'filesize_approx': int_or_none(f.get('size'), invscale=1024), |
345 | 'container': f.get('containerFormat'), | |
1d16035b | 346 | 'vcodec': vcodec, |
d80a39ce S |
347 | 'height': int_or_none(f.get('height')), |
348 | 'width': int_or_none(f.get('width')), | |
01b06aed S |
349 | 'url': video_url, |
350 | }) | |
81953d1a RA |
351 | if '/playManifest/' in data_url: |
352 | m3u8_url = sign_url(data_url.replace( | |
353 | 'format/url', 'format/applehttp')) | |
3f047fc4 | 354 | fmts, subs = self._extract_m3u8_formats_and_subtitles( |
81953d1a | 355 | m3u8_url, entry_id, 'mp4', 'm3u8_native', |
3f047fc4 F |
356 | m3u8_id='hls', fatal=False) |
357 | formats.extend(fmts) | |
358 | self._merge_subtitles(subs, target=subtitles) | |
bb4b8c57 | 359 | |
0d97ef43 NJ |
360 | self._sort_formats(formats) |
361 | ||
1094074c RA |
362 | if captions: |
363 | for caption in captions.get('objects', []): | |
1094074c | 364 | # Continue if caption is not ready |
65547082 | 365 | if caption.get('status') != 2: |
1094074c | 366 | continue |
92d4cfa3 S |
367 | if not caption.get('id'): |
368 | continue | |
369 | caption_format = int_or_none(caption.get('format')) | |
1094074c RA |
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']), | |
92d4cfa3 | 372 | 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml', |
1094074c RA |
373 | }) |
374 | ||
0d97ef43 | 375 | return { |
ee3ec091 | 376 | 'id': entry_id, |
0d97ef43 NJ |
377 | 'title': info['name'], |
378 | 'formats': formats, | |
1094074c | 379 | 'subtitles': subtitles, |
bdceea7a | 380 | 'description': clean_html(info.get('description')), |
0d97ef43 NJ |
381 | 'thumbnail': info.get('thumbnailUrl'), |
382 | 'duration': info.get('duration'), | |
383 | 'timestamp': info.get('createdAt'), | |
e0ddbd02 | 384 | 'uploader_id': format_field(info, 'userId', ignore=('None', None)), |
6d1b3489 | 385 | 'view_count': int_or_none(info.get('plays')), |
0d97ef43 | 386 | } |