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