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