]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/kaltura.py
[cleanup] Use format_field where applicable
[yt-dlp.git] / yt_dlp / extractor / kaltura.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import base64
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_urlparse,
10 compat_parse_qs,
11 )
12 from ..utils import (
13 clean_html,
14 ExtractorError,
15 format_field,
16 int_or_none,
17 unsmuggle_url,
18 smuggle_url,
19 )
20
21
22 class KalturaIE(InfoExtractor):
23 _VALID_URL = r'''(?x)
24 (?:
25 kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)|
26 https?://
27 (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/
28 (?:
29 (?:
30 # flash player
31 index\.php/(?:kwidget|extwidget/preview)|
32 # html5 player
33 html5/html5lib/[^/]+/mwEmbedFrame\.php
34 )
35 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
36 )
37 '''
38 _SERVICE_URL = 'http://cdnapi.kaltura.com'
39 _SERVICE_BASE = '/api_v3/index.php'
40 # See https://github.com/kaltura/server/blob/master/plugins/content/caption/base/lib/model/enums/CaptionType.php
41 _CAPTION_TYPES = {
42 1: 'srt',
43 2: 'ttml',
44 3: 'vtt',
45 }
46 _TESTS = [
47 {
48 'url': 'kaltura:269692:1_1jc2y3e4',
49 'md5': '3adcbdb3dcc02d647539e53f284ba171',
50 'info_dict': {
51 'id': '1_1jc2y3e4',
52 'ext': 'mp4',
53 'title': 'Straight from the Heart',
54 'upload_date': '20131219',
55 'uploader_id': 'mlundberg@wolfgangsvault.com',
56 'description': 'The Allman Brothers Band, 12/16/1981',
57 'thumbnail': 're:^https?://.*/thumbnail/.*',
58 'timestamp': int,
59 },
60 },
61 {
62 'url': 'http://www.kaltura.com/index.php/kwidget/cache_st/1300318621/wid/_269692/uiconf_id/3873291/entry_id/1_1jc2y3e4',
63 'only_matching': True,
64 },
65 {
66 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
67 'only_matching': True,
68 },
69 {
70 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.30.2/mwEmbedFrame.php/p/1337/uiconf_id/20540612/entry_id/1_sf5ovm7u?wid=_243342',
71 'only_matching': True,
72 },
73 {
74 # video with subtitles
75 'url': 'kaltura:111032:1_cw786r8q',
76 'only_matching': True,
77 },
78 {
79 # video with ttml subtitles (no fileExt)
80 'url': 'kaltura:1926081:0_l5ye1133',
81 'info_dict': {
82 'id': '0_l5ye1133',
83 'ext': 'mp4',
84 'title': 'What Can You Do With Python?',
85 'upload_date': '20160221',
86 'uploader_id': 'stork',
87 'thumbnail': 're:^https?://.*/thumbnail/.*',
88 'timestamp': int,
89 'subtitles': {
90 'en': [{
91 'ext': 'ttml',
92 }],
93 },
94 },
95 'skip': 'Gone. Maybe https://www.safaribooksonline.com/library/tutorials/introduction-to-python-anon/3469/',
96 'params': {
97 'skip_download': True,
98 },
99 },
100 {
101 'url': 'https://www.kaltura.com/index.php/extwidget/preview/partner_id/1770401/uiconf_id/37307382/entry_id/0_58u8kme7/embed/iframe?&flashvars[streamerType]=auto',
102 'only_matching': True,
103 },
104 {
105 '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',
106 'only_matching': True,
107 },
108 {
109 # unavailable source format
110 'url': 'kaltura:513551:1_66x4rg7o',
111 'only_matching': True,
112 }
113 ]
114
115 @staticmethod
116 def _extract_url(webpage):
117 urls = KalturaIE._extract_urls(webpage)
118 return urls[0] if urls else None
119
120 @staticmethod
121 def _extract_urls(webpage):
122 # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
123 finditer = (
124 list(re.finditer(
125 r"""(?xs)
126 kWidget\.(?:thumb)?[Ee]mbed\(
127 \{.*?
128 (?P<q1>['"])wid(?P=q1)\s*:\s*
129 (?P<q2>['"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
130 (?P<q3>['"])entry_?[Ii]d(?P=q3)\s*:\s*
131 (?P<q4>['"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
132 """, webpage))
133 or list(re.finditer(
134 r'''(?xs)
135 (?P<q1>["'])
136 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
137 (?P=q1).*?
138 (?:
139 (?:
140 entry_?[Ii]d|
141 (?P<q2>["'])entry_?[Ii]d(?P=q2)
142 )\s*:\s*|
143 \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
144 )
145 (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
146 ''', webpage))
147 or list(re.finditer(
148 r'''(?xs)
149 <(?:iframe[^>]+src|meta[^>]+\bcontent)=(?P<q1>["'])\s*
150 (?:https?:)?//(?:(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)
151 (?:(?!(?P=q1)).)*
152 [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
153 (?:(?!(?P=q1)).)*
154 (?P=q1)
155 ''', webpage))
156 )
157 urls = []
158 for mobj in finditer:
159 embed_info = mobj.groupdict()
160 for k, v in embed_info.items():
161 if v:
162 embed_info[k] = v.strip()
163 url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
164 escaped_pid = re.escape(embed_info['partner_id'])
165 service_mobj = re.search(
166 r'<script[^>]+src=(["\'])(?P<id>(?:https?:)?//(?:(?!\1).)+)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
167 webpage)
168 if service_mobj:
169 url = smuggle_url(url, {'service_url': service_mobj.group('id')})
170 urls.append(url)
171 return urls
172
173 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
174 params = actions[0]
175 if len(actions) > 1:
176 for i, a in enumerate(actions[1:], start=1):
177 for k, v in a.items():
178 params['%d:%s' % (i, k)] = v
179
180 data = self._download_json(
181 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
182 video_id, query=params, *args, **kwargs)
183
184 status = data if len(actions) == 1 else data[0]
185 if status.get('objectType') == 'KalturaAPIException':
186 raise ExtractorError(
187 '%s said: %s' % (self.IE_NAME, status['message']))
188
189 return data
190
191 def _get_video_info(self, video_id, partner_id, service_url=None):
192 actions = [
193 {
194 'action': 'null',
195 'apiVersion': '3.1.5',
196 'clientTag': 'kdp:v3.8.5',
197 'format': 1, # JSON, 2 = XML, 3 = PHP
198 'service': 'multirequest',
199 },
200 {
201 'expiry': 86400,
202 'service': 'session',
203 'action': 'startWidgetSession',
204 'widgetId': '_%s' % partner_id,
205 },
206 {
207 'action': 'get',
208 'entryId': video_id,
209 'service': 'baseentry',
210 'ks': '{1:result:ks}',
211 'responseProfile:fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId',
212 'responseProfile:type': 1,
213 },
214 {
215 'action': 'getbyentryid',
216 'entryId': video_id,
217 'service': 'flavorAsset',
218 'ks': '{1:result:ks}',
219 },
220 {
221 'action': 'list',
222 'filter:entryIdEqual': video_id,
223 'service': 'caption_captionasset',
224 'ks': '{1:result:ks}',
225 },
226 ]
227 return self._kaltura_api_call(
228 video_id, actions, service_url, note='Downloading video info JSON')
229
230 def _real_extract(self, url):
231 url, smuggled_data = unsmuggle_url(url, {})
232
233 mobj = self._match_valid_url(url)
234 partner_id, entry_id = mobj.group('partner_id', 'id')
235 ks = None
236 captions = None
237 if partner_id and entry_id:
238 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
239 else:
240 path, query = mobj.group('path', 'query')
241 if not path and not query:
242 raise ExtractorError('Invalid URL', expected=True)
243 params = {}
244 if query:
245 params = compat_parse_qs(query)
246 if path:
247 splitted_path = path.split('/')
248 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
249 if 'wid' in params:
250 partner_id = params['wid'][0][1:]
251 elif 'p' in params:
252 partner_id = params['p'][0]
253 elif 'partner_id' in params:
254 partner_id = params['partner_id'][0]
255 else:
256 raise ExtractorError('Invalid URL', expected=True)
257 if 'entry_id' in params:
258 entry_id = params['entry_id'][0]
259 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
260 elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
261 reference_id = params['flashvars[referenceId]'][0]
262 webpage = self._download_webpage(url, reference_id)
263 entry_data = self._parse_json(self._search_regex(
264 r'window\.kalturaIframePackageData\s*=\s*({.*});',
265 webpage, 'kalturaIframePackageData'),
266 reference_id)['entryResult']
267 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
268 entry_id = info['id']
269 # Unfortunately, data returned in kalturaIframePackageData lacks
270 # captions so we will try requesting the complete data using
271 # regular approach since we now know the entry_id
272 try:
273 _, info, flavor_assets, captions = self._get_video_info(
274 entry_id, partner_id)
275 except ExtractorError:
276 # Regular scenario failed but we already have everything
277 # extracted apart from captions and can process at least
278 # with this
279 pass
280 else:
281 raise ExtractorError('Invalid URL', expected=True)
282 ks = params.get('flashvars[ks]', [None])[0]
283
284 source_url = smuggled_data.get('source_url')
285 if source_url:
286 referrer = base64.b64encode(
287 '://'.join(compat_urlparse.urlparse(source_url)[:2])
288 .encode('utf-8')).decode('utf-8')
289 else:
290 referrer = None
291
292 def sign_url(unsigned_url):
293 if ks:
294 unsigned_url += '/ks/%s' % ks
295 if referrer:
296 unsigned_url += '?referrer=%s' % referrer
297 return unsigned_url
298
299 data_url = info['dataUrl']
300 if '/flvclipper/' in data_url:
301 data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
302
303 formats = []
304 for f in flavor_assets:
305 # Continue if asset is not ready
306 if f.get('status') != 2:
307 continue
308 # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
309 # skip for now.
310 if f.get('fileExt') == 'chun':
311 continue
312 # DRM-protected video, cannot be decrypted
313 if not self.get_param('allow_unplayable_formats') and f.get('fileExt') == 'wvm':
314 continue
315 if not f.get('fileExt'):
316 # QT indicates QuickTime; some videos have broken fileExt
317 if f.get('containerFormat') == 'qt':
318 f['fileExt'] = 'mov'
319 else:
320 f['fileExt'] = 'mp4'
321 video_url = sign_url(
322 '%s/flavorId/%s' % (data_url, f['id']))
323 format_id = '%(fileExt)s-%(bitrate)s' % f
324 # Source format may not be available (e.g. kaltura:513551:1_66x4rg7o)
325 if f.get('isOriginal') is True and not self._is_valid_url(
326 video_url, entry_id, format_id):
327 continue
328 # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
329 # -f mp4-56)
330 vcodec = 'none' if 'videoCodecId' not in f and f.get(
331 'frameRate') == 0 else f.get('videoCodecId')
332 formats.append({
333 'format_id': format_id,
334 'ext': f.get('fileExt'),
335 'tbr': int_or_none(f['bitrate']),
336 'fps': int_or_none(f.get('frameRate')),
337 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
338 'container': f.get('containerFormat'),
339 'vcodec': vcodec,
340 'height': int_or_none(f.get('height')),
341 'width': int_or_none(f.get('width')),
342 'url': video_url,
343 })
344 if '/playManifest/' in data_url:
345 m3u8_url = sign_url(data_url.replace(
346 'format/url', 'format/applehttp'))
347 formats.extend(self._extract_m3u8_formats(
348 m3u8_url, entry_id, 'mp4', 'm3u8_native',
349 m3u8_id='hls', fatal=False))
350
351 self._sort_formats(formats)
352
353 subtitles = {}
354 if captions:
355 for caption in captions.get('objects', []):
356 # Continue if caption is not ready
357 if caption.get('status') != 2:
358 continue
359 if not caption.get('id'):
360 continue
361 caption_format = int_or_none(caption.get('format'))
362 subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
363 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
364 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
365 })
366
367 return {
368 'id': entry_id,
369 'title': info['name'],
370 'formats': formats,
371 'subtitles': subtitles,
372 'description': clean_html(info.get('description')),
373 'thumbnail': info.get('thumbnailUrl'),
374 'duration': info.get('duration'),
375 'timestamp': info.get('createdAt'),
376 'uploader_id': format_field(info, 'userId', ignore=('None', None)),
377 'view_count': info.get('plays'),
378 }