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