]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/kaltura.py
Prepare to release.
[youtubedl] / youtube_dl / 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 int_or_none,
16 unsmuggle_url,
17 smuggle_url,
18 )
19
20
21 class KalturaIE(InfoExtractor):
22 _VALID_URL = r'''(?x)
23 (?:
24 kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)|
25 https?://
26 (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/
27 (?:
28 (?:
29 # flash player
30 index\.php/(?:kwidget|extwidget/preview)|
31 # html5 player
32 html5/html5lib/[^/]+/mwEmbedFrame\.php
33 )
34 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
35 )
36 '''
37 _SERVICE_URL = 'http://cdnapi.kaltura.com'
38 _SERVICE_BASE = '/api_v3/index.php'
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 }
45 _TESTS = [
46 {
47 'url': 'kaltura:269692:1_1jc2y3e4',
48 'md5': '3adcbdb3dcc02d647539e53f284ba171',
49 'info_dict': {
50 'id': '1_1jc2y3e4',
51 'ext': 'mp4',
52 'title': 'Straight from the Heart',
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 },
64 {
65 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
66 'only_matching': True,
67 },
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,
71 },
72 {
73 # video with subtitles
74 'url': 'kaltura:111032:1_cw786r8q',
75 'only_matching': True,
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 'skip': 'Gone. Maybe https://www.safaribooksonline.com/library/tutorials/introduction-to-python-anon/3469/',
95 'params': {
96 'skip_download': True,
97 },
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,
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,
106 }
107 ]
108
109 @staticmethod
110 def _extract_url(webpage):
111 # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
112 mobj = (
113 re.search(
114 r"""(?xs)
115 kWidget\.(?:thumb)?[Ee]mbed\(
116 \{.*?
117 (?P<q1>['"])wid(?P=q1)\s*:\s*
118 (?P<q2>['"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
119 (?P<q3>['"])entry_?[Ii]d(?P=q3)\s*:\s*
120 (?P<q4>['"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
121 """, webpage) or
122 re.search(
123 r'''(?xs)
124 (?P<q1>["'])
125 (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
126 (?P=q1).*?
127 (?:
128 (?:
129 entry_?[Ii]d|
130 (?P<q2>["'])entry_?[Ii]d(?P=q2)
131 )\s*:\s*|
132 \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
133 )
134 (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
135 ''', webpage) or
136 re.search(
137 r'''(?xs)
138 <(?:iframe[^>]+src|meta[^>]+\bcontent)=(?P<q1>["'])
139 (?:https?:)?//(?:(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)
140 (?:(?!(?P=q1)).)*
141 [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
142 (?:(?!(?P=q1)).)*
143 (?P=q1)
144 ''', webpage)
145 )
146 if mobj:
147 embed_info = mobj.groupdict()
148 url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
149 escaped_pid = re.escape(embed_info['partner_id'])
150 service_url = re.search(
151 r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
152 webpage)
153 if service_url:
154 url = smuggle_url(url, {'service_url': service_url.group(1)})
155 return url
156
157 def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
158 params = actions[0]
159 if len(actions) > 1:
160 for i, a in enumerate(actions[1:], start=1):
161 for k, v in a.items():
162 params['%d:%s' % (i, k)] = v
163
164 data = self._download_json(
165 (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
166 video_id, query=params, *args, **kwargs)
167
168 status = data if len(actions) == 1 else data[0]
169 if status.get('objectType') == 'KalturaAPIException':
170 raise ExtractorError(
171 '%s said: %s' % (self.IE_NAME, status['message']))
172
173 return data
174
175 def _get_video_info(self, video_id, partner_id, service_url=None):
176 actions = [
177 {
178 'action': 'null',
179 'apiVersion': '3.1.5',
180 'clientTag': 'kdp:v3.8.5',
181 'format': 1, # JSON, 2 = XML, 3 = PHP
182 'service': 'multirequest',
183 },
184 {
185 'expiry': 86400,
186 'service': 'session',
187 'action': 'startWidgetSession',
188 'widgetId': '_%s' % partner_id,
189 },
190 {
191 'action': 'get',
192 'entryId': video_id,
193 'service': 'baseentry',
194 'ks': '{1:result:ks}',
195 },
196 {
197 'action': 'getbyentryid',
198 'entryId': video_id,
199 'service': 'flavorAsset',
200 'ks': '{1:result:ks}',
201 },
202 {
203 'action': 'list',
204 'filter:entryIdEqual': video_id,
205 'service': 'caption_captionasset',
206 'ks': '{1:result:ks}',
207 },
208 ]
209 return self._kaltura_api_call(
210 video_id, actions, service_url, note='Downloading video info JSON')
211
212 def _real_extract(self, url):
213 url, smuggled_data = unsmuggle_url(url, {})
214
215 mobj = re.match(self._VALID_URL, url)
216 partner_id, entry_id = mobj.group('partner_id', 'id')
217 ks = None
218 captions = None
219 if partner_id and entry_id:
220 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
221 else:
222 path, query = mobj.group('path', 'query')
223 if not path and not query:
224 raise ExtractorError('Invalid URL', expected=True)
225 params = {}
226 if query:
227 params = compat_parse_qs(query)
228 if path:
229 splitted_path = path.split('/')
230 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
231 if 'wid' in params:
232 partner_id = params['wid'][0][1:]
233 elif 'p' in params:
234 partner_id = params['p'][0]
235 elif 'partner_id' in params:
236 partner_id = params['partner_id'][0]
237 else:
238 raise ExtractorError('Invalid URL', expected=True)
239 if 'entry_id' in params:
240 entry_id = params['entry_id'][0]
241 _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
242 elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
243 reference_id = params['flashvars[referenceId]'][0]
244 webpage = self._download_webpage(url, reference_id)
245 entry_data = self._parse_json(self._search_regex(
246 r'window\.kalturaIframePackageData\s*=\s*({.*});',
247 webpage, 'kalturaIframePackageData'),
248 reference_id)['entryResult']
249 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
250 entry_id = info['id']
251 # Unfortunately, data returned in kalturaIframePackageData lacks
252 # captions so we will try requesting the complete data using
253 # regular approach since we now know the entry_id
254 try:
255 _, info, flavor_assets, captions = self._get_video_info(
256 entry_id, partner_id)
257 except ExtractorError:
258 # Regular scenario failed but we already have everything
259 # extracted apart from captions and can process at least
260 # with this
261 pass
262 else:
263 raise ExtractorError('Invalid URL', expected=True)
264 ks = params.get('flashvars[ks]', [None])[0]
265
266 source_url = smuggled_data.get('source_url')
267 if source_url:
268 referrer = base64.b64encode(
269 '://'.join(compat_urlparse.urlparse(source_url)[:2])
270 .encode('utf-8')).decode('utf-8')
271 else:
272 referrer = None
273
274 def sign_url(unsigned_url):
275 if ks:
276 unsigned_url += '/ks/%s' % ks
277 if referrer:
278 unsigned_url += '?referrer=%s' % referrer
279 return unsigned_url
280
281 data_url = info['dataUrl']
282 if '/flvclipper/' in data_url:
283 data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
284
285 formats = []
286 for f in flavor_assets:
287 # Continue if asset is not ready
288 if f.get('status') != 2:
289 continue
290 # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
291 # skip for now.
292 if f.get('fileExt') == 'chun':
293 continue
294 # DRM-protected video, cannot be decrypted
295 if f.get('fileExt') == 'wvm':
296 continue
297 if not f.get('fileExt'):
298 # QT indicates QuickTime; some videos have broken fileExt
299 if f.get('containerFormat') == 'qt':
300 f['fileExt'] = 'mov'
301 else:
302 f['fileExt'] = 'mp4'
303 video_url = sign_url(
304 '%s/flavorId/%s' % (data_url, f['id']))
305 # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
306 # -f mp4-56)
307 vcodec = 'none' if 'videoCodecId' not in f and f.get(
308 'frameRate') == 0 else f.get('videoCodecId')
309 formats.append({
310 'format_id': '%(fileExt)s-%(bitrate)s' % f,
311 'ext': f.get('fileExt'),
312 'tbr': int_or_none(f['bitrate']),
313 'fps': int_or_none(f.get('frameRate')),
314 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
315 'container': f.get('containerFormat'),
316 'vcodec': vcodec,
317 'height': int_or_none(f.get('height')),
318 'width': int_or_none(f.get('width')),
319 'url': video_url,
320 })
321 if '/playManifest/' in data_url:
322 m3u8_url = sign_url(data_url.replace(
323 'format/url', 'format/applehttp'))
324 formats.extend(self._extract_m3u8_formats(
325 m3u8_url, entry_id, 'mp4', 'm3u8_native',
326 m3u8_id='hls', fatal=False))
327
328 self._sort_formats(formats)
329
330 subtitles = {}
331 if captions:
332 for caption in captions.get('objects', []):
333 # Continue if caption is not ready
334 if caption.get('status') != 2:
335 continue
336 if not caption.get('id'):
337 continue
338 caption_format = int_or_none(caption.get('format'))
339 subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
340 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
341 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
342 })
343
344 return {
345 'id': entry_id,
346 'title': info['name'],
347 'formats': formats,
348 'subtitles': subtitles,
349 'description': clean_html(info.get('description')),
350 'thumbnail': info.get('thumbnailUrl'),
351 'duration': info.get('duration'),
352 'timestamp': info.get('createdAt'),
353 'uploader_id': info.get('userId') if info.get('userId') != 'None' else None,
354 'view_count': info.get('plays'),
355 }