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