]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/nexx.py
d/p/remove-autoupdate-mechanism.patch: Update patch with metadata at the top.
[youtubedl] / youtube_dl / extractor / nexx.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hashlib
5 import random
6 import re
7 import time
8
9 from .common import InfoExtractor
10 from ..compat import compat_str
11 from ..utils import (
12 ExtractorError,
13 int_or_none,
14 parse_duration,
15 try_get,
16 urlencode_postdata,
17 )
18
19
20 class NexxIE(InfoExtractor):
21 _VALID_URL = r'''(?x)
22 (?:
23 https?://api\.nexx(?:\.cloud|cdn\.com)/v3/(?P<domain_id>\d+)/videos/byid/|
24 nexx:(?:(?P<domain_id_s>\d+):)?|
25 https?://arc\.nexx\.cloud/api/video/
26 )
27 (?P<id>\d+)
28 '''
29 _TESTS = [{
30 # movie
31 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
32 'md5': '828cea195be04e66057b846288295ba1',
33 'info_dict': {
34 'id': '128907',
35 'ext': 'mp4',
36 'title': 'Stiftung Warentest',
37 'alt_title': 'Wie ein Test abläuft',
38 'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
39 'release_year': 2013,
40 'creator': 'SPIEGEL TV',
41 'thumbnail': r're:^https?://.*\.jpg$',
42 'duration': 2509,
43 'timestamp': 1384264416,
44 'upload_date': '20131112',
45 },
46 }, {
47 # episode
48 'url': 'https://api.nexx.cloud/v3/741/videos/byid/247858',
49 'info_dict': {
50 'id': '247858',
51 'ext': 'mp4',
52 'title': 'Return of the Golden Child (OV)',
53 'description': 'md5:5d969537509a92b733de21bae249dc63',
54 'release_year': 2017,
55 'thumbnail': r're:^https?://.*\.jpg$',
56 'duration': 1397,
57 'timestamp': 1495033267,
58 'upload_date': '20170517',
59 'episode_number': 2,
60 'season_number': 2,
61 },
62 'params': {
63 'skip_download': True,
64 },
65 }, {
66 # does not work via arc
67 'url': 'nexx:741:1269984',
68 'md5': 'c714b5b238b2958dc8d5642addba6886',
69 'info_dict': {
70 'id': '1269984',
71 'ext': 'mp4',
72 'title': '1 TAG ohne KLO... wortwörtlich! 😑',
73 'alt_title': '1 TAG ohne KLO... wortwörtlich! 😑',
74 'description': 'md5:4604539793c49eda9443ab5c5b1d612f',
75 'thumbnail': r're:^https?://.*\.jpg$',
76 'duration': 607,
77 'timestamp': 1518614955,
78 'upload_date': '20180214',
79 },
80 }, {
81 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
82 'only_matching': True,
83 }, {
84 'url': 'nexx:748:128907',
85 'only_matching': True,
86 }, {
87 'url': 'nexx:128907',
88 'only_matching': True,
89 }, {
90 'url': 'https://arc.nexx.cloud/api/video/128907.json',
91 'only_matching': True,
92 }]
93
94 @staticmethod
95 def _extract_domain_id(webpage):
96 mobj = re.search(
97 r'<script\b[^>]+\bsrc=["\'](?:https?:)?//require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
98 webpage)
99 return mobj.group('id') if mobj else None
100
101 @staticmethod
102 def _extract_urls(webpage):
103 # Reference:
104 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
105
106 entries = []
107
108 # JavaScript Integration
109 domain_id = NexxIE._extract_domain_id(webpage)
110 if domain_id:
111 for video_id in re.findall(
112 r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
113 webpage):
114 entries.append(
115 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
116 % (domain_id, video_id))
117
118 # TODO: support more embed formats
119
120 return entries
121
122 @staticmethod
123 def _extract_url(webpage):
124 return NexxIE._extract_urls(webpage)[0]
125
126 def _handle_error(self, response):
127 status = int_or_none(try_get(
128 response, lambda x: x['metadata']['status']) or 200)
129 if 200 <= status < 300:
130 return
131 raise ExtractorError(
132 '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
133 expected=True)
134
135 def _call_api(self, domain_id, path, video_id, data=None, headers={}):
136 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
137 result = self._download_json(
138 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
139 'Downloading %s JSON' % path, data=urlencode_postdata(data),
140 headers=headers)
141 self._handle_error(result)
142 return result['result']
143
144 def _real_extract(self, url):
145 mobj = re.match(self._VALID_URL, url)
146 domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
147 video_id = mobj.group('id')
148
149 video = None
150
151 response = self._download_json(
152 'https://arc.nexx.cloud/api/video/%s.json' % video_id,
153 video_id, fatal=False)
154 if response and isinstance(response, dict):
155 result = response.get('result')
156 if result and isinstance(result, dict):
157 video = result
158
159 # not all videos work via arc, e.g. nexx:741:1269984
160 if not video:
161 # Reverse engineered from JS code (see getDeviceID function)
162 device_id = '%d:%d:%d%d' % (
163 random.randint(1, 4), int(time.time()),
164 random.randint(1e4, 99999), random.randint(1, 9))
165
166 result = self._call_api(domain_id, 'session/init', video_id, data={
167 'nxp_devh': device_id,
168 'nxp_userh': '',
169 'precid': '0',
170 'playlicense': '0',
171 'screenx': '1920',
172 'screeny': '1080',
173 'playerversion': '6.0.00',
174 'gateway': 'html5',
175 'adGateway': '',
176 'explicitlanguage': 'en-US',
177 'addTextTemplates': '1',
178 'addDomainData': '1',
179 'addAdModel': '1',
180 }, headers={
181 'X-Request-Enable-Auth-Fallback': '1',
182 })
183
184 cid = result['general']['cid']
185
186 # As described in [1] X-Request-Token generation algorithm is
187 # as follows:
188 # md5( operation + domain_id + domain_secret )
189 # where domain_secret is a static value that will be given by nexx.tv
190 # as per [1]. Here is how this "secret" is generated (reversed
191 # from _play.api.init function, search for clienttoken). So it's
192 # actually not static and not that much of a secret.
193 # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
194 secret = result['device']['clienttoken'][int(device_id[0]):]
195 secret = secret[0:len(secret) - int(device_id[-1])]
196
197 op = 'byid'
198
199 # Reversed from JS code for _play.api.call function (search for
200 # X-Request-Token)
201 request_token = hashlib.md5(
202 ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
203
204 video = self._call_api(
205 domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
206 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
207 'addInteractionOptions': '1',
208 'addStatusDetails': '1',
209 'addStreamDetails': '1',
210 'addCaptions': '1',
211 'addScenes': '1',
212 'addHotSpots': '1',
213 'addBumpers': '1',
214 'captionFormat': 'data',
215 }, headers={
216 'X-Request-CID': cid,
217 'X-Request-Token': request_token,
218 })
219
220 general = video['general']
221 title = general['title']
222
223 stream_data = video['streamdata']
224 language = general.get('language_raw') or ''
225
226 # TODO: reverse more cdns
227
228 cdn = stream_data['cdnType']
229 assert cdn == 'azure'
230
231 azure_locator = stream_data['azureLocator']
232
233 AZURE_URL = 'http://nx%s%02d.akamaized.net/'
234
235 def get_cdn_shield_base(shield_type='', prefix='-p'):
236 for secure in ('', 's'):
237 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
238 if cdn_shield:
239 return 'http%s://%s' % (secure, cdn_shield)
240 else:
241 return AZURE_URL % (prefix, int(stream_data['azureAccount'].replace('nexxplayplus', '')))
242
243 azure_stream_base = get_cdn_shield_base()
244 is_ml = ',' in language
245 azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
246 azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
247
248 protection_token = try_get(
249 video, lambda x: x['protectiondata']['token'], compat_str)
250 if protection_token:
251 azure_manifest_url += '?hdnts=%s' % protection_token
252
253 formats = self._extract_m3u8_formats(
254 azure_manifest_url % '(format=m3u8-aapl)',
255 video_id, 'mp4', 'm3u8_native',
256 m3u8_id='%s-hls' % cdn, fatal=False)
257 formats.extend(self._extract_mpd_formats(
258 azure_manifest_url % '(format=mpd-time-csf)',
259 video_id, mpd_id='%s-dash' % cdn, fatal=False))
260 formats.extend(self._extract_ism_formats(
261 azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
262
263 azure_progressive_base = get_cdn_shield_base('Prog', '-d')
264 azure_file_distribution = stream_data.get('azureFileDistribution')
265 if azure_file_distribution:
266 fds = azure_file_distribution.split(',')
267 if fds:
268 for fd in fds:
269 ss = fd.split(':')
270 if len(ss) == 2:
271 tbr = int_or_none(ss[0])
272 if tbr:
273 f = {
274 'url': '%s%s/%s_src_%s_%d.mp4' % (
275 azure_progressive_base, azure_locator, video_id, ss[1], tbr),
276 'format_id': '%s-http-%d' % (cdn, tbr),
277 'tbr': tbr,
278 }
279 width_height = ss[1].split('x')
280 if len(width_height) == 2:
281 f.update({
282 'width': int_or_none(width_height[0]),
283 'height': int_or_none(width_height[1]),
284 })
285 formats.append(f)
286
287 self._sort_formats(formats)
288
289 return {
290 'id': video_id,
291 'title': title,
292 'alt_title': general.get('subtitle'),
293 'description': general.get('description'),
294 'release_year': int_or_none(general.get('year')),
295 'creator': general.get('studio') or general.get('studio_adref'),
296 'thumbnail': try_get(
297 video, lambda x: x['imagedata']['thumb'], compat_str),
298 'duration': parse_duration(general.get('runtime')),
299 'timestamp': int_or_none(general.get('uploaded')),
300 'episode_number': int_or_none(try_get(
301 video, lambda x: x['episodedata']['episode'])),
302 'season_number': int_or_none(try_get(
303 video, lambda x: x['episodedata']['season'])),
304 'formats': formats,
305 }
306
307
308 class NexxEmbedIE(InfoExtractor):
309 _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
310 _TEST = {
311 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
312 'md5': '16746bfc28c42049492385c989b26c4a',
313 'info_dict': {
314 'id': '161464',
315 'ext': 'mp4',
316 'title': 'Nervenkitzel Achterbahn',
317 'alt_title': 'Karussellbauer in Deutschland',
318 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
319 'release_year': 2005,
320 'creator': 'SPIEGEL TV',
321 'thumbnail': r're:^https?://.*\.jpg$',
322 'duration': 2761,
323 'timestamp': 1394021479,
324 'upload_date': '20140305',
325 },
326 'params': {
327 'format': 'bestvideo',
328 'skip_download': True,
329 },
330 }
331
332 @staticmethod
333 def _extract_urls(webpage):
334 # Reference:
335 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
336
337 # iFrame Embed Integration
338 return [mobj.group('url') for mobj in re.finditer(
339 r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
340 webpage)]
341
342 def _real_extract(self, url):
343 embed_id = self._match_id(url)
344
345 webpage = self._download_webpage(url, embed_id)
346
347 return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())