]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/kaltura.py
[utils] Add PUTRequest
[yt-dlp.git] / youtube_dl / extractor / kaltura.py
CommitLineData
0d97ef43
NJ
1# coding: utf-8
2from __future__ import unicode_literals
3
4import re
01b06aed 5import base64
0d97ef43
NJ
6
7from .common import InfoExtractor
01b06aed 8from ..compat import (
15707c7e 9 compat_urllib_parse_urlencode,
01b06aed 10 compat_urlparse,
fac7e792 11 compat_parse_qs,
01b06aed 12)
0d97ef43 13from ..utils import (
bdceea7a 14 clean_html,
0d97ef43
NJ
15 ExtractorError,
16 int_or_none,
01b06aed 17 unsmuggle_url,
0d97ef43
NJ
18)
19
20
21class KalturaIE(InfoExtractor):
22 _VALID_URL = r'''(?x)
ee3ec091 23 (?:
fac7e792 24 kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)|
ee3ec091 25 https?://
b25f7533 26 (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/
ee3ec091
S
27 (?:
28 (?:
29 # flash player
fac7e792 30 index\.php/kwidget|
b184f944 31 # html5 player
fac7e792 32 html5/html5lib/[^/]+/mwEmbedFrame\.php
ae6a8021 33 )
fac7e792 34 )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
ee3ec091
S
35 )
36 '''
0d97ef43
NJ
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',
bb4b8c57 45 'title': 'Straight from the Heart',
0d97ef43
NJ
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 },
bd3749ed
S
57 {
58 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
59 'only_matching': True,
60 },
ef49b590 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 }
0d97ef43
NJ
65 ]
66
9ea5c04c
S
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
0d97ef43
NJ
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
15707c7e 100 query = compat_urllib_parse_urlencode(params)
0d97ef43
NJ
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 {
bb4b8c57 141 'action': 'getbyentryid',
0d97ef43 142 'entryId': video_id,
bb4b8c57 143 'service': 'flavorAsset',
0d97ef43
NJ
144 },
145 ]
146 return self._kaltura_api_call(
147 video_id, actions, note='Downloading video info JSON')
148
149 def _real_extract(self, url):
01b06aed
S
150 url, smuggled_data = unsmuggle_url(url, {})
151
0d97ef43 152 mobj = re.match(self._VALID_URL, url)
fac7e792 153 partner_id, entry_id = mobj.group('partner_id', 'id')
9dce3c09 154 ks = None
fac7e792 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('/')
e5a2e17a 166 params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
fac7e792 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)
9dce3c09 187 ks = params.get('flashvars[ks]', [None])[0]
0d97ef43 188
01b06aed
S
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
9dce3c09
S
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
01b06aed 204 formats = []
bb4b8c57 205 for f in flavor_assets:
206 # Continue if asset is not ready
207 if f['status'] != 2:
208 continue
9dce3c09 209 video_url = sign_url('%s/flavorId/%s' % (info['dataUrl'], f['id']))
01b06aed
S
210 formats.append({
211 'format_id': '%(fileExt)s-%(bitrate)s' % f,
d80a39ce
S
212 'ext': f.get('fileExt'),
213 'tbr': int_or_none(f['bitrate']),
214 'fps': int_or_none(f.get('frameRate')),
01b06aed
S
215 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
216 'container': f.get('containerFormat'),
217 'vcodec': f.get('videoCodecId'),
d80a39ce
S
218 'height': int_or_none(f.get('height')),
219 'width': int_or_none(f.get('width')),
01b06aed
S
220 'url': video_url,
221 })
9dce3c09 222 m3u8_url = sign_url(info['dataUrl'].replace('format/url', 'format/applehttp'))
7e5edcfd
S
223 formats.extend(self._extract_m3u8_formats(
224 m3u8_url, entry_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
bb4b8c57 225
01b06aed 226 self._check_formats(formats, entry_id)
0d97ef43
NJ
227 self._sort_formats(formats)
228
229 return {
ee3ec091 230 'id': entry_id,
0d97ef43
NJ
231 'title': info['name'],
232 'formats': formats,
bdceea7a 233 'description': clean_html(info.get('description')),
0d97ef43
NJ
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 }