]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nexx.py
[cleanup] Add more ruff rules (#10149)
[yt-dlp.git] / yt_dlp / extractor / nexx.py
CommitLineData
d91dd0ce
S
1import hashlib
2import random
4e826cd9 3import re
d91dd0ce 4import time
4e826cd9
S
5
6from .common import InfoExtractor
4e826cd9 7from ..utils import (
d91dd0ce 8 ExtractorError,
4e826cd9
S
9 int_or_none,
10 parse_duration,
0931ba94 11 srt_subtitles_timecode,
5f969a78 12 traverse_obj,
4e826cd9 13 try_get,
d91dd0ce 14 urlencode_postdata,
4e826cd9
S
15)
16
17
18class NexxIE(InfoExtractor):
694b6154
S
19 _VALID_URL = r'''(?x)
20 (?:
0931ba94 21 https?://api\.nexx(?:\.cloud|cdn\.com)/v3(?:\.\d)?/(?P<domain_id>\d+)/videos/byid/|
b5434b5c 22 nexx:(?:(?P<domain_id_s>\d+):)?|
0704306e 23 https?://arc\.nexx\.cloud/api/video/
694b6154
S
24 )
25 (?P<id>\d+)
26 '''
4e826cd9
S
27 _TESTS = [{
28 # movie
29 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
2e697530 30 'md5': '31899fd683de49ad46f4ee67e53e83fe',
4e826cd9
S
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',
4e826cd9
S
37 'creator': 'SPIEGEL TV',
38 'thumbnail': r're:^https?://.*\.jpg$',
39 'duration': 2509,
40 'timestamp': 1384264416,
41 'upload_date': '20131112',
42 },
add96eb9 43 'skip': 'Spiegel nexx CDNs are now disabled',
4e826cd9 44 }, {
0931ba94
M
45 # episode with captions
46 'url': 'https://api.nexx.cloud/v3.1/741/videos/byid/1701834',
4e826cd9 47 'info_dict': {
0931ba94 48 'id': '1701834',
4e826cd9 49 'ext': 'mp4',
0931ba94
M
50 'title': 'Mein Leben mit \'nem TikTok E-Boy 😤',
51 'alt_title': 'Mein Leben mit \'nem TikTok E-Boy 😤',
52 'description': 'md5:f84f395a881fd143f952c892deab528d',
4e826cd9 53 'thumbnail': r're:^https?://.*\.jpg$',
0931ba94
M
54 'duration': 770,
55 'timestamp': 1595600027,
56 'upload_date': '20200724',
4e826cd9
S
57 'episode_number': 2,
58 'season_number': 2,
0931ba94
M
59 'episode': 'Episode 2',
60 'season': 'Season 2',
4e826cd9
S
61 },
62 'params': {
4e826cd9
S
63 'skip_download': True,
64 },
d91dd0ce 65 }, {
d91dd0ce 66 'url': 'nexx:741:1269984',
0931ba94 67 'md5': 'd5f14e14b592501e51addd5abef95a7f',
d91dd0ce
S
68 'info_dict': {
69 'id': '1269984',
70 'ext': 'mp4',
0931ba94
M
71 'title': '1 TAG ohne KLO... wortwörtlich! ?',
72 'alt_title': '1 TAG ohne KLO... wortwörtlich! ?',
73 'description': 'md5:2016393a31991a900946432ccdd09a6f',
d91dd0ce
S
74 'thumbnail': r're:^https?://.*\.jpg$',
75 'duration': 607,
76 'timestamp': 1518614955,
77 'upload_date': '20180214',
78 },
06ea7bdd
S
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',
93 },
add96eb9 94 'skip': 'Spiegel nexx CDNs are now disabled',
4e826cd9
S
95 }, {
96 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
97 'only_matching': True,
694b6154
S
98 }, {
99 'url': 'nexx:748:128907',
100 'only_matching': True,
9dc7ea32
S
101 }, {
102 'url': 'nexx:128907',
103 'only_matching': True,
0704306e
S
104 }, {
105 'url': 'https://arc.nexx.cloud/api/video/128907.json',
106 'only_matching': True,
4e826cd9
S
107 }]
108
694b6154
S
109 @staticmethod
110 def _extract_domain_id(webpage):
111 mobj = re.search(
eb22d1b5 112 r'<script\b[^>]+\bsrc=["\'](?:https?:)?//(?:require|arc)\.nexx(?:\.cloud|cdn\.com)/(?:sdk/)?(?P<id>\d+)',
694b6154
S
113 webpage)
114 return mobj.group('id') if mobj else None
115
bfd973ec 116 @classmethod
117 def _extract_embed_urls(cls, url, webpage):
4e826cd9
S
118 # Reference:
119 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
120
121 entries = []
122
123 # JavaScript Integration
694b6154
S
124 domain_id = NexxIE._extract_domain_id(webpage)
125 if domain_id:
089b97cf 126 for video_id in re.findall(
eb22d1b5 127 r'(?is)onPLAYReady.+?_play\.(?:init|(?:control\.)?addPlayer)\s*\(.+?\s*,\s*["\']?(\d+)',
089b97cf
S
128 webpage):
129 entries.append(
add96eb9 130 f'https://api.nexx.cloud/v3/{domain_id}/videos/byid/{video_id}')
4e826cd9
S
131
132 # TODO: support more embed formats
133
134 return entries
135
d91dd0ce 136 def _handle_error(self, response):
0931ba94 137 if traverse_obj(response, ('metadata', 'notice'), expected_type=str):
add96eb9 138 self.report_warning('{} said: {}'.format(self.IE_NAME, response['metadata']['notice']))
d91dd0ce
S
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(
add96eb9 144 '{} said: {}'.format(self.IE_NAME, response['metadata']['errorhint']),
d91dd0ce
S
145 expected=True)
146
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(
add96eb9 150 f'https://api.nexx.cloud/v3/{domain_id}/{path}', video_id,
151 f'Downloading {path} JSON', data=urlencode_postdata(data),
d91dd0ce
S
152 headers=headers)
153 self._handle_error(result)
154 return result['result']
155
06ea7bdd
S
156 def _extract_free_formats(self, video, video_id):
157 stream_data = video['streamdata']
158 cdn = stream_data['cdnType']
159 assert cdn == 'free'
160
add96eb9 161 video_hash = video['general']['hash']
06ea7bdd 162
add96eb9 163 ps = str(stream_data['originalDomain'])
06ea7bdd
S
164 if stream_data['applyFolderHierarchy'] == 1:
165 s = ('%04d' % int(video_id))[::-1]
add96eb9 166 ps += f'/{s[0:2]}/{s[2:4]}'
167 ps += f'/{video_id}/{video_hash}_'
06ea7bdd 168
9afd74d7
RA
169 t = 'http://%s' + ps
170 fd = stream_data['azureFileDistribution'].split(',')
171 cdn_provider = stream_data['cdnProvider']
172
173 def p0(p):
add96eb9 174 return f'_{p}' if stream_data['applyAzureStructure'] == 1 else ''
9afd74d7
RA
175
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])
add96eb9 192 filename = f'{h}{p[1]}{p0(tbr)}.mp4'
9afd74d7
RA
193 f = {
194 'url': http_base + '/' + filename,
add96eb9 195 'format_id': f'{cdn}-http-{tbr}',
9afd74d7
RA
196 'tbr': tbr,
197 }
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]),
203 })
204 formats.append(f)
add96eb9 205 a = filename + f':{tbr * 1000}'
9afd74d7
RA
206 t += a + ','
207 t = t[:-1] + '&audiostream=' + a.split(':')[0]
208 else:
209 assert False
210
211 if cdn_provider == 'ce':
212 formats.extend(self._extract_mpd_formats(
213 t % (stream_data['cdnPathDASH'], 'mpd'), video_id,
add96eb9 214 mpd_id=f'{cdn}-dash', fatal=False))
06ea7bdd 215 formats.extend(self._extract_m3u8_formats(
9afd74d7 216 t % (stream_data['cdnPathHLS'], 'm3u8'), video_id, 'mp4',
add96eb9 217 entry_protocol='m3u8_native', m3u8_id=f'{cdn}-hls', fatal=False))
06ea7bdd
S
218
219 return formats
220
5f969a78
M
221 def _extract_3q_formats(self, video, video_id):
222 stream_data = video['streamdata']
223 cdn = stream_data['cdnType']
224 assert cdn == '3q'
225
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)
229
230 def get_cdn_shield_base(shield_type=''):
231 for secure in ('', 's'):
add96eb9 232 cdn_shield = stream_data.get(f'cdnShield{shield_type}HTTP{secure.upper()}')
5f969a78 233 if cdn_shield:
add96eb9 234 return f'http{secure}://{cdn_shield}'
5f969a78
M
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 '')
236
237 stream_base = get_cdn_shield_base()
238
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))
246
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',
add96eb9 257 'format_id': f'{cdn}-{ss[0]}{f"-{tbr}" if tbr else ""}',
5f969a78
M
258 'tbr': tbr,
259 })
260
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',
add96eb9 271 'format_id': f'{cdn}-http-{f"-{tbr}" if tbr else ""}',
5f969a78
M
272 'tbr': tbr,
273 'width': int_or_none(width),
274 'height': int_or_none(height),
275 }
276 formats.append(f)
277
278 return formats
279
06ea7bdd
S
280 def _extract_azure_formats(self, video, video_id):
281 stream_data = video['streamdata']
282 cdn = stream_data['cdnType']
283 assert cdn == 'azure'
284
285 azure_locator = stream_data['azureLocator']
286
287 def get_cdn_shield_base(shield_type='', static=False):
288 for secure in ('', 's'):
add96eb9 289 cdn_shield = stream_data.get(f'cdnShield{shield_type}HTTP{secure.upper()}')
06ea7bdd 290 if cdn_shield:
add96eb9 291 return f'http{secure}://{cdn_shield}'
292 if 'fb' in stream_data['azureAccount']:
293 prefix = 'df' if static else 'f'
06ea7bdd 294 else:
add96eb9 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)
06ea7bdd
S
298
299 language = video['general'].get('language_raw') or ''
300
301 azure_stream_base = get_cdn_shield_base()
302 is_ml = ',' in language
add96eb9 303 azure_manifest_url = '{}{}/{}_src{}.ism/Manifest'.format(
06ea7bdd
S
304 azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
305
306 protection_token = try_get(
add96eb9 307 video, lambda x: x['protectiondata']['token'], str)
06ea7bdd 308 if protection_token:
add96eb9 309 azure_manifest_url += f'?hdnts={protection_token}'
06ea7bdd
S
310
311 formats = self._extract_m3u8_formats(
312 azure_manifest_url % '(format=m3u8-aapl)',
313 video_id, 'mp4', 'm3u8_native',
add96eb9 314 m3u8_id=f'{cdn}-hls', fatal=False)
06ea7bdd
S
315 formats.extend(self._extract_mpd_formats(
316 azure_manifest_url % '(format=mpd-time-csf)',
add96eb9 317 video_id, mpd_id=f'{cdn}-dash', fatal=False))
06ea7bdd 318 formats.extend(self._extract_ism_formats(
add96eb9 319 azure_manifest_url % '', video_id, ism_id=f'{cdn}-mss', fatal=False))
06ea7bdd
S
320
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 = {
add96eb9 332 'url': f'{azure_progressive_base}{azure_locator}/{video_id}_src_{ss[1]}_{tbr}.mp4',
333 'format_id': f'{cdn}-http-{tbr}',
06ea7bdd
S
334 'tbr': tbr,
335 }
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]),
341 })
342 formats.append(f)
343
344 return formats
345
4e826cd9 346 def _real_extract(self, url):
5ad28e7f 347 mobj = self._match_valid_url(url)
d91dd0ce
S
348 domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
349 video_id = mobj.group('id')
350
351 video = None
4e826cd9 352
7e05df71
RA
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
362
d91dd0ce 363 response = self._download_json(
add96eb9 364 f'https://arc.nexx.cloud/api/video/{video_id}.json',
d91dd0ce
S
365 video_id, fatal=False)
366 if response and isinstance(response, dict):
367 result = response.get('result')
7e05df71
RA
368 if result:
369 video = find_video(result)
d91dd0ce
S
370
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)
add96eb9 374 device_id = f'{random.randint(1, 4)}:{int(time.time())}:{random.randint(1e4, 99999)}{random.randint(1, 9)}'
d91dd0ce
S
375
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',
392 })
393
394 cid = result['general']['cid']
395
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
0931ba94
M
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.
d91dd0ce 404 # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
0931ba94 405 secret = result['device']['domaintoken'][int(device_id[0]):]
d91dd0ce
S
406 secret = secret[0:len(secret) - int(device_id[-1])]
407
408 op = 'byid'
409
410 # Reversed from JS code for _play.api.call function (search for
411 # X-Request-Token)
412 request_token = hashlib.md5(
add96eb9 413 ''.join((op, domain_id, secret)).encode()).hexdigest()
d91dd0ce 414
7e05df71 415 result = self._call_api(
add96eb9 416 domain_id, f'videos/{op}/{video_id}', video_id, data={
0931ba94 417 'additionalfields': 'language,channel,format,licenseby,slug,fileversion,episode,season',
d91dd0ce
S
418 'addInteractionOptions': '1',
419 'addStatusDetails': '1',
420 'addStreamDetails': '1',
0931ba94
M
421 'addFeatures': '1',
422 # Caption format selection doesn't seem to be enforced?
423 'addCaptions': 'vtt',
d91dd0ce 424 'addScenes': '1',
0931ba94 425 'addChapters': '1',
d91dd0ce 426 'addHotSpots': '1',
0931ba94 427 'addConnectedMedia': 'persons',
d91dd0ce 428 'addBumpers': '1',
d91dd0ce
S
429 }, headers={
430 'X-Request-CID': cid,
431 'X-Request-Token': request_token,
432 })
7e05df71 433 video = find_video(result)
4e826cd9
S
434
435 general = video['general']
436 title = general['title']
437
06ea7bdd 438 cdn = video['streamdata']['cdnType']
4e826cd9 439
06ea7bdd
S
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)
5f969a78
M
444 elif cdn == '3q':
445 formats = self._extract_3q_formats(video, video_id)
06ea7bdd 446 else:
48e93106 447 self.raise_no_formats(f'{cdn} formats are currently not supported', video_id)
c0f647a1 448
0931ba94
M
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'])),
add96eb9 457 'name': sub.get('language_long') or sub.get('title'),
0931ba94
M
458 })
459 elif sub.get('url'):
460 subtitles.setdefault(sub.get('language', 'en'), []).append({
461 'url': sub['url'],
462 'ext': sub.get('format'),
add96eb9 463 'name': sub.get('language_long') or sub.get('title'),
0931ba94
M
464 })
465
4e826cd9
S
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')),
0931ba94 472 'creator': general.get('studio') or general.get('studio_adref') or None,
4e826cd9 473 'thumbnail': try_get(
add96eb9 474 video, lambda x: x['imagedata']['thumb'], str),
4e826cd9
S
475 'duration': parse_duration(general.get('runtime')),
476 'timestamp': int_or_none(general.get('uploaded')),
0931ba94
M
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),
4e826cd9 482 'formats': formats,
0931ba94 483 'subtitles': subtitles,
4e826cd9 484 }
3f59b015
S
485
486
487class NexxEmbedIE(InfoExtractor):
eb22d1b5 488 _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:video/)?(?P<id>[^/?#&]+)'
bfd973ec 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']
eb22d1b5 491 _TESTS = [{
3f59b015
S
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',
3f59b015
S
500 'creator': 'SPIEGEL TV',
501 'thumbnail': r're:^https?://.*\.jpg$',
502 'duration': 2761,
503 'timestamp': 1394021479,
504 'upload_date': '20140305',
505 },
506 'params': {
3f59b015
S
507 'skip_download': True,
508 },
eb22d1b5
RA
509 }, {
510 'url': 'https://embed.nexx.cloud/11888/video/DSRTO7UVOX06S7',
511 'only_matching': True,
512 }]
3f59b015 513
3f59b015
S
514 def _real_extract(self, url):
515 embed_id = self._match_id(url)
516
517 webpage = self._download_webpage(url, embed_id)
518
519 return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())