]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nexx.py
[tiktok] Extract user thumbnail
[yt-dlp.git] / yt_dlp / extractor / nexx.py
CommitLineData
4e826cd9
S
1# coding: utf-8
2from __future__ import unicode_literals
3
d91dd0ce
S
4import hashlib
5import random
4e826cd9 6import re
d91dd0ce 7import time
4e826cd9
S
8
9from .common import InfoExtractor
10from ..compat import compat_str
11from ..utils import (
d91dd0ce 12 ExtractorError,
4e826cd9
S
13 int_or_none,
14 parse_duration,
5f969a78 15 traverse_obj,
4e826cd9 16 try_get,
d91dd0ce 17 urlencode_postdata,
4e826cd9
S
18)
19
20
21class NexxIE(InfoExtractor):
694b6154
S
22 _VALID_URL = r'''(?x)
23 (?:
d91dd0ce 24 https?://api\.nexx(?:\.cloud|cdn\.com)/v3/(?P<domain_id>\d+)/videos/byid/|
b5434b5c 25 nexx:(?:(?P<domain_id_s>\d+):)?|
0704306e 26 https?://arc\.nexx\.cloud/api/video/
694b6154
S
27 )
28 (?P<id>\d+)
29 '''
4e826cd9
S
30 _TESTS = [{
31 # movie
32 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
2e697530 33 'md5': '31899fd683de49ad46f4ee67e53e83fe',
4e826cd9
S
34 'info_dict': {
35 'id': '128907',
36 'ext': 'mp4',
37 'title': 'Stiftung Warentest',
38 'alt_title': 'Wie ein Test abläuft',
39 'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
4e826cd9
S
40 'creator': 'SPIEGEL TV',
41 'thumbnail': r're:^https?://.*\.jpg$',
42 'duration': 2509,
43 'timestamp': 1384264416,
44 'upload_date': '20131112',
45 },
4e826cd9
S
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': {
4e826cd9
S
63 'skip_download': True,
64 },
2e697530 65 'skip': 'HTTP Error 404: Not Found',
d91dd0ce
S
66 }, {
67 # does not work via arc
68 'url': 'nexx:741:1269984',
69 'md5': 'c714b5b238b2958dc8d5642addba6886',
70 'info_dict': {
71 'id': '1269984',
72 'ext': 'mp4',
73 'title': '1 TAG ohne KLO... wortwörtlich! 😑',
74 'alt_title': '1 TAG ohne KLO... wortwörtlich! 😑',
d91dd0ce
S
75 'thumbnail': r're:^https?://.*\.jpg$',
76 'duration': 607,
77 'timestamp': 1518614955,
78 'upload_date': '20180214',
79 },
06ea7bdd
S
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 },
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
4e826cd9
S
116 @staticmethod
117 def _extract_urls(webpage):
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(
130 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
131 % (domain_id, video_id))
4e826cd9
S
132
133 # TODO: support more embed formats
134
135 return entries
136
3f59b015
S
137 @staticmethod
138 def _extract_url(webpage):
139 return NexxIE._extract_urls(webpage)[0]
140
d91dd0ce
S
141 def _handle_error(self, response):
142 status = int_or_none(try_get(
143 response, lambda x: x['metadata']['status']) or 200)
144 if 200 <= status < 300:
145 return
146 raise ExtractorError(
147 '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
148 expected=True)
149
150 def _call_api(self, domain_id, path, video_id, data=None, headers={}):
151 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
152 result = self._download_json(
153 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
154 'Downloading %s JSON' % path, data=urlencode_postdata(data),
155 headers=headers)
156 self._handle_error(result)
157 return result['result']
158
06ea7bdd
S
159 def _extract_free_formats(self, video, video_id):
160 stream_data = video['streamdata']
161 cdn = stream_data['cdnType']
162 assert cdn == 'free'
163
164 hash = video['general']['hash']
165
166 ps = compat_str(stream_data['originalDomain'])
167 if stream_data['applyFolderHierarchy'] == 1:
168 s = ('%04d' % int(video_id))[::-1]
169 ps += '/%s/%s' % (s[0:2], s[2:4])
170 ps += '/%s/%s_' % (video_id, hash)
171
9afd74d7
RA
172 t = 'http://%s' + ps
173 fd = stream_data['azureFileDistribution'].split(',')
174 cdn_provider = stream_data['cdnProvider']
175
176 def p0(p):
177 return '_%s' % p if stream_data['applyAzureStructure'] == 1 else ''
178
179 formats = []
180 if cdn_provider == 'ak':
181 t += ','
182 for i in fd:
183 p = i.split(':')
184 t += p[1] + p0(int(p[0])) + ','
185 t += '.mp4.csmil/master.%s'
186 elif cdn_provider == 'ce':
187 k = t.split('/')
188 h = k.pop()
189 http_base = t = '/'.join(k)
190 http_base = http_base % stream_data['cdnPathHTTP']
191 t += '/asset.ism/manifest.%s?dcp_ver=aos4&videostream='
192 for i in fd:
193 p = i.split(':')
194 tbr = int(p[0])
195 filename = '%s%s%s.mp4' % (h, p[1], p0(tbr))
196 f = {
197 'url': http_base + '/' + filename,
198 'format_id': '%s-http-%d' % (cdn, tbr),
199 'tbr': tbr,
200 }
201 width_height = p[1].split('x')
202 if len(width_height) == 2:
203 f.update({
204 'width': int_or_none(width_height[0]),
205 'height': int_or_none(width_height[1]),
206 })
207 formats.append(f)
208 a = filename + ':%s' % (tbr * 1000)
209 t += a + ','
210 t = t[:-1] + '&audiostream=' + a.split(':')[0]
211 else:
212 assert False
213
214 if cdn_provider == 'ce':
215 formats.extend(self._extract_mpd_formats(
216 t % (stream_data['cdnPathDASH'], 'mpd'), video_id,
217 mpd_id='%s-dash' % cdn, fatal=False))
06ea7bdd 218 formats.extend(self._extract_m3u8_formats(
9afd74d7 219 t % (stream_data['cdnPathHLS'], 'm3u8'), video_id, 'mp4',
06ea7bdd
S
220 entry_protocol='m3u8_native', m3u8_id='%s-hls' % cdn, fatal=False))
221
222 return formats
223
5f969a78
M
224 def _extract_3q_formats(self, video, video_id):
225 stream_data = video['streamdata']
226 cdn = stream_data['cdnType']
227 assert cdn == '3q'
228
229 q_acc, q_prefix, q_locator, q_hash = stream_data['qAccount'], stream_data['qPrefix'], stream_data['qLocator'], stream_data['qHash']
230 protection_key = traverse_obj(
231 video, ('protectiondata', 'key'), expected_type=str)
232
233 def get_cdn_shield_base(shield_type=''):
234 for secure in ('', 's'):
235 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
236 if cdn_shield:
237 return 'http%s://%s' % (secure, cdn_shield)
238 return f'http://sdn-global-{"prog" if shield_type.lower() == "prog" else "streaming"}-cache.3qsdn.com/' + (f's/{protection_key}/' if protection_key else '')
239
240 stream_base = get_cdn_shield_base()
241
242 formats = []
243 formats.extend(self._extract_m3u8_formats(
244 f'{stream_base}{q_acc}/files/{q_prefix}/{q_locator}/{q_acc}-{stream_data.get("qHEVCHash") or q_hash}.ism/manifest.m3u8',
245 video_id, 'mp4', m3u8_id=f'{cdn}-hls', fatal=False))
246 formats.extend(self._extract_mpd_formats(
247 f'{stream_base}{q_acc}/files/{q_prefix}/{q_locator}/{q_acc}-{q_hash}.ism/manifest.mpd',
248 video_id, mpd_id=f'{cdn}-dash', fatal=False))
249
250 progressive_base = get_cdn_shield_base('Prog')
251 q_references = stream_data.get('qReferences') or ''
252 fds = q_references.split(',')
253 for fd in fds:
254 ss = fd.split(':')
255 if len(ss) != 3:
256 continue
257 tbr = int_or_none(ss[1], scale=1000)
258 formats.append({
259 'url': f'{progressive_base}{q_acc}/uploads/{q_acc}-{ss[2]}.webm',
260 'format_id': f'{cdn}-{ss[0]}{"-%s" % tbr if tbr else ""}',
261 'tbr': tbr,
262 })
263
264 azure_file_distribution = stream_data.get('azureFileDistribution') or ''
265 fds = azure_file_distribution.split(',')
266 for fd in fds:
267 ss = fd.split(':')
268 if len(ss) != 3:
269 continue
270 tbr = int_or_none(ss[0])
271 width, height = ss[1].split('x') if len(ss[1].split('x')) == 2 else (None, None)
272 f = {
273 'url': f'{progressive_base}{q_acc}/files/{q_prefix}/{q_locator}/{ss[2]}.mp4',
274 'format_id': f'{cdn}-http-{"-%s" % tbr if tbr else ""}',
275 'tbr': tbr,
276 'width': int_or_none(width),
277 'height': int_or_none(height),
278 }
279 formats.append(f)
280
281 return formats
282
06ea7bdd
S
283 def _extract_azure_formats(self, video, video_id):
284 stream_data = video['streamdata']
285 cdn = stream_data['cdnType']
286 assert cdn == 'azure'
287
288 azure_locator = stream_data['azureLocator']
289
290 def get_cdn_shield_base(shield_type='', static=False):
291 for secure in ('', 's'):
292 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
293 if cdn_shield:
294 return 'http%s://%s' % (secure, cdn_shield)
295 else:
296 if 'fb' in stream_data['azureAccount']:
297 prefix = 'df' if static else 'f'
298 else:
299 prefix = 'd' if static else 'p'
300 account = int(stream_data['azureAccount'].replace('nexxplayplus', '').replace('nexxplayfb', ''))
301 return 'http://nx-%s%02d.akamaized.net/' % (prefix, account)
302
303 language = video['general'].get('language_raw') or ''
304
305 azure_stream_base = get_cdn_shield_base()
306 is_ml = ',' in language
307 azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
308 azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
309
310 protection_token = try_get(
311 video, lambda x: x['protectiondata']['token'], compat_str)
312 if protection_token:
313 azure_manifest_url += '?hdnts=%s' % protection_token
314
315 formats = self._extract_m3u8_formats(
316 azure_manifest_url % '(format=m3u8-aapl)',
317 video_id, 'mp4', 'm3u8_native',
318 m3u8_id='%s-hls' % cdn, fatal=False)
319 formats.extend(self._extract_mpd_formats(
320 azure_manifest_url % '(format=mpd-time-csf)',
321 video_id, mpd_id='%s-dash' % cdn, fatal=False))
322 formats.extend(self._extract_ism_formats(
323 azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
324
325 azure_progressive_base = get_cdn_shield_base('Prog', True)
326 azure_file_distribution = stream_data.get('azureFileDistribution')
327 if azure_file_distribution:
328 fds = azure_file_distribution.split(',')
329 if fds:
330 for fd in fds:
331 ss = fd.split(':')
332 if len(ss) == 2:
333 tbr = int_or_none(ss[0])
334 if tbr:
335 f = {
336 'url': '%s%s/%s_src_%s_%d.mp4' % (
337 azure_progressive_base, azure_locator, video_id, ss[1], tbr),
338 'format_id': '%s-http-%d' % (cdn, tbr),
339 'tbr': tbr,
340 }
341 width_height = ss[1].split('x')
342 if len(width_height) == 2:
343 f.update({
344 'width': int_or_none(width_height[0]),
345 'height': int_or_none(width_height[1]),
346 })
347 formats.append(f)
348
349 return formats
350
4e826cd9 351 def _real_extract(self, url):
5ad28e7f 352 mobj = self._match_valid_url(url)
d91dd0ce
S
353 domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
354 video_id = mobj.group('id')
355
356 video = None
4e826cd9 357
7e05df71
RA
358 def find_video(result):
359 if isinstance(result, dict):
360 return result
361 elif isinstance(result, list):
362 vid = int(video_id)
363 for v in result:
364 if try_get(v, lambda x: x['general']['ID'], int) == vid:
365 return v
366 return None
367
d91dd0ce 368 response = self._download_json(
e231afb1 369 'https://arc.nexx.cloud/api/video/%s.json' % video_id,
d91dd0ce
S
370 video_id, fatal=False)
371 if response and isinstance(response, dict):
372 result = response.get('result')
7e05df71
RA
373 if result:
374 video = find_video(result)
d91dd0ce
S
375
376 # not all videos work via arc, e.g. nexx:741:1269984
377 if not video:
378 # Reverse engineered from JS code (see getDeviceID function)
379 device_id = '%d:%d:%d%d' % (
380 random.randint(1, 4), int(time.time()),
381 random.randint(1e4, 99999), random.randint(1, 9))
382
383 result = self._call_api(domain_id, 'session/init', video_id, data={
384 'nxp_devh': device_id,
385 'nxp_userh': '',
386 'precid': '0',
387 'playlicense': '0',
388 'screenx': '1920',
389 'screeny': '1080',
390 'playerversion': '6.0.00',
391 'gateway': 'html5',
392 'adGateway': '',
393 'explicitlanguage': 'en-US',
394 'addTextTemplates': '1',
395 'addDomainData': '1',
396 'addAdModel': '1',
397 }, headers={
398 'X-Request-Enable-Auth-Fallback': '1',
399 })
400
401 cid = result['general']['cid']
402
403 # As described in [1] X-Request-Token generation algorithm is
404 # as follows:
405 # md5( operation + domain_id + domain_secret )
406 # where domain_secret is a static value that will be given by nexx.tv
407 # as per [1]. Here is how this "secret" is generated (reversed
408 # from _play.api.init function, search for clienttoken). So it's
409 # actually not static and not that much of a secret.
410 # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
411 secret = result['device']['clienttoken'][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
7e05df71 421 result = self._call_api(
d91dd0ce
S
422 domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
423 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
424 'addInteractionOptions': '1',
425 'addStatusDetails': '1',
426 'addStreamDetails': '1',
427 'addCaptions': '1',
428 'addScenes': '1',
429 'addHotSpots': '1',
430 'addBumpers': '1',
431 'captionFormat': 'data',
432 }, headers={
433 'X-Request-CID': cid,
434 'X-Request-Token': request_token,
435 })
7e05df71 436 video = find_video(result)
4e826cd9
S
437
438 general = video['general']
439 title = general['title']
440
06ea7bdd 441 cdn = video['streamdata']['cdnType']
4e826cd9 442
06ea7bdd
S
443 if cdn == 'azure':
444 formats = self._extract_azure_formats(video, video_id)
445 elif cdn == 'free':
446 formats = self._extract_free_formats(video, video_id)
5f969a78
M
447 elif cdn == '3q':
448 formats = self._extract_3q_formats(video, video_id)
06ea7bdd 449 else:
48e93106 450 self.raise_no_formats(f'{cdn} formats are currently not supported', video_id)
c0f647a1 451
4e826cd9
S
452 self._sort_formats(formats)
453
454 return {
455 'id': video_id,
456 'title': title,
457 'alt_title': general.get('subtitle'),
458 'description': general.get('description'),
459 'release_year': int_or_none(general.get('year')),
460 'creator': general.get('studio') or general.get('studio_adref'),
461 'thumbnail': try_get(
462 video, lambda x: x['imagedata']['thumb'], compat_str),
463 'duration': parse_duration(general.get('runtime')),
464 'timestamp': int_or_none(general.get('uploaded')),
465 'episode_number': int_or_none(try_get(
466 video, lambda x: x['episodedata']['episode'])),
467 'season_number': int_or_none(try_get(
468 video, lambda x: x['episodedata']['season'])),
469 'formats': formats,
470 }
3f59b015
S
471
472
473class NexxEmbedIE(InfoExtractor):
eb22d1b5
RA
474 _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:video/)?(?P<id>[^/?#&]+)'
475 _TESTS = [{
3f59b015
S
476 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
477 'md5': '16746bfc28c42049492385c989b26c4a',
478 'info_dict': {
479 'id': '161464',
480 'ext': 'mp4',
481 'title': 'Nervenkitzel Achterbahn',
482 'alt_title': 'Karussellbauer in Deutschland',
483 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
3f59b015
S
484 'creator': 'SPIEGEL TV',
485 'thumbnail': r're:^https?://.*\.jpg$',
486 'duration': 2761,
487 'timestamp': 1394021479,
488 'upload_date': '20140305',
489 },
490 'params': {
3f59b015
S
491 'skip_download': True,
492 },
eb22d1b5
RA
493 }, {
494 'url': 'https://embed.nexx.cloud/11888/video/DSRTO7UVOX06S7',
495 'only_matching': True,
496 }]
3f59b015
S
497
498 @staticmethod
499 def _extract_urls(webpage):
500 # Reference:
501 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
502
503 # iFrame Embed Integration
504 return [mobj.group('url') for mobj in re.finditer(
13eb526f 505 r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
3f59b015
S
506 webpage)]
507
508 def _real_extract(self, url):
509 embed_id = self._match_id(url)
510
511 webpage = self._download_webpage(url, embed_id)
512
513 return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())