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