]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/nexx.py
[ie/orf:on] Improve extraction (#9677)
[yt-dlp.git] / yt_dlp / extractor / nexx.py
1 import hashlib
2 import random
3 import re
4 import time
5
6 from .common import InfoExtractor
7 from ..compat import compat_str
8 from ..utils import (
9 ExtractorError,
10 int_or_none,
11 parse_duration,
12 srt_subtitles_timecode,
13 traverse_obj,
14 try_get,
15 urlencode_postdata,
16 )
17
18
19 class NexxIE(InfoExtractor):
20 _VALID_URL = r'''(?x)
21 (?:
22 https?://api\.nexx(?:\.cloud|cdn\.com)/v3(?:\.\d)?/(?P<domain_id>\d+)/videos/byid/|
23 nexx:(?:(?P<domain_id_s>\d+):)?|
24 https?://arc\.nexx\.cloud/api/video/
25 )
26 (?P<id>\d+)
27 '''
28 _TESTS = [{
29 # movie
30 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
31 'md5': '31899fd683de49ad46f4ee67e53e83fe',
32 'info_dict': {
33 'id': '128907',
34 'ext': 'mp4',
35 'title': 'Stiftung Warentest',
36 'alt_title': 'Wie ein Test abläuft',
37 'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
38 'creator': 'SPIEGEL TV',
39 'thumbnail': r're:^https?://.*\.jpg$',
40 'duration': 2509,
41 'timestamp': 1384264416,
42 'upload_date': '20131112',
43 },
44 'skip': 'Spiegel nexx CDNs are now disabled'
45 }, {
46 # episode with captions
47 'url': 'https://api.nexx.cloud/v3.1/741/videos/byid/1701834',
48 'info_dict': {
49 'id': '1701834',
50 'ext': 'mp4',
51 'title': 'Mein Leben mit \'nem TikTok E-Boy 😤',
52 'alt_title': 'Mein Leben mit \'nem TikTok E-Boy 😤',
53 'description': 'md5:f84f395a881fd143f952c892deab528d',
54 'thumbnail': r're:^https?://.*\.jpg$',
55 'duration': 770,
56 'timestamp': 1595600027,
57 'upload_date': '20200724',
58 'episode_number': 2,
59 'season_number': 2,
60 'episode': 'Episode 2',
61 'season': 'Season 2',
62 },
63 'params': {
64 'skip_download': True,
65 },
66 }, {
67 'url': 'nexx:741:1269984',
68 'md5': 'd5f14e14b592501e51addd5abef95a7f',
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:2016393a31991a900946432ccdd09a6f',
75 'thumbnail': r're:^https?://.*\.jpg$',
76 'duration': 607,
77 'timestamp': 1518614955,
78 'upload_date': '20180214',
79 },
80 }, {
81 # free cdn from http://www.spiegel.de/video/eifel-zoo-aufregung-um-ausgebrochene-raubtiere-video-99018031.html
82 'url': 'nexx:747:1533779',
83 'md5': '6bf6883912b82b7069fb86c2297e9893',
84 'info_dict': {
85 'id': '1533779',
86 'ext': 'mp4',
87 'title': 'Aufregung um ausgebrochene Raubtiere',
88 'alt_title': 'Eifel-Zoo',
89 'description': 'md5:f21375c91c74ad741dcb164c427999d2',
90 'thumbnail': r're:^https?://.*\.jpg$',
91 'duration': 111,
92 'timestamp': 1527874460,
93 'upload_date': '20180601',
94 },
95 'skip': 'Spiegel nexx CDNs are now disabled'
96 }, {
97 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
98 'only_matching': True,
99 }, {
100 'url': 'nexx:748:128907',
101 'only_matching': True,
102 }, {
103 'url': 'nexx:128907',
104 'only_matching': True,
105 }, {
106 'url': 'https://arc.nexx.cloud/api/video/128907.json',
107 'only_matching': True,
108 }]
109
110 @staticmethod
111 def _extract_domain_id(webpage):
112 mobj = re.search(
113 r'<script\b[^>]+\bsrc=["\'](?:https?:)?//(?:require|arc)\.nexx(?:\.cloud|cdn\.com)/(?:sdk/)?(?P<id>\d+)',
114 webpage)
115 return mobj.group('id') if mobj else None
116
117 @classmethod
118 def _extract_embed_urls(cls, url, webpage):
119 # Reference:
120 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
121
122 entries = []
123
124 # JavaScript Integration
125 domain_id = NexxIE._extract_domain_id(webpage)
126 if domain_id:
127 for video_id in re.findall(
128 r'(?is)onPLAYReady.+?_play\.(?:init|(?:control\.)?addPlayer)\s*\(.+?\s*,\s*["\']?(\d+)',
129 webpage):
130 entries.append(
131 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
132 % (domain_id, video_id))
133
134 # TODO: support more embed formats
135
136 return entries
137
138 def _handle_error(self, response):
139 if traverse_obj(response, ('metadata', 'notice'), expected_type=str):
140 self.report_warning('%s said: %s' % (self.IE_NAME, response['metadata']['notice']))
141 status = int_or_none(try_get(
142 response, lambda x: x['metadata']['status']) or 200)
143 if 200 <= status < 300:
144 return
145 raise ExtractorError(
146 '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
147 expected=True)
148
149 def _call_api(self, domain_id, path, video_id, data=None, headers={}):
150 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
151 result = self._download_json(
152 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
153 'Downloading %s JSON' % path, data=urlencode_postdata(data),
154 headers=headers)
155 self._handle_error(result)
156 return result['result']
157
158 def _extract_free_formats(self, video, video_id):
159 stream_data = video['streamdata']
160 cdn = stream_data['cdnType']
161 assert cdn == 'free'
162
163 hash = video['general']['hash']
164
165 ps = compat_str(stream_data['originalDomain'])
166 if stream_data['applyFolderHierarchy'] == 1:
167 s = ('%04d' % int(video_id))[::-1]
168 ps += '/%s/%s' % (s[0:2], s[2:4])
169 ps += '/%s/%s_' % (video_id, hash)
170
171 t = 'http://%s' + ps
172 fd = stream_data['azureFileDistribution'].split(',')
173 cdn_provider = stream_data['cdnProvider']
174
175 def p0(p):
176 return '_%s' % p if stream_data['applyAzureStructure'] == 1 else ''
177
178 formats = []
179 if cdn_provider == 'ak':
180 t += ','
181 for i in fd:
182 p = i.split(':')
183 t += p[1] + p0(int(p[0])) + ','
184 t += '.mp4.csmil/master.%s'
185 elif cdn_provider == 'ce':
186 k = t.split('/')
187 h = k.pop()
188 http_base = t = '/'.join(k)
189 http_base = http_base % stream_data['cdnPathHTTP']
190 t += '/asset.ism/manifest.%s?dcp_ver=aos4&videostream='
191 for i in fd:
192 p = i.split(':')
193 tbr = int(p[0])
194 filename = '%s%s%s.mp4' % (h, p[1], p0(tbr))
195 f = {
196 'url': http_base + '/' + filename,
197 'format_id': '%s-http-%d' % (cdn, tbr),
198 'tbr': tbr,
199 }
200 width_height = p[1].split('x')
201 if len(width_height) == 2:
202 f.update({
203 'width': int_or_none(width_height[0]),
204 'height': int_or_none(width_height[1]),
205 })
206 formats.append(f)
207 a = filename + ':%s' % (tbr * 1000)
208 t += a + ','
209 t = t[:-1] + '&audiostream=' + a.split(':')[0]
210 else:
211 assert False
212
213 if cdn_provider == 'ce':
214 formats.extend(self._extract_mpd_formats(
215 t % (stream_data['cdnPathDASH'], 'mpd'), video_id,
216 mpd_id='%s-dash' % cdn, fatal=False))
217 formats.extend(self._extract_m3u8_formats(
218 t % (stream_data['cdnPathHLS'], 'm3u8'), video_id, 'mp4',
219 entry_protocol='m3u8_native', m3u8_id='%s-hls' % cdn, fatal=False))
220
221 return formats
222
223 def _extract_3q_formats(self, video, video_id):
224 stream_data = video['streamdata']
225 cdn = stream_data['cdnType']
226 assert cdn == '3q'
227
228 q_acc, q_prefix, q_locator, q_hash = stream_data['qAccount'], stream_data['qPrefix'], stream_data['qLocator'], stream_data['qHash']
229 protection_key = traverse_obj(
230 video, ('protectiondata', 'key'), expected_type=str)
231
232 def get_cdn_shield_base(shield_type=''):
233 for secure in ('', 's'):
234 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
235 if cdn_shield:
236 return 'http%s://%s' % (secure, cdn_shield)
237 return f'http://sdn-global-{"prog" if shield_type.lower() == "prog" else "streaming"}-cache.3qsdn.com/' + (f's/{protection_key}/' if protection_key else '')
238
239 stream_base = get_cdn_shield_base()
240
241 formats = []
242 formats.extend(self._extract_m3u8_formats(
243 f'{stream_base}{q_acc}/files/{q_prefix}/{q_locator}/{q_acc}-{stream_data.get("qHEVCHash") or q_hash}.ism/manifest.m3u8',
244 video_id, 'mp4', m3u8_id=f'{cdn}-hls', fatal=False))
245 formats.extend(self._extract_mpd_formats(
246 f'{stream_base}{q_acc}/files/{q_prefix}/{q_locator}/{q_acc}-{q_hash}.ism/manifest.mpd',
247 video_id, mpd_id=f'{cdn}-dash', fatal=False))
248
249 progressive_base = get_cdn_shield_base('Prog')
250 q_references = stream_data.get('qReferences') or ''
251 fds = q_references.split(',')
252 for fd in fds:
253 ss = fd.split(':')
254 if len(ss) != 3:
255 continue
256 tbr = int_or_none(ss[1], scale=1000)
257 formats.append({
258 'url': f'{progressive_base}{q_acc}/uploads/{q_acc}-{ss[2]}.webm',
259 'format_id': f'{cdn}-{ss[0]}{"-%s" % tbr if tbr else ""}',
260 'tbr': tbr,
261 })
262
263 azure_file_distribution = stream_data.get('azureFileDistribution') or ''
264 fds = azure_file_distribution.split(',')
265 for fd in fds:
266 ss = fd.split(':')
267 if len(ss) != 3:
268 continue
269 tbr = int_or_none(ss[0])
270 width, height = ss[1].split('x') if len(ss[1].split('x')) == 2 else (None, None)
271 f = {
272 'url': f'{progressive_base}{q_acc}/files/{q_prefix}/{q_locator}/{ss[2]}.mp4',
273 'format_id': f'{cdn}-http-{"-%s" % tbr if tbr else ""}',
274 'tbr': tbr,
275 'width': int_or_none(width),
276 'height': int_or_none(height),
277 }
278 formats.append(f)
279
280 return formats
281
282 def _extract_azure_formats(self, video, video_id):
283 stream_data = video['streamdata']
284 cdn = stream_data['cdnType']
285 assert cdn == 'azure'
286
287 azure_locator = stream_data['azureLocator']
288
289 def get_cdn_shield_base(shield_type='', static=False):
290 for secure in ('', 's'):
291 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
292 if cdn_shield:
293 return 'http%s://%s' % (secure, cdn_shield)
294 else:
295 if 'fb' in stream_data['azureAccount']:
296 prefix = 'df' if static else 'f'
297 else:
298 prefix = 'd' if static else 'p'
299 account = int(stream_data['azureAccount'].replace('nexxplayplus', '').replace('nexxplayfb', ''))
300 return 'http://nx-%s%02d.akamaized.net/' % (prefix, account)
301
302 language = video['general'].get('language_raw') or ''
303
304 azure_stream_base = get_cdn_shield_base()
305 is_ml = ',' in language
306 azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
307 azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
308
309 protection_token = try_get(
310 video, lambda x: x['protectiondata']['token'], compat_str)
311 if protection_token:
312 azure_manifest_url += '?hdnts=%s' % protection_token
313
314 formats = self._extract_m3u8_formats(
315 azure_manifest_url % '(format=m3u8-aapl)',
316 video_id, 'mp4', 'm3u8_native',
317 m3u8_id='%s-hls' % cdn, fatal=False)
318 formats.extend(self._extract_mpd_formats(
319 azure_manifest_url % '(format=mpd-time-csf)',
320 video_id, mpd_id='%s-dash' % cdn, fatal=False))
321 formats.extend(self._extract_ism_formats(
322 azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
323
324 azure_progressive_base = get_cdn_shield_base('Prog', True)
325 azure_file_distribution = stream_data.get('azureFileDistribution')
326 if azure_file_distribution:
327 fds = azure_file_distribution.split(',')
328 if fds:
329 for fd in fds:
330 ss = fd.split(':')
331 if len(ss) == 2:
332 tbr = int_or_none(ss[0])
333 if tbr:
334 f = {
335 'url': '%s%s/%s_src_%s_%d.mp4' % (
336 azure_progressive_base, azure_locator, video_id, ss[1], tbr),
337 'format_id': '%s-http-%d' % (cdn, tbr),
338 'tbr': tbr,
339 }
340 width_height = ss[1].split('x')
341 if len(width_height) == 2:
342 f.update({
343 'width': int_or_none(width_height[0]),
344 'height': int_or_none(width_height[1]),
345 })
346 formats.append(f)
347
348 return formats
349
350 def _real_extract(self, url):
351 mobj = self._match_valid_url(url)
352 domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
353 video_id = mobj.group('id')
354
355 video = None
356
357 def find_video(result):
358 if isinstance(result, dict):
359 return result
360 elif isinstance(result, list):
361 vid = int(video_id)
362 for v in result:
363 if try_get(v, lambda x: x['general']['ID'], int) == vid:
364 return v
365 return None
366
367 response = self._download_json(
368 'https://arc.nexx.cloud/api/video/%s.json' % video_id,
369 video_id, fatal=False)
370 if response and isinstance(response, dict):
371 result = response.get('result')
372 if result:
373 video = find_video(result)
374
375 # not all videos work via arc, e.g. nexx:741:1269984
376 if not video:
377 # Reverse engineered from JS code (see getDeviceID function)
378 device_id = '%d:%d:%d%d' % (
379 random.randint(1, 4), int(time.time()),
380 random.randint(1e4, 99999), random.randint(1, 9))
381
382 result = self._call_api(domain_id, 'session/init', video_id, data={
383 'nxp_devh': device_id,
384 'nxp_userh': '',
385 'precid': '0',
386 'playlicense': '0',
387 'screenx': '1920',
388 'screeny': '1080',
389 'playerversion': '6.0.00',
390 'gateway': 'html5',
391 'adGateway': '',
392 'explicitlanguage': 'en-US',
393 'addTextTemplates': '1',
394 'addDomainData': '1',
395 'addAdModel': '1',
396 }, headers={
397 'X-Request-Enable-Auth-Fallback': '1',
398 })
399
400 cid = result['general']['cid']
401
402 # As described in [1] X-Request-Token generation algorithm is
403 # as follows:
404 # md5( operation + domain_id + domain_secret )
405 # where domain_secret is a static value that will be given by nexx.tv
406 # as per [1]. Here is how this "secret" is generated (reversed
407 # from _play._factory.data.getDomainData function, search for
408 # domaintoken or enableAPIAccess). So it's actually not static
409 # and not that much of a secret.
410 # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
411 secret = result['device']['domaintoken'][int(device_id[0]):]
412 secret = secret[0:len(secret) - int(device_id[-1])]
413
414 op = 'byid'
415
416 # Reversed from JS code for _play.api.call function (search for
417 # X-Request-Token)
418 request_token = hashlib.md5(
419 ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
420
421 result = self._call_api(
422 domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
423 'additionalfields': 'language,channel,format,licenseby,slug,fileversion,episode,season',
424 'addInteractionOptions': '1',
425 'addStatusDetails': '1',
426 'addStreamDetails': '1',
427 'addFeatures': '1',
428 # Caption format selection doesn't seem to be enforced?
429 'addCaptions': 'vtt',
430 'addScenes': '1',
431 'addChapters': '1',
432 'addHotSpots': '1',
433 'addConnectedMedia': 'persons',
434 'addBumpers': '1',
435 }, headers={
436 'X-Request-CID': cid,
437 'X-Request-Token': request_token,
438 })
439 video = find_video(result)
440
441 general = video['general']
442 title = general['title']
443
444 cdn = video['streamdata']['cdnType']
445
446 if cdn == 'azure':
447 formats = self._extract_azure_formats(video, video_id)
448 elif cdn == 'free':
449 formats = self._extract_free_formats(video, video_id)
450 elif cdn == '3q':
451 formats = self._extract_3q_formats(video, video_id)
452 else:
453 self.raise_no_formats(f'{cdn} formats are currently not supported', video_id)
454
455 subtitles = {}
456 for sub in video.get('captiondata') or []:
457 if sub.get('data'):
458 subtitles.setdefault(sub.get('language', 'en'), []).append({
459 'ext': 'srt',
460 'data': '\n\n'.join(
461 f'{i + 1}\n{srt_subtitles_timecode(line["fromms"] / 1000)} --> {srt_subtitles_timecode(line["toms"] / 1000)}\n{line["caption"]}'
462 for i, line in enumerate(sub['data'])),
463 'name': sub.get('language_long') or sub.get('title')
464 })
465 elif sub.get('url'):
466 subtitles.setdefault(sub.get('language', 'en'), []).append({
467 'url': sub['url'],
468 'ext': sub.get('format'),
469 'name': sub.get('language_long') or sub.get('title')
470 })
471
472 return {
473 'id': video_id,
474 'title': title,
475 'alt_title': general.get('subtitle'),
476 'description': general.get('description'),
477 'release_year': int_or_none(general.get('year')),
478 'creator': general.get('studio') or general.get('studio_adref') or None,
479 'thumbnail': try_get(
480 video, lambda x: x['imagedata']['thumb'], compat_str),
481 'duration': parse_duration(general.get('runtime')),
482 'timestamp': int_or_none(general.get('uploaded')),
483 'episode_number': traverse_obj(
484 video, (('episodedata', 'general'), 'episode'), expected_type=int, get_all=False),
485 'season_number': traverse_obj(
486 video, (('episodedata', 'general'), 'season'), expected_type=int, get_all=False),
487 'cast': traverse_obj(video, ('connectedmedia', ..., 'title'), expected_type=str),
488 'formats': formats,
489 'subtitles': subtitles,
490 }
491
492
493 class NexxEmbedIE(InfoExtractor):
494 _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:video/)?(?P<id>[^/?#&]+)'
495 # Reference. https://nx-s.akamaized.net/files/201510/44.pdf
496 _EMBED_REGEX = [r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1']
497 _TESTS = [{
498 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
499 'md5': '16746bfc28c42049492385c989b26c4a',
500 'info_dict': {
501 'id': '161464',
502 'ext': 'mp4',
503 'title': 'Nervenkitzel Achterbahn',
504 'alt_title': 'Karussellbauer in Deutschland',
505 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
506 'creator': 'SPIEGEL TV',
507 'thumbnail': r're:^https?://.*\.jpg$',
508 'duration': 2761,
509 'timestamp': 1394021479,
510 'upload_date': '20140305',
511 },
512 'params': {
513 'skip_download': True,
514 },
515 }, {
516 'url': 'https://embed.nexx.cloud/11888/video/DSRTO7UVOX06S7',
517 'only_matching': True,
518 }]
519
520 def _real_extract(self, url):
521 embed_id = self._match_id(url)
522
523 webpage = self._download_webpage(url, embed_id)
524
525 return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())