]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/kaltura.py
[kaltura] Assume ttml to be default subtitles' extension
[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'
0d97ef43
NJ
39 _TESTS = [
40 {
41 'url': 'kaltura:269692:1_1jc2y3e4',
42 'md5': '3adcbdb3dcc02d647539e53f284ba171',
43 'info_dict': {
44 'id': '1_1jc2y3e4',
45 'ext': 'mp4',
bb4b8c57 46 'title': 'Straight from the Heart',
0d97ef43
NJ
47 'upload_date': '20131219',
48 'uploader_id': 'mlundberg@wolfgangsvault.com',
49 'description': 'The Allman Brothers Band, 12/16/1981',
50 'thumbnail': 're:^https?://.*/thumbnail/.*',
51 'timestamp': int,
52 },
53 },
54 {
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,
57 },
bd3749ed
S
58 {
59 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
60 'only_matching': True,
61 },
ef49b590 62 {
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,
1094074c
RA
65 },
66 {
67 # video with subtitles
68 'url': 'kaltura:111032:1_cw786r8q',
69 'only_matching': True,
ef49b590 70 }
0d97ef43
NJ
71 ]
72
9ea5c04c
S
73 @staticmethod
74 def _extract_url(webpage):
75 mobj = (
76 re.search(
77 r"""(?xs)
78 kWidget\.(?:thumb)?[Ee]mbed\(
79 \{.*?
80 (?P<q1>['\"])wid(?P=q1)\s*:\s*
81 (?P<q2>['\"])_?(?P<partner_id>[^'\"]+)(?P=q2),.*?
82 (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
83 (?P<q4>['\"])(?P<id>[^'\"]+)(?P=q4),
84 """, webpage) or
85 re.search(
86 r'''(?xs)
87 (?P<q1>["\'])
88 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com/.*?(?:p|partner_id)/(?P<partner_id>\d+).*?
89 (?P=q1).*?
90 (?:
91 entry_?[Ii]d|
92 (?P<q2>["\'])entry_?[Ii]d(?P=q2)
93 )\s*:\s*
94 (?P<q3>["\'])(?P<id>.+?)(?P=q3)
95 ''', webpage))
96 if mobj:
81953d1a
RA
97 embed_info = mobj.groupdict()
98 url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
d9163ae3 99 escaped_pid = re.escape(embed_info['partner_id'])
81953d1a 100 service_url = re.search(
d9163ae3 101 r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
81953d1a
RA
102 webpage)
103 if service_url:
104 url = smuggle_url(url, {'service_url': service_url.group(1)})
105 return url
9ea5c04c 106
d9163ae3 107 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
0d97ef43
NJ
108 params = actions[0]
109 if len(actions) > 1:
110 for i, a in enumerate(actions[1:], start=1):
111 for k, v in a.items():
112 params['%d:%s' % (i, k)] = v
113
81953d1a 114 data = self._download_json(
d9163ae3 115 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
81953d1a 116 video_id, query=params, *args, **kwargs)
0d97ef43
NJ
117
118 status = data if len(actions) == 1 else data[0]
119 if status.get('objectType') == 'KalturaAPIException':
120 raise ExtractorError(
121 '%s said: %s' % (self.IE_NAME, status['message']))
122
123 return data
124
d9163ae3 125 def _get_video_info(self, video_id, partner_id, service_url=None):
0d97ef43
NJ
126 actions = [
127 {
128 'action': 'null',
129 'apiVersion': '3.1.5',
130 'clientTag': 'kdp:v3.8.5',
131 'format': 1, # JSON, 2 = XML, 3 = PHP
132 'service': 'multirequest',
1094074c
RA
133 },
134 {
135 'expiry': 86400,
136 'service': 'session',
137 'action': 'startWidgetSession',
138 'widgetId': '_%s' % partner_id,
0d97ef43
NJ
139 },
140 {
141 'action': 'get',
142 'entryId': video_id,
143 'service': 'baseentry',
1094074c 144 'ks': '{1:result:ks}',
0d97ef43
NJ
145 },
146 {
bb4b8c57 147 'action': 'getbyentryid',
0d97ef43 148 'entryId': video_id,
bb4b8c57 149 'service': 'flavorAsset',
1094074c
RA
150 'ks': '{1:result:ks}',
151 },
152 {
153 'action': 'list',
154 'filter:entryIdEqual': video_id,
155 'service': 'caption_captionasset',
156 'ks': '{1:result:ks}',
0d97ef43
NJ
157 },
158 ]
159 return self._kaltura_api_call(
d9163ae3 160 video_id, actions, service_url, note='Downloading video info JSON')
0d97ef43
NJ
161
162 def _real_extract(self, url):
01b06aed
S
163 url, smuggled_data = unsmuggle_url(url, {})
164
0d97ef43 165 mobj = re.match(self._VALID_URL, url)
fac7e792 166 partner_id, entry_id = mobj.group('partner_id', 'id')
9dce3c09 167 ks = None
1094074c 168 captions = None
fac7e792 169 if partner_id and entry_id:
1094074c 170 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
fac7e792 171 else:
172 path, query = mobj.group('path', 'query')
173 if not path and not query:
174 raise ExtractorError('Invalid URL', expected=True)
175 params = {}
176 if query:
177 params = compat_parse_qs(query)
178 if path:
179 splitted_path = path.split('/')
e5a2e17a 180 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
fac7e792 181 if 'wid' in params:
182 partner_id = params['wid'][0][1:]
183 elif 'p' in params:
184 partner_id = params['p'][0]
185 else:
186 raise ExtractorError('Invalid URL', expected=True)
187 if 'entry_id' in params:
188 entry_id = params['entry_id'][0]
1094074c 189 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
fac7e792 190 elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
191 reference_id = params['flashvars[referenceId]'][0]
192 webpage = self._download_webpage(url, reference_id)
193 entry_data = self._parse_json(self._search_regex(
194 r'window\.kalturaIframePackageData\s*=\s*({.*});',
195 webpage, 'kalturaIframePackageData'),
196 reference_id)['entryResult']
197 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
198 entry_id = info['id']
a8094467
S
199 # Unfortunately, data returned in kalturaIframePackageData lacks
200 # captions so we will try requesting the complete data using
201 # regular approach since we now know the entry_id
202 try:
203 _, info, flavor_assets, captions = self._get_video_info(
204 entry_id, partner_id)
205 except ExtractorError:
206 # Regular scenario failed but we already have everything
207 # extracted apart from captions and can process at least
208 # with this
209 pass
fac7e792 210 else:
211 raise ExtractorError('Invalid URL', expected=True)
9dce3c09 212 ks = params.get('flashvars[ks]', [None])[0]
0d97ef43 213
01b06aed
S
214 source_url = smuggled_data.get('source_url')
215 if source_url:
216 referrer = base64.b64encode(
217 '://'.join(compat_urlparse.urlparse(source_url)[:2])
218 .encode('utf-8')).decode('utf-8')
219 else:
220 referrer = None
221
9dce3c09
S
222 def sign_url(unsigned_url):
223 if ks:
224 unsigned_url += '/ks/%s' % ks
225 if referrer:
226 unsigned_url += '?referrer=%s' % referrer
227 return unsigned_url
228
81953d1a
RA
229 data_url = info['dataUrl']
230 if '/flvclipper/' in data_url:
231 data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
232
01b06aed 233 formats = []
bb4b8c57 234 for f in flavor_assets:
235 # Continue if asset is not ready
1094074c 236 if f.get('status') != 2:
bb4b8c57 237 continue
81953d1a
RA
238 video_url = sign_url(
239 '%s/flavorId/%s' % (data_url, f['id']))
01b06aed
S
240 formats.append({
241 'format_id': '%(fileExt)s-%(bitrate)s' % f,
d80a39ce
S
242 'ext': f.get('fileExt'),
243 'tbr': int_or_none(f['bitrate']),
244 'fps': int_or_none(f.get('frameRate')),
01b06aed
S
245 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
246 'container': f.get('containerFormat'),
247 'vcodec': f.get('videoCodecId'),
d80a39ce
S
248 'height': int_or_none(f.get('height')),
249 'width': int_or_none(f.get('width')),
01b06aed
S
250 'url': video_url,
251 })
81953d1a
RA
252 if '/playManifest/' in data_url:
253 m3u8_url = sign_url(data_url.replace(
254 'format/url', 'format/applehttp'))
255 formats.extend(self._extract_m3u8_formats(
256 m3u8_url, entry_id, 'mp4', 'm3u8_native',
257 m3u8_id='hls', fatal=False))
bb4b8c57 258
0d97ef43
NJ
259 self._sort_formats(formats)
260
1094074c
RA
261 subtitles = {}
262 if captions:
263 for caption in captions.get('objects', []):
1094074c
RA
264 # Continue if caption is not ready
265 if f.get('status') != 2:
266 continue
267 subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
268 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
fddaa76a 269 'ext': caption.get('fileExt', 'ttml'),
1094074c
RA
270 })
271
0d97ef43 272 return {
ee3ec091 273 'id': entry_id,
0d97ef43
NJ
274 'title': info['name'],
275 'formats': formats,
1094074c 276 'subtitles': subtitles,
bdceea7a 277 'description': clean_html(info.get('description')),
0d97ef43
NJ
278 'thumbnail': info.get('thumbnailUrl'),
279 'duration': info.get('duration'),
280 'timestamp': info.get('createdAt'),
281 'uploader_id': info.get('userId'),
282 'view_count': info.get('plays'),
283 }