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