[kaltura] add support videos stored on custom kaltura servers(closes #5557)
[youtube-dl] / 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/
27                         (?:
28                             (?:
29                                 # flash player
30                                 index\.php/kwidget|
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     _TESTS = [
40         {
41             'url': 'kaltura:269692:1_1jc2y3e4',
42             'md5': '3adcbdb3dcc02d647539e53f284ba171',
43             'info_dict': {
44                 'id': '1_1jc2y3e4',
45                 'ext': 'mp4',
46                 'title': 'Straight from the Heart',
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         },
58         {
59             'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
60             'only_matching': True,
61         },
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,
65         }
66     ]
67
68     @staticmethod
69     def _extract_url(webpage):
70         mobj = (
71             re.search(
72                 r"""(?xs)
73                     kWidget\.(?:thumb)?[Ee]mbed\(
74                     \{.*?
75                         (?P<q1>['\"])wid(?P=q1)\s*:\s*
76                         (?P<q2>['\"])_?(?P<partner_id>[^'\"]+)(?P=q2),.*?
77                         (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
78                         (?P<q4>['\"])(?P<id>[^'\"]+)(?P=q4),
79                 """, webpage) or
80             re.search(
81                 r'''(?xs)
82                     (?P<q1>["\'])
83                         (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com/.*?(?:p|partner_id)/(?P<partner_id>\d+).*?
84                     (?P=q1).*?
85                     (?:
86                         entry_?[Ii]d|
87                         (?P<q2>["\'])entry_?[Ii]d(?P=q2)
88                     )\s*:\s*
89                     (?P<q3>["\'])(?P<id>.+?)(?P=q3)
90                 ''', webpage))
91         if mobj:
92             embed_info = mobj.groupdict()
93             url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
94             service_url = re.search(
95                 '<script[^>]+src=(?:["\'])((?:https?:)?//.+?)/p/%(partner_id)s/sp/%(partner_id)s00/embedIframeJs' % embed_info,
96                 webpage)
97             if service_url:
98                 url = smuggle_url(url, {'service_url': service_url.group(1)})
99             return url
100
101     def _kaltura_api_call(self, video_id, actions, *args, **kwargs):
102         params = actions[0]
103         if len(actions) > 1:
104             for i, a in enumerate(actions[1:], start=1):
105                 for k, v in a.items():
106                     params['%d:%s' % (i, k)] = v
107
108         data = self._download_json(
109             self._SERVICE_URL + self._SERVICE_BASE,
110             video_id, query=params, *args, **kwargs)
111
112         status = data if len(actions) == 1 else data[0]
113         if status.get('objectType') == 'KalturaAPIException':
114             raise ExtractorError(
115                 '%s said: %s' % (self.IE_NAME, status['message']))
116
117         return data
118
119     def _get_kaltura_signature(self, video_id, partner_id):
120         actions = [{
121             'apiVersion': '3.1',
122             'expiry': 86400,
123             'format': 1,
124             'service': 'session',
125             'action': 'startWidgetSession',
126             'widgetId': '_%s' % partner_id,
127         }]
128         return self._kaltura_api_call(
129             video_id, actions, note='Downloading Kaltura signature')['ks']
130
131     def _get_video_info(self, video_id, partner_id):
132         signature = self._get_kaltura_signature(video_id, partner_id)
133         actions = [
134             {
135                 'action': 'null',
136                 'apiVersion': '3.1.5',
137                 'clientTag': 'kdp:v3.8.5',
138                 'format': 1,  # JSON, 2 = XML, 3 = PHP
139                 'service': 'multirequest',
140                 'ks': signature,
141             },
142             {
143                 'action': 'get',
144                 'entryId': video_id,
145                 'service': 'baseentry',
146                 'version': '-1',
147             },
148             {
149                 'action': 'getbyentryid',
150                 'entryId': video_id,
151                 'service': 'flavorAsset',
152             },
153         ]
154         return self._kaltura_api_call(
155             video_id, actions, note='Downloading video info JSON')
156
157     def _real_extract(self, url):
158         url, smuggled_data = unsmuggle_url(url, {})
159         service_url = smuggled_data.get('service_url')
160         if service_url:
161             self._SERVICE_URL = service_url
162
163         mobj = re.match(self._VALID_URL, url)
164         partner_id, entry_id = mobj.group('partner_id', 'id')
165         ks = None
166         if partner_id and entry_id:
167             info, flavor_assets = self._get_video_info(entry_id, partner_id)
168         else:
169             path, query = mobj.group('path', 'query')
170             if not path and not query:
171                 raise ExtractorError('Invalid URL', expected=True)
172             params = {}
173             if query:
174                 params = compat_parse_qs(query)
175             if path:
176                 splitted_path = path.split('/')
177                 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
178             if 'wid' in params:
179                 partner_id = params['wid'][0][1:]
180             elif 'p' in params:
181                 partner_id = params['p'][0]
182             else:
183                 raise ExtractorError('Invalid URL', expected=True)
184             if 'entry_id' in params:
185                 entry_id = params['entry_id'][0]
186                 info, flavor_assets = self._get_video_info(entry_id, partner_id)
187             elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
188                 reference_id = params['flashvars[referenceId]'][0]
189                 webpage = self._download_webpage(url, reference_id)
190                 entry_data = self._parse_json(self._search_regex(
191                     r'window\.kalturaIframePackageData\s*=\s*({.*});',
192                     webpage, 'kalturaIframePackageData'),
193                     reference_id)['entryResult']
194                 info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
195                 entry_id = info['id']
196             else:
197                 raise ExtractorError('Invalid URL', expected=True)
198             ks = params.get('flashvars[ks]', [None])[0]
199
200         source_url = smuggled_data.get('source_url')
201         if source_url:
202             referrer = base64.b64encode(
203                 '://'.join(compat_urlparse.urlparse(source_url)[:2])
204                 .encode('utf-8')).decode('utf-8')
205         else:
206             referrer = None
207
208         def sign_url(unsigned_url):
209             if ks:
210                 unsigned_url += '/ks/%s' % ks
211             if referrer:
212                 unsigned_url += '?referrer=%s' % referrer
213             return unsigned_url
214
215         data_url = info['dataUrl']
216         if '/flvclipper/' in data_url:
217             data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
218
219         formats = []
220         for f in flavor_assets:
221             # Continue if asset is not ready
222             if f['status'] != 2:
223                 continue
224             video_url = sign_url(
225                 '%s/flavorId/%s' % (data_url, f['id']))
226             formats.append({
227                 'format_id': '%(fileExt)s-%(bitrate)s' % f,
228                 'ext': f.get('fileExt'),
229                 'tbr': int_or_none(f['bitrate']),
230                 'fps': int_or_none(f.get('frameRate')),
231                 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
232                 'container': f.get('containerFormat'),
233                 'vcodec': f.get('videoCodecId'),
234                 'height': int_or_none(f.get('height')),
235                 'width': int_or_none(f.get('width')),
236                 'url': video_url,
237             })
238         if '/playManifest/' in data_url:
239             m3u8_url = sign_url(data_url.replace(
240                 'format/url', 'format/applehttp'))
241             formats.extend(self._extract_m3u8_formats(
242                 m3u8_url, entry_id, 'mp4', 'm3u8_native',
243                 m3u8_id='hls', fatal=False))
244
245         self._check_formats(formats, entry_id)
246         self._sort_formats(formats)
247
248         return {
249             'id': entry_id,
250             'title': info['name'],
251             'formats': formats,
252             'description': clean_html(info.get('description')),
253             'thumbnail': info.get('thumbnailUrl'),
254             'duration': info.get('duration'),
255             'timestamp': info.get('createdAt'),
256             'uploader_id': info.get('userId'),
257             'view_count': info.get('plays'),
258         }