]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/kaltura.py
[konserthusetplay] Add support for rspoplay.se
[yt-dlp.git] / youtube_dl / extractor / kaltura.py
CommitLineData
0d97ef43
NJ
1# coding: utf-8
2from __future__ import unicode_literals
3
4import re
01b06aed 5import base64
0d97ef43
NJ
6
7from .common import InfoExtractor
01b06aed 8from ..compat import (
01b06aed 9 compat_urlparse,
fac7e792 10 compat_parse_qs,
01b06aed 11)
0d97ef43 12from ..utils import (
bdceea7a 13 clean_html,
0d97ef43
NJ
14 ExtractorError,
15 int_or_none,
01b06aed 16 unsmuggle_url,
81953d1a 17 smuggle_url,
0d97ef43
NJ
18)
19
20
21class KalturaIE(InfoExtractor):
22 _VALID_URL = r'''(?x)
ee3ec091 23 (?:
fac7e792 24 kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)|
ee3ec091 25 https?://
b25f7533 26 (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/
ee3ec091
S
27 (?:
28 (?:
29 # flash player
fac7e792 30 index\.php/kwidget|
b184f944 31 # html5 player
fac7e792 32 html5/html5lib/[^/]+/mwEmbedFrame\.php
ae6a8021 33 )
fac7e792 34 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
ee3ec091
S
35 )
36 '''
81953d1a
RA
37 _SERVICE_URL = 'http://cdnapi.kaltura.com'
38 _SERVICE_BASE = '/api_v3/index.php'
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 },
94 'params': {
95 'skip_download': True,
96 },
ef49b590 97 }
0d97ef43
NJ
98 ]
99
9ea5c04c
S
100 @staticmethod
101 def _extract_url(webpage):
102 mobj = (
103 re.search(
104 r"""(?xs)
105 kWidget\.(?:thumb)?[Ee]mbed\(
106 \{.*?
107 (?P<q1>['\"])wid(?P=q1)\s*:\s*
fffb9cff 108 (?P<q2>['\"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
9ea5c04c 109 (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
8ab7e6c4 110 (?P<q4>['\"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
9ea5c04c
S
111 """, webpage) or
112 re.search(
113 r'''(?xs)
114 (?P<q1>["\'])
fffb9cff 115 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com/(?:(?!(?P=q1)).)*(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
9ea5c04c
S
116 (?P=q1).*?
117 (?:
118 entry_?[Ii]d|
119 (?P<q2>["\'])entry_?[Ii]d(?P=q2)
120 )\s*:\s*
fffb9cff 121 (?P<q3>["\'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
9ea5c04c
S
122 ''', webpage))
123 if mobj:
81953d1a
RA
124 embed_info = mobj.groupdict()
125 url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
d9163ae3 126 escaped_pid = re.escape(embed_info['partner_id'])
81953d1a 127 service_url = re.search(
d9163ae3 128 r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
81953d1a
RA
129 webpage)
130 if service_url:
131 url = smuggle_url(url, {'service_url': service_url.group(1)})
132 return url
9ea5c04c 133
d9163ae3 134 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
0d97ef43
NJ
135 params = actions[0]
136 if len(actions) > 1:
137 for i, a in enumerate(actions[1:], start=1):
138 for k, v in a.items():
139 params['%d:%s' % (i, k)] = v
140
81953d1a 141 data = self._download_json(
d9163ae3 142 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
81953d1a 143 video_id, query=params, *args, **kwargs)
0d97ef43
NJ
144
145 status = data if len(actions) == 1 else data[0]
146 if status.get('objectType') == 'KalturaAPIException':
147 raise ExtractorError(
148 '%s said: %s' % (self.IE_NAME, status['message']))
149
150 return data
151
d9163ae3 152 def _get_video_info(self, video_id, partner_id, service_url=None):
0d97ef43
NJ
153 actions = [
154 {
155 'action': 'null',
156 'apiVersion': '3.1.5',
157 'clientTag': 'kdp:v3.8.5',
158 'format': 1, # JSON, 2 = XML, 3 = PHP
159 'service': 'multirequest',
1094074c
RA
160 },
161 {
162 'expiry': 86400,
163 'service': 'session',
164 'action': 'startWidgetSession',
165 'widgetId': '_%s' % partner_id,
0d97ef43
NJ
166 },
167 {
168 'action': 'get',
169 'entryId': video_id,
170 'service': 'baseentry',
1094074c 171 'ks': '{1:result:ks}',
0d97ef43
NJ
172 },
173 {
bb4b8c57 174 'action': 'getbyentryid',
0d97ef43 175 'entryId': video_id,
bb4b8c57 176 'service': 'flavorAsset',
1094074c
RA
177 'ks': '{1:result:ks}',
178 },
179 {
180 'action': 'list',
181 'filter:entryIdEqual': video_id,
182 'service': 'caption_captionasset',
183 'ks': '{1:result:ks}',
0d97ef43
NJ
184 },
185 ]
186 return self._kaltura_api_call(
d9163ae3 187 video_id, actions, service_url, note='Downloading video info JSON')
0d97ef43
NJ
188
189 def _real_extract(self, url):
01b06aed
S
190 url, smuggled_data = unsmuggle_url(url, {})
191
0d97ef43 192 mobj = re.match(self._VALID_URL, url)
fac7e792 193 partner_id, entry_id = mobj.group('partner_id', 'id')
9dce3c09 194 ks = None
1094074c 195 captions = None
fac7e792 196 if partner_id and entry_id:
1094074c 197 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
fac7e792 198 else:
199 path, query = mobj.group('path', 'query')
200 if not path and not query:
201 raise ExtractorError('Invalid URL', expected=True)
202 params = {}
203 if query:
204 params = compat_parse_qs(query)
205 if path:
206 splitted_path = path.split('/')
e5a2e17a 207 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
fac7e792 208 if 'wid' in params:
209 partner_id = params['wid'][0][1:]
210 elif 'p' in params:
211 partner_id = params['p'][0]
212 else:
213 raise ExtractorError('Invalid URL', expected=True)
214 if 'entry_id' in params:
215 entry_id = params['entry_id'][0]
1094074c 216 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
fac7e792 217 elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
218 reference_id = params['flashvars[referenceId]'][0]
219 webpage = self._download_webpage(url, reference_id)
220 entry_data = self._parse_json(self._search_regex(
221 r'window\.kalturaIframePackageData\s*=\s*({.*});',
222 webpage, 'kalturaIframePackageData'),
223 reference_id)['entryResult']
224 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
225 entry_id = info['id']
a8094467
S
226 # Unfortunately, data returned in kalturaIframePackageData lacks
227 # captions so we will try requesting the complete data using
228 # regular approach since we now know the entry_id
229 try:
230 _, info, flavor_assets, captions = self._get_video_info(
231 entry_id, partner_id)
232 except ExtractorError:
233 # Regular scenario failed but we already have everything
234 # extracted apart from captions and can process at least
235 # with this
236 pass
fac7e792 237 else:
238 raise ExtractorError('Invalid URL', expected=True)
9dce3c09 239 ks = params.get('flashvars[ks]', [None])[0]
0d97ef43 240
01b06aed
S
241 source_url = smuggled_data.get('source_url')
242 if source_url:
243 referrer = base64.b64encode(
244 '://'.join(compat_urlparse.urlparse(source_url)[:2])
245 .encode('utf-8')).decode('utf-8')
246 else:
247 referrer = None
248
9dce3c09
S
249 def sign_url(unsigned_url):
250 if ks:
251 unsigned_url += '/ks/%s' % ks
252 if referrer:
253 unsigned_url += '?referrer=%s' % referrer
254 return unsigned_url
255
81953d1a
RA
256 data_url = info['dataUrl']
257 if '/flvclipper/' in data_url:
258 data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
259
01b06aed 260 formats = []
bb4b8c57 261 for f in flavor_assets:
262 # Continue if asset is not ready
1094074c 263 if f.get('status') != 2:
bb4b8c57 264 continue
e8bcd982
S
265 # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
266 # skip for now.
267 if f.get('fileExt') == 'chun':
268 continue
8ab7e6c4
YCH
269 if not f.get('fileExt') and f.get('containerFormat') == 'qt':
270 # QT indicates QuickTime; some videos have broken fileExt
271 f['fileExt'] = 'mov'
81953d1a
RA
272 video_url = sign_url(
273 '%s/flavorId/%s' % (data_url, f['id']))
1d16035b
S
274 # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
275 # -f mp4-56)
276 vcodec = 'none' if 'videoCodecId' not in f and f.get(
277 'frameRate') == 0 else f.get('videoCodecId')
01b06aed
S
278 formats.append({
279 'format_id': '%(fileExt)s-%(bitrate)s' % f,
d80a39ce
S
280 'ext': f.get('fileExt'),
281 'tbr': int_or_none(f['bitrate']),
282 'fps': int_or_none(f.get('frameRate')),
01b06aed
S
283 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
284 'container': f.get('containerFormat'),
1d16035b 285 'vcodec': vcodec,
d80a39ce
S
286 'height': int_or_none(f.get('height')),
287 'width': int_or_none(f.get('width')),
01b06aed
S
288 'url': video_url,
289 })
81953d1a
RA
290 if '/playManifest/' in data_url:
291 m3u8_url = sign_url(data_url.replace(
292 'format/url', 'format/applehttp'))
293 formats.extend(self._extract_m3u8_formats(
294 m3u8_url, entry_id, 'mp4', 'm3u8_native',
295 m3u8_id='hls', fatal=False))
bb4b8c57 296
0d97ef43
NJ
297 self._sort_formats(formats)
298
1094074c
RA
299 subtitles = {}
300 if captions:
301 for caption in captions.get('objects', []):
1094074c
RA
302 # Continue if caption is not ready
303 if f.get('status') != 2:
304 continue
92d4cfa3
S
305 if not caption.get('id'):
306 continue
307 caption_format = int_or_none(caption.get('format'))
1094074c
RA
308 subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
309 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
92d4cfa3 310 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
1094074c
RA
311 })
312
0d97ef43 313 return {
ee3ec091 314 'id': entry_id,
0d97ef43
NJ
315 'title': info['name'],
316 'formats': formats,
1094074c 317 'subtitles': subtitles,
bdceea7a 318 'description': clean_html(info.get('description')),
0d97ef43
NJ
319 'thumbnail': info.get('thumbnailUrl'),
320 'duration': info.get('duration'),
321 'timestamp': info.get('createdAt'),
322 'uploader_id': info.get('userId'),
323 'view_count': info.get('plays'),
324 }