]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/tiktok.py
[ie/orf:on] Improve extraction (#9677)
[yt-dlp.git] / yt_dlp / extractor / tiktok.py
CommitLineData
3584b839 1import functools
f7f18f90 2import itertools
b801cd71 3import json
bd9ff55b 4import random
216bcb66 5import re
bd9ff55b 6import time
cb61e20c 7import uuid
1ead840d
KS
8
9from .common import InfoExtractor
9ff94664 10from ..compat import compat_urllib_parse_urlparse
3d2623a8 11from ..networking import HEADRequest
1ead840d 12from ..utils import (
ce18a19b 13 ExtractorError,
b801cd71 14 LazyList,
11e1c2e3 15 UnsupportedError,
933ed882 16 UserNotLive,
8ceb07e8 17 determine_ext,
3584b839 18 filter_dict,
216bcb66 19 format_field,
1ead840d 20 int_or_none,
34921b43 21 join_nonempty,
216bcb66 22 merge_dicts,
4ccd73fe 23 mimetype2ext,
24 parse_qs,
b801cd71 25 qualities,
ba723997 26 remove_start,
e0585e65 27 srt_subtitles_timecode,
1ead840d 28 str_or_none,
bd9ff55b 29 traverse_obj,
216bcb66 30 try_call,
bd9ff55b 31 try_get,
943d5ab1 32 url_or_none,
1ead840d
KS
33)
34
35
0fd6661e 36class TikTokBaseIE(InfoExtractor):
943d5ab1 37 _UPLOADER_URL_FORMAT = 'https://www.tiktok.com/@%s'
53dad39e 38 _WEBPAGE_HOST = 'https://www.tiktok.com/'
be1f331f 39 QUALITIES = ('360p', '540p', '720p', '1080p')
ce18a19b 40
cb61e20c 41 _APP_INFO_DEFAULTS = {
42 # unique "install id"
43 'iid': None,
44 # TikTok (KR/PH/TW/TH/VN) = trill, TikTok (rest of world) = musical_ly, Douyin = aweme
45 'app_name': 'musical_ly',
46 'app_version': '34.1.2',
47 'manifest_app_version': '2023401020',
48 # "app id": aweme = 1128, trill = 1180, musical_ly = 1233, universal = 0
49 'aid': '0',
50 }
cb61e20c 51 _APP_INFO_POOL = None
52 _APP_INFO = None
53 _APP_USER_AGENT = None
54
3584b839 55 @functools.cached_property
41ba4a80 56 def _KNOWN_APP_INFO(self):
3584b839 57 # If we have a genuine device ID, we may not need any IID
58 default = [''] if self._KNOWN_DEVICE_ID else []
59 return self._configuration_arg('app_info', default, ie_key=TikTokIE)
41ba4a80 60
3584b839 61 @functools.cached_property
62 def _KNOWN_DEVICE_ID(self):
63 return self._configuration_arg('device_id', [None], ie_key=TikTokIE)[0]
64
65 @functools.cached_property
66 def _DEVICE_ID(self):
67 return self._KNOWN_DEVICE_ID or str(random.randint(7250000000000000000, 7351147085025500000))
68
69 @functools.cached_property
c4cbd3be 70 def _API_HOSTNAME(self):
71 return self._configuration_arg(
41ba4a80 72 'api_hostname', ['api16-normal-c-useast1a.tiktokv.com'], ie_key=TikTokIE)[0]
c4cbd3be 73
cb61e20c 74 def _get_next_app_info(self):
75 if self._APP_INFO_POOL is None:
76 defaults = {
77 key: self._configuration_arg(key, [default], ie_key=TikTokIE)[0]
78 for key, default in self._APP_INFO_DEFAULTS.items()
79 if key != 'iid'
80 }
cb61e20c 81 self._APP_INFO_POOL = [
82 {**defaults, **dict(
83 (k, v) for k, v in zip(self._APP_INFO_DEFAULTS, app_info.split('/')) if v
41ba4a80 84 )} for app_info in self._KNOWN_APP_INFO
cb61e20c 85 ]
86
87 if not self._APP_INFO_POOL:
88 return False
89
90 self._APP_INFO = self._APP_INFO_POOL.pop(0)
91
92 app_name = self._APP_INFO['app_name']
93 version = self._APP_INFO['manifest_app_version']
94 if app_name == 'musical_ly':
95 package = f'com.zhiliaoapp.musically/{version}'
96 else: # trill, aweme
97 package = f'com.ss.android.ugc.{app_name}/{version}'
98 self._APP_USER_AGENT = f'{package} (Linux; U; Android 13; en_US; Pixel 7; Build/TD1A.220804.031; Cronet/58.0.2991.0)'
99
100 return True
101
b801cd71 102 @staticmethod
103 def _create_url(user_id, video_id):
104 return f'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
105
a39a7ba8 106 def _get_sigi_state(self, webpage, display_id):
069cbece 107 return self._search_json(
108 r'<script[^>]+\bid="(?:SIGI_STATE|sigi-persisted-data)"[^>]*>', webpage,
d9b4154c 109 'sigi state', display_id, end_pattern=r'</script>', default={})
110
111 def _get_universal_data(self, webpage, display_id):
112 return traverse_obj(self._search_json(
113 r'<script[^>]+\bid="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>', webpage,
114 'universal data', display_id, end_pattern=r'</script>', default={}),
115 ('__DEFAULT_SCOPE__', {dict})) or {}
a39a7ba8 116
cb61e20c 117 def _call_api_impl(self, ep, query, video_id, fatal=True,
046cab39 118 note='Downloading API JSON', errnote='Unable to download API page'):
efa944f4 119 self._set_cookie(self._API_HOSTNAME, 'odin_tt', ''.join(random.choices('0123456789abcdef', k=160)))
046cab39
M
120 webpage_cookies = self._get_cookies(self._WEBPAGE_HOST)
121 if webpage_cookies.get('sid_tt'):
122 self._set_cookie(self._API_HOSTNAME, 'sid_tt', webpage_cookies['sid_tt'].value)
123 return self._download_json(
124 'https://%s/aweme/v1/%s/' % (self._API_HOSTNAME, ep), video_id=video_id,
125 fatal=fatal, note=note, errnote=errnote, headers={
cb61e20c 126 'User-Agent': self._APP_USER_AGENT,
046cab39
M
127 'Accept': 'application/json',
128 }, query=query)
129
cb61e20c 130 def _build_api_query(self, query):
3584b839 131 return filter_dict({
0fd6661e 132 **query,
bd9ff55b 133 'device_platform': 'android',
cb61e20c 134 'os': 'android',
135 'ssmix': 'a',
136 '_rticket': int(time.time() * 1000),
137 'cdid': str(uuid.uuid4()),
138 'channel': 'googleplay',
139 'aid': self._APP_INFO['aid'],
140 'app_name': self._APP_INFO['app_name'],
141 'version_code': ''.join((f'{int(v):02d}' for v in self._APP_INFO['app_version'].split('.'))),
142 'version_name': self._APP_INFO['app_version'],
143 'manifest_version_code': self._APP_INFO['manifest_app_version'],
144 'update_version_code': self._APP_INFO['manifest_app_version'],
145 'ab_version': self._APP_INFO['app_version'],
c2a1bdb0 146 'resolution': '1080*2400',
bd9ff55b 147 'dpi': 420,
cb61e20c 148 'device_type': 'Pixel 7',
149 'device_brand': 'Google',
150 'language': 'en',
bd9ff55b 151 'os_api': '29',
cb61e20c 152 'os_version': '13',
153 'ac': 'wifi',
154 'is_pad': '0',
155 'current_region': 'US',
156 'app_type': 'normal',
bd9ff55b 157 'sys_region': 'US',
cb61e20c 158 'last_install_time': int(time.time()) - random.randint(86400, 1123200),
bd9ff55b 159 'timezone_name': 'America/New_York',
cb61e20c 160 'residence': 'US',
161 'app_language': 'en',
bd9ff55b 162 'timezone_offset': '-14400',
cb61e20c 163 'host_abi': 'armeabi-v7a',
164 'locale': 'en',
165 'ac2': 'wifi5g',
166 'uoo': '1',
fc53ec13 167 'carrier_region': 'US',
cb61e20c 168 'op_region': 'US',
169 'build_number': self._APP_INFO['app_version'],
170 'region': 'US',
171 'ts': int(time.time()),
3584b839 172 'iid': self._APP_INFO.get('iid'),
173 'device_id': self._DEVICE_ID,
cb61e20c 174 'openudid': ''.join(random.choices('0123456789abcdef', k=16)),
3584b839 175 })
046cab39
M
176
177 def _call_api(self, ep, query, video_id, fatal=True,
178 note='Downloading API JSON', errnote='Unable to download API page'):
cb61e20c 179 if not self._APP_INFO and not self._get_next_app_info():
180 message = 'No working app info is available'
181 if fatal:
182 raise ExtractorError(message, expected=True)
183 else:
184 self.report_warning(message)
185 return
186
187 max_tries = len(self._APP_INFO_POOL) + 1 # _APP_INFO_POOL + _APP_INFO
188 for count in itertools.count(1):
189 self.write_debug(str(self._APP_INFO))
190 real_query = self._build_api_query(query)
046cab39 191 try:
cb61e20c 192 return self._call_api_impl(ep, real_query, video_id, fatal, note, errnote)
046cab39
M
193 except ExtractorError as e:
194 if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0:
cb61e20c 195 message = str(e.cause or e.msg)
196 if not self._get_next_app_info():
046cab39 197 if fatal:
cb61e20c 198 raise
046cab39 199 else:
cb61e20c 200 self.report_warning(message)
046cab39 201 return
cb61e20c 202 self.report_warning(f'{message}. Retrying... (attempt {count} of {max_tries})')
046cab39 203 continue
cb61e20c 204 raise
0fd6661e 205
ba723997 206 def _extract_aweme_app(self, aweme_id):
207 feed_list = self._call_api(
208 'feed', {'aweme_id': aweme_id}, aweme_id, note='Downloading video feed',
209 errnote='Unable to download video feed').get('aweme_list') or []
210 aweme_detail = next((aweme for aweme in feed_list if str(aweme.get('aweme_id')) == aweme_id), None)
211 if not aweme_detail:
212 raise ExtractorError('Unable to find video in feed', video_id=aweme_id)
213 return self._parse_aweme_video_app(aweme_detail)
214
eef1e9f4 215 def _extract_web_data_and_status(self, url, video_id, fatal=True):
216 webpage = self._download_webpage(url, video_id, headers={'User-Agent': 'Mozilla/5.0'}, fatal=fatal) or ''
217 video_data, status = {}, None
218
219 if universal_data := self._get_universal_data(webpage, video_id):
220 self.write_debug('Found universal data for rehydration')
221 status = traverse_obj(universal_data, ('webapp.video-detail', 'statusCode', {int})) or 0
222 video_data = traverse_obj(universal_data, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict}))
223
224 elif sigi_data := self._get_sigi_state(webpage, video_id):
225 self.write_debug('Found sigi state data')
226 status = traverse_obj(sigi_data, ('VideoPage', 'statusCode', {int})) or 0
227 video_data = traverse_obj(sigi_data, ('ItemModule', video_id, {dict}))
228
229 elif next_data := self._search_nextjs_data(webpage, video_id, default={}):
230 self.write_debug('Found next.js data')
231 status = traverse_obj(next_data, ('props', 'pageProps', 'statusCode', {int})) or 0
232 video_data = traverse_obj(next_data, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict}))
233
234 elif fatal:
235 raise ExtractorError('Unable to extract webpage video data')
236
237 return video_data, status
238
239 def _get_subtitles(self, aweme_detail, aweme_id, user_url):
e0585e65
M
240 # TODO: Extract text positioning info
241 subtitles = {}
ba723997 242 # aweme/detail endpoint subs
e0585e65 243 captions_info = traverse_obj(
ba723997 244 aweme_detail, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type=dict)
e0585e65
M
245 for caption in captions_info:
246 caption_url = traverse_obj(caption, ('url', 'url_list', ...), expected_type=url_or_none, get_all=False)
247 if not caption_url:
248 continue
249 caption_json = self._download_json(
250 caption_url, aweme_id, note='Downloading captions', errnote='Unable to download captions', fatal=False)
251 if not caption_json:
252 continue
253 subtitles.setdefault(caption.get('language', 'en'), []).append({
254 'ext': 'srt',
255 'data': '\n\n'.join(
256 f'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
257 for i, line in enumerate(caption_json['utterances']) if line.get('text'))
258 })
ba723997 259 # feed endpoint subs
260 if not subtitles:
261 for caption in traverse_obj(aweme_detail, ('video', 'cla_info', 'caption_infos', ...), expected_type=dict):
262 if not caption.get('url'):
263 continue
264 subtitles.setdefault(caption.get('lang') or 'en', []).append({
265 'ext': remove_start(caption.get('caption_format'), 'web'),
266 'url': caption['url'],
267 })
268 # webpage subs
269 if not subtitles:
eef1e9f4 270 if user_url: # only _parse_aweme_video_app needs to extract the webpage here
271 aweme_detail, _ = self._extract_web_data_and_status(
272 f'{user_url}/video/{aweme_id}', aweme_id, fatal=False)
273 for caption in traverse_obj(aweme_detail, ('video', 'subtitleInfos', lambda _, v: v['Url'])):
ba723997 274 subtitles.setdefault(caption.get('LanguageCodeName') or 'en', []).append({
275 'ext': remove_start(caption.get('Format'), 'web'),
276 'url': caption['Url'],
277 })
e0585e65
M
278 return subtitles
279
4ccd73fe 280 def _parse_url_key(self, url_key):
281 format_id, codec, res, bitrate = self._search_regex(
282 r'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key,
283 'url key', default=(None, None, None, None), group=('id', 'codec', 'res', 'bitrate'))
284 if not format_id:
285 return {}, None
286 return {
287 'format_id': format_id,
288 'vcodec': 'h265' if codec == 'bytevc1' else codec,
289 'tbr': int_or_none(bitrate, scale=1000) or None,
290 'quality': qualities(self.QUALITIES)(res),
291 }, res
292
943d5ab1 293 def _parse_aweme_video_app(self, aweme_detail):
0fd6661e 294 aweme_id = aweme_detail['aweme_id']
bd9ff55b 295 video_info = aweme_detail['video']
bd9ff55b
M
296 known_resolutions = {}
297
b09bd0c1 298 def audio_meta(url):
299 ext = determine_ext(url, default_ext='m4a')
8ceb07e8 300 return {
301 'format_note': 'Music track',
b09bd0c1 302 'ext': ext,
303 'acodec': 'aac' if ext == 'm4a' else ext,
8ceb07e8 304 'vcodec': 'none',
305 'width': None,
306 'height': None,
b09bd0c1 307 } if ext == 'mp3' or '-music-' in url else {}
8ceb07e8 308
bd9ff55b 309 def extract_addr(addr, add_meta={}):
4ccd73fe 310 parsed_meta, res = self._parse_url_key(addr.get('url_key', ''))
63f685f3 311 is_bytevc2 = parsed_meta.get('vcodec') == 'bytevc2'
bd9ff55b 312 if res:
9ff94664 313 known_resolutions.setdefault(res, {}).setdefault('height', int_or_none(addr.get('height')))
314 known_resolutions[res].setdefault('width', int_or_none(addr.get('width')))
bd9ff55b
M
315 parsed_meta.update(known_resolutions.get(res, {}))
316 add_meta.setdefault('height', int_or_none(res[:-1]))
317 return [{
318 'url': url,
319 'filesize': int_or_none(addr.get('data_size')),
320 'ext': 'mp4',
321 'acodec': 'aac',
0fd6661e
M
322 'source_preference': -2 if 'aweme/v1' in url else -1, # Downloads from API might get blocked
323 **add_meta, **parsed_meta,
4ccd73fe 324 # bytevc2 is bytedance's own custom h266/vvc codec, as-of-yet unplayable
63f685f3 325 'preference': -100 if is_bytevc2 else -1,
34921b43 326 'format_note': join_nonempty(
63f685f3 327 add_meta.get('format_note'), '(API)' if 'aweme/v1' in url else None,
328 '(UNPLAYABLE)' if is_bytevc2 else None, delim=' '),
b09bd0c1 329 **audio_meta(url),
bd9ff55b
M
330 } for url in addr.get('url_list') or []]
331
332 # Hack: Add direct video links first to prioritize them when removing duplicate formats
333 formats = []
9ff94664 334 width = int_or_none(video_info.get('width'))
335 height = int_or_none(video_info.get('height'))
4ccd73fe 336 ratio = try_call(lambda: width / height) or 0.5625
bd9ff55b
M
337 if video_info.get('play_addr'):
338 formats.extend(extract_addr(video_info['play_addr'], {
339 'format_id': 'play_addr',
340 'format_note': 'Direct video',
341 'vcodec': 'h265' if traverse_obj(
be1f331f 342 video_info, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
9ff94664 343 'width': width,
344 'height': height,
bd9ff55b
M
345 }))
346 if video_info.get('download_addr'):
9ff94664 347 download_addr = video_info['download_addr']
348 dl_width = int_or_none(download_addr.get('width'))
349 formats.extend(extract_addr(download_addr, {
bd9ff55b
M
350 'format_id': 'download_addr',
351 'format_note': 'Download video%s' % (', watermarked' if video_info.get('has_watermark') else ''),
352 'vcodec': 'h264',
4ccd73fe 353 'width': dl_width,
354 'height': try_call(lambda: int(dl_width / ratio)), # download_addr['height'] is wrong
0fd6661e 355 'preference': -2 if video_info.get('has_watermark') else -1,
bd9ff55b
M
356 }))
357 if video_info.get('play_addr_h264'):
358 formats.extend(extract_addr(video_info['play_addr_h264'], {
359 'format_id': 'play_addr_h264',
360 'format_note': 'Direct video',
361 'vcodec': 'h264',
362 }))
363 if video_info.get('play_addr_bytevc1'):
364 formats.extend(extract_addr(video_info['play_addr_bytevc1'], {
365 'format_id': 'play_addr_bytevc1',
366 'format_note': 'Direct video',
367 'vcodec': 'h265',
368 }))
369
370 for bitrate in video_info.get('bit_rate', []):
371 if bitrate.get('play_addr'):
372 formats.extend(extract_addr(bitrate['play_addr'], {
373 'format_id': bitrate.get('gear_name'),
374 'format_note': 'Playback video',
375 'tbr': try_get(bitrate, lambda x: x['bit_rate'] / 1000),
376 'vcodec': 'h265' if traverse_obj(
377 bitrate, 'is_bytevc1', 'is_h265') else 'h264',
943d5ab1 378 'fps': bitrate.get('FPS'),
bd9ff55b
M
379 }))
380
381 self._remove_duplicate_formats(formats)
6134fbeb
M
382 auth_cookie = self._get_cookies(self._WEBPAGE_HOST).get('sid_tt')
383 if auth_cookie:
384 for f in formats:
be1f331f 385 self._set_cookie(compat_urllib_parse_urlparse(f['url']).hostname, 'sid_tt', auth_cookie.value)
bd9ff55b
M
386
387 thumbnails = []
388 for cover_id in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
389 'origin_cover', 'dynamic_cover'):
92593690 390 for cover_url in traverse_obj(video_info, (cover_id, 'url_list', ...)):
391 thumbnails.append({
392 'id': cover_id,
393 'url': cover_url,
394 })
395
396 stats_info = aweme_detail.get('statistics') or {}
397 author_info = aweme_detail.get('author') or {}
398 music_info = aweme_detail.get('music') or {}
943d5ab1
M
399 user_url = self._UPLOADER_URL_FORMAT % (traverse_obj(author_info,
400 'sec_uid', 'id', 'uid', 'unique_id',
401 expected_type=str_or_none, get_all=False))
6839ae1f 402 labels = traverse_obj(aweme_detail, ('hybrid_label', ..., 'text'), expected_type=str)
bd9ff55b
M
403
404 contained_music_track = traverse_obj(
405 music_info, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type=str)
406 contained_music_author = traverse_obj(
407 music_info, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type=str)
408
409 is_generic_og_trackname = music_info.get('is_original_sound') and music_info.get('title') == 'original sound - %s' % music_info.get('owner_handle')
410 if is_generic_og_trackname:
411 music_track, music_author = contained_music_track or 'original sound', contained_music_author
412 else:
f4f9f6d0 413 music_track, music_author = music_info.get('title'), traverse_obj(music_info, ('author', {str}))
bd9ff55b
M
414
415 return {
416 'id': aweme_id,
92593690 417 **traverse_obj(aweme_detail, {
418 'title': ('desc', {str}),
419 'description': ('desc', {str}),
420 'timestamp': ('create_time', {int_or_none}),
421 }),
422 **traverse_obj(stats_info, {
423 'view_count': 'play_count',
424 'like_count': 'digg_count',
425 'repost_count': 'share_count',
426 'comment_count': 'comment_count',
427 }, expected_type=int_or_none),
428 **traverse_obj(author_info, {
f4f9f6d0 429 'uploader': ('unique_id', {str}),
430 'uploader_id': ('uid', {str_or_none}),
431 'creators': ('nickname', {str}, {lambda x: [x] if x else None}), # for compat
432 'channel': ('nickname', {str}),
433 'channel_id': ('sec_uid', {str}),
434 }),
943d5ab1 435 'uploader_url': user_url,
bd9ff55b
M
436 'track': music_track,
437 'album': str_or_none(music_info.get('album')) or None,
f4f9f6d0 438 'artists': re.split(r'(?:, | & )', music_author) if music_author else None,
bd9ff55b 439 'formats': formats,
eef1e9f4 440 'subtitles': self.extract_subtitles(aweme_detail, aweme_id, user_url),
bd9ff55b 441 'thumbnails': thumbnails,
53dad39e
M
442 'duration': int_or_none(traverse_obj(video_info, 'duration', ('download_addr', 'duration')), scale=1000),
443 'availability': self._availability(
444 is_private='Private' in labels,
445 needs_subscription='Friends only' in labels,
9f14daf2 446 is_unlisted='Followers only' in labels),
447 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
bd9ff55b
M
448 }
449
92593690 450 def _parse_aweme_video_web(self, aweme_detail, webpage_url, video_id):
943d5ab1 451 video_info = aweme_detail['video']
11aa91a1 452 author_info = traverse_obj(aweme_detail, 'authorInfo', 'author', expected_type=dict, default={})
943d5ab1
M
453 music_info = aweme_detail.get('music') or {}
454 stats_info = aweme_detail.get('stats') or {}
92593690 455 channel_id = traverse_obj(author_info or aweme_detail, (('authorSecId', 'secUid'), {str}), get_all=False)
456 user_url = self._UPLOADER_URL_FORMAT % channel_id if channel_id else None
943d5ab1
M
457
458 formats = []
92593690 459 width = int_or_none(video_info.get('width'))
460 height = int_or_none(video_info.get('height'))
4ccd73fe 461 ratio = try_call(lambda: width / height) or 0.5625
462 COMMON_FORMAT_INFO = {
463 'ext': 'mp4',
464 'vcodec': 'h264',
465 'acodec': 'aac',
466 }
467
468 for bitrate_info in traverse_obj(video_info, ('bitrateInfo', lambda _, v: v['PlayAddr']['UrlList'])):
469 format_info, res = self._parse_url_key(
470 traverse_obj(bitrate_info, ('PlayAddr', 'UrlKey', {str})) or '')
471 # bytevc2 is bytedance's own custom h266/vvc codec, as-of-yet unplayable
472 is_bytevc2 = format_info.get('vcodec') == 'bytevc2'
473 format_info.update({
474 'format_note': 'UNPLAYABLE' if is_bytevc2 else None,
475 'preference': -100 if is_bytevc2 else -1,
476 'filesize': traverse_obj(bitrate_info, ('PlayAddr', 'DataSize', {int_or_none})),
477 })
478
479 if dimension := (res and int(res[:-1])):
480 if dimension == 540: # '540p' is actually 576p
481 dimension = 576
482 if ratio < 1: # portrait: res/dimension is width
483 y = int(dimension / ratio)
484 format_info.update({
485 'width': dimension,
486 'height': y - (y % 2),
487 })
488 else: # landscape: res/dimension is height
489 x = int(dimension * ratio)
490 format_info.update({
491 'width': x - (x % 2),
492 'height': dimension,
493 })
494
495 for video_url in traverse_obj(bitrate_info, ('PlayAddr', 'UrlList', ..., {url_or_none})):
496 formats.append({
497 **COMMON_FORMAT_INFO,
498 **format_info,
499 'url': self._proto_relative_url(video_url),
500 })
501
502 # We don't have res string for play formats, but need quality for sorting & de-duplication
503 play_quality = traverse_obj(formats, (lambda _, v: v['width'] == width, 'quality', any))
92593690 504
505 for play_url in traverse_obj(video_info, ('playAddr', ((..., 'src'), None), {url_or_none})):
506 formats.append({
4ccd73fe 507 **COMMON_FORMAT_INFO,
508 'format_id': 'play',
943d5ab1 509 'url': self._proto_relative_url(play_url),
943d5ab1
M
510 'width': width,
511 'height': height,
4ccd73fe 512 'quality': play_quality,
92593690 513 })
943d5ab1 514
92593690 515 for download_url in traverse_obj(video_info, (('downloadAddr', ('download', 'url')), {url_or_none})):
943d5ab1 516 formats.append({
4ccd73fe 517 **COMMON_FORMAT_INFO,
943d5ab1
M
518 'format_id': 'download',
519 'url': self._proto_relative_url(download_url),
943d5ab1 520 })
92593690 521
943d5ab1 522 self._remove_duplicate_formats(formats)
943d5ab1 523
4ccd73fe 524 for f in traverse_obj(formats, lambda _, v: 'unwatermarked' not in v['url']):
525 f.update({
526 'format_note': join_nonempty(f.get('format_note'), 'watermarked', delim=', '),
527 'preference': f.get('preference') or -2,
528 })
529
530 # Is it a slideshow with only audio for download?
531 if not formats and traverse_obj(music_info, ('playUrl', {url_or_none})):
532 audio_url = music_info['playUrl']
533 ext = traverse_obj(parse_qs(audio_url), (
534 'mime_type', -1, {lambda x: x.replace('_', '/')}, {mimetype2ext})) or 'm4a'
535 formats.append({
536 'format_id': 'audio',
537 'url': self._proto_relative_url(audio_url),
538 'ext': ext,
539 'acodec': 'aac' if ext == 'm4a' else ext,
540 'vcodec': 'none',
541 })
542
943d5ab1 543 thumbnails = []
92593690 544 for thumb_url in traverse_obj(aweme_detail, (
545 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none})):
546 thumbnails.append({
547 'url': self._proto_relative_url(thumb_url),
548 'width': width,
549 'height': height,
550 })
943d5ab1
M
551
552 return {
92593690 553 'id': video_id,
4ccd73fe 554 **traverse_obj(music_info, {
555 'track': ('title', {str}),
556 'album': ('album', {str}, {lambda x: x or None}),
557 'artists': ('authorName', {str}, {lambda x: [x] if x else None}),
558 'duration': ('duration', {int_or_none}),
559 }),
92593690 560 **traverse_obj(aweme_detail, {
561 'title': ('desc', {str}),
562 'description': ('desc', {str}),
4ccd73fe 563 # audio-only slideshows have a video duration of 0 and an actual audio duration
564 'duration': ('video', 'duration', {int_or_none}, {lambda x: x or None}),
92593690 565 'timestamp': ('createTime', {int_or_none}),
566 }),
567 **traverse_obj(author_info or aweme_detail, {
f4f9f6d0 568 'creators': ('nickname', {str}, {lambda x: [x] if x else None}), # for compat
569 'channel': ('nickname', {str}),
92593690 570 'uploader': (('uniqueId', 'author'), {str}),
571 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}),
572 }, get_all=False),
573 **traverse_obj(stats_info, {
574 'view_count': 'playCount',
575 'like_count': 'diggCount',
576 'repost_count': 'shareCount',
577 'comment_count': 'commentCount',
578 }, expected_type=int_or_none),
92593690 579 'channel_id': channel_id,
943d5ab1 580 'uploader_url': user_url,
943d5ab1 581 'formats': formats,
eef1e9f4 582 'subtitles': self.extract_subtitles(aweme_detail, video_id, None),
943d5ab1 583 'thumbnails': thumbnails,
943d5ab1 584 'http_headers': {
92593690 585 'Referer': webpage_url,
943d5ab1
M
586 }
587 }
588
0fd6661e
M
589
590class TikTokIE(TikTokBaseIE):
c4cbd3be 591 _VALID_URL = r'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
bfd973ec 592 _EMBED_REGEX = [rf'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
0fd6661e
M
593
594 _TESTS = [{
595 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
0481e266 596 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
0fd6661e
M
597 'info_dict': {
598 'id': '6748451240264420610',
599 'ext': 'mp4',
600 'title': '#jassmanak #lehanga #leenabhushan',
601 'description': '#jassmanak #lehanga #leenabhushan',
602 'duration': 13,
0481e266 603 'height': 1024,
604 'width': 576,
0fd6661e
M
605 'uploader': 'leenabhushan',
606 'uploader_id': '6691488002098119685',
0481e266 607 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
0fd6661e
M
608 'creator': 'facestoriesbyleenabh',
609 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
610 'upload_date': '20191016',
611 'timestamp': 1571246252,
612 'view_count': int,
613 'like_count': int,
614 'repost_count': int,
615 'comment_count': int,
a44ca5a4 616 'artist': 'Ysrbeats',
617 'album': 'Lehanga',
618 'track': 'Lehanga',
92593690 619 },
620 'skip': '404 Not Found',
0fd6661e
M
621 }, {
622 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
0481e266 623 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
0fd6661e
M
624 'info_dict': {
625 'id': '6742501081818877190',
626 'ext': 'mp4',
627 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
628 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
629 'duration': 27,
630 'height': 960,
631 'width': 540,
632 'uploader': 'patrox',
633 'uploader_id': '18702747',
0481e266 634 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
92593690 635 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
f4f9f6d0 636 'channel': 'patroX',
637 'creators': ['patroX'],
0fd6661e
M
638 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
639 'upload_date': '20190930',
640 'timestamp': 1569860870,
641 'view_count': int,
642 'like_count': int,
643 'repost_count': int,
644 'comment_count': int,
f4f9f6d0 645 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'],
a44ca5a4 646 'track': 'Big Fun',
92593690 647 },
0fd6661e 648 }, {
96f13f01
M
649 # Banned audio, only available on the app
650 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
651 'info_dict': {
652 'id': '6984138651336838402',
653 'ext': 'mp4',
654 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
655 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
656 'uploader': 'barudakhb_',
f4f9f6d0 657 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
658 'creators': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
96f13f01
M
659 'uploader_id': '6974687867511718913',
660 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
92593690 661 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
96f13f01 662 'track': 'Boka Dance',
f4f9f6d0 663 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
96f13f01
M
664 'timestamp': 1626121503,
665 'duration': 18,
666 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
667 'upload_date': '20210712',
668 'view_count': int,
669 'like_count': int,
670 'repost_count': int,
671 'comment_count': int,
92593690 672 },
96f13f01
M
673 }, {
674 # Sponsored video, only available with feed workaround
675 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
676 'info_dict': {
677 'id': '7042692929109986561',
678 'ext': 'mp4',
679 'title': 'Slap and Run!',
680 'description': 'Slap and Run!',
681 'uploader': 'user440922249',
f4f9f6d0 682 'channel': 'Slap And Run',
683 'creators': ['Slap And Run'],
96f13f01
M
684 'uploader_id': '7036055384943690754',
685 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
92593690 686 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
96f13f01
M
687 'track': 'Promoted Music',
688 'timestamp': 1639754738,
689 'duration': 30,
690 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
691 'upload_date': '20211217',
692 'view_count': int,
693 'like_count': int,
694 'repost_count': int,
695 'comment_count': int,
696 },
b09bd0c1 697 'params': {'skip_download': True}, # XXX: unable to download video data: HTTP Error 403: Forbidden
5fa3c9a8
HTL
698 }, {
699 # Video without title and description
700 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
701 'info_dict': {
702 'id': '7059698374567611694',
703 'ext': 'mp4',
b801cd71 704 'title': 'TikTok video #7059698374567611694',
5fa3c9a8
HTL
705 'description': '',
706 'uploader': 'pokemonlife22',
f4f9f6d0 707 'channel': 'Pokemon',
708 'creators': ['Pokemon'],
5fa3c9a8
HTL
709 'uploader_id': '6820838815978423302',
710 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
92593690 711 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
5fa3c9a8
HTL
712 'track': 'original sound',
713 'timestamp': 1643714123,
714 'duration': 6,
715 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
716 'upload_date': '20220201',
f4f9f6d0 717 'artists': ['Pokemon'],
5fa3c9a8
HTL
718 'view_count': int,
719 'like_count': int,
720 'repost_count': int,
721 'comment_count': int,
722 },
a39a7ba8 723 }, {
724 # hydration JSON is sent in a <script> element
725 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
726 'info_dict': {
727 'id': '7065799023130643713',
728 'ext': 'mp4',
729 'title': '#denidil#денидил',
730 'description': '#denidil#денидил',
731 'uploader': 'denidil6',
732 'uploader_id': '7046664115636405250',
733 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
734 'artist': 'Holocron Music',
735 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
736 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
737 'timestamp': 1645134536,
738 'duration': 26,
739 'upload_date': '20220217',
740 'view_count': int,
741 'like_count': int,
742 'repost_count': int,
743 'comment_count': int,
744 },
f7c5a5e9 745 'skip': 'This video is unavailable',
8ceb07e8 746 }, {
747 # slideshow audio-only mp3 format
748 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
749 'info_dict': {
750 'id': '7139980461132074283',
751 'ext': 'mp3',
752 'title': 'TikTok video #7139980461132074283',
753 'description': '',
f4f9f6d0 754 'channel': 'Antaura',
755 'creators': ['Antaura'],
8ceb07e8 756 'uploader': '_le_cannibale_',
757 'uploader_id': '6604511138619654149',
758 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
92593690 759 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
f4f9f6d0 760 'artists': ['nathan !'],
8ceb07e8 761 'track': 'grahamscott canon',
762 'upload_date': '20220905',
763 'timestamp': 1662406249,
764 'view_count': int,
765 'like_count': int,
766 'repost_count': int,
767 'comment_count': int,
f4f9f6d0 768 'thumbnail': r're:^https://.+\.(?:webp|jpe?g)',
8ceb07e8 769 },
92593690 770 }, {
771 # only available via web
f4f9f6d0 772 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662', # FIXME
b09bd0c1 773 'md5': '6aba7fad816e8709ff2c149679ace165',
92593690 774 'info_dict': {
775 'id': '7206382937372134662',
776 'ext': 'mp4',
777 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
778 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
f4f9f6d0 779 'channel': 'MoxyPatch',
d9b4154c 780 'creators': ['MoxyPatch'],
92593690 781 'uploader': 'moxypatch',
782 'uploader_id': '7039142049363379205',
783 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
784 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
d9b4154c 785 'artists': ['your worst nightmare'],
92593690 786 'track': 'original sound',
787 'upload_date': '20230303',
788 'timestamp': 1677866781,
789 'duration': 10,
790 'view_count': int,
791 'like_count': int,
792 'repost_count': int,
793 'comment_count': int,
794 'thumbnail': r're:^https://.+',
795 'thumbnails': 'count:3',
796 },
797 'expected_warnings': ['Unable to find video in feed'],
c2a1bdb0 798 }, {
799 # 1080p format
f4f9f6d0 800 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME
c2a1bdb0 801 'md5': '982512017a8a917124d5a08c8ae79621',
802 'info_dict': {
803 'id': '7107337212743830830',
804 'ext': 'mp4',
805 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
806 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
807 'uploader': 'tatemcrae',
808 'uploader_id': '86328792343818240',
809 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
810 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
f4f9f6d0 811 'channel': 'tate mcrae',
812 'creators': ['tate mcrae'],
813 'artists': ['tate mcrae'],
c2a1bdb0 814 'track': 'original sound',
815 'upload_date': '20220609',
816 'timestamp': 1654805899,
817 'duration': 150,
818 'view_count': int,
819 'like_count': int,
820 'repost_count': int,
821 'comment_count': int,
822 'thumbnail': r're:^https://.+\.webp',
823 },
d9b4154c 824 'skip': 'Unavailable via feed API, no formats available via web',
b09bd0c1 825 }, {
826 # Slideshow, audio-only m4a format
827 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
828 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
829 'info_dict': {
830 'id': '7253412088251534594',
831 'ext': 'm4a',
832 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
833 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
834 'uploader': 'hara_yoimiya',
835 'uploader_id': '6582536342634676230',
836 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
837 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
f4f9f6d0 838 'channel': 'лампочка',
839 'creators': ['лампочка'],
840 'artists': ['Øneheart'],
b09bd0c1 841 'album': 'watching the stars',
842 'track': 'watching the stars',
843 'upload_date': '20230708',
844 'timestamp': 1688816612,
845 'view_count': int,
846 'like_count': int,
847 'comment_count': int,
848 'repost_count': int,
f4f9f6d0 849 'thumbnail': r're:^https://.+\.(?:webp|jpe?g)',
b09bd0c1 850 },
e0585e65
M
851 }, {
852 # Auto-captions available
853 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
854 'only_matching': True
0fd6661e
M
855 }]
856
ce18a19b 857 def _real_extract(self, url):
b801cd71 858 video_id, user_id = self._match_valid_url(url).group('id', 'user_id')
41ba4a80 859
860 if self._KNOWN_APP_INFO:
861 try:
862 return self._extract_aweme_app(video_id)
863 except ExtractorError as e:
864 e.expected = True
865 self.report_warning(f'{e}; trying with webpage')
bd9ff55b 866
a39a7ba8 867 url = self._create_url(user_id, video_id)
eef1e9f4 868 video_data, status = self._extract_web_data_and_status(url, video_id)
11aa91a1 869
d9b4154c 870 if video_data and status == 0:
92593690 871 return self._parse_aweme_video_web(video_data, url, video_id)
1418a043 872 elif status == 10216:
873 raise ExtractorError('This video is private', expected=True)
d9b4154c 874 raise ExtractorError(f'Video not available, status code {status}', video_id=video_id)
f7f18f90
A
875
876
0fd6661e 877class TikTokUserIE(TikTokBaseIE):
f7f18f90 878 IE_NAME = 'tiktok:user'
0fd6661e 879 _VALID_URL = r'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
f7c5a5e9 880 _WORKING = False
f7f18f90 881 _TESTS = [{
526d74ec 882 'url': 'https://tiktok.com/@corgibobaa?lang=en',
f7f18f90
A
883 'playlist_mincount': 45,
884 'info_dict': {
885 'id': '6935371178089399301',
0481e266 886 'title': 'corgibobaa',
b3187433 887 'thumbnail': r're:https://.+_1080x1080\.webp'
f7f18f90 888 },
0481e266 889 'expected_warnings': ['Retrying']
5fa3c9a8
HTL
890 }, {
891 'url': 'https://www.tiktok.com/@6820838815978423302',
892 'playlist_mincount': 5,
893 'info_dict': {
894 'id': '6820838815978423302',
895 'title': '6820838815978423302',
896 'thumbnail': r're:https://.+_1080x1080\.webp'
897 },
898 'expected_warnings': ['Retrying']
f7f18f90
A
899 }, {
900 'url': 'https://www.tiktok.com/@meme',
901 'playlist_mincount': 593,
902 'info_dict': {
903 'id': '79005827461758976',
0481e266 904 'title': 'meme',
b3187433 905 'thumbnail': r're:https://.+_1080x1080\.webp'
f7f18f90 906 },
0481e266 907 'expected_warnings': ['Retrying']
f7f18f90
A
908 }]
909
0fd6661e
M
910 r''' # TODO: Fix by adding _signature to api_url
911 def _entries(self, webpage, user_id, username):
912 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
f7f18f90
A
913 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
914 if not verifyfp_cookie:
915 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
916 api_url = f'https://m.tiktok.com/api/post/item_list/?aid=1988&cookie_enabled=true&count=30&verifyFp={verifyfp_cookie.value}&secUid={secuid}&cursor='
917 cursor = '0'
918 for page in itertools.count():
0fd6661e 919 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
f7f18f90
A
920 for video in data_json.get('itemList', []):
921 video_id = video['id']
922 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
bd9ff55b 923 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
526d74ec 924 if not data_json.get('hasMore'):
f7f18f90
A
925 break
926 cursor = data_json['cursor']
0fd6661e
M
927 '''
928
b3187433 929 def _video_entries_api(self, webpage, user_id, username):
0fd6661e
M
930 query = {
931 'user_id': user_id,
932 'count': 21,
933 'max_cursor': 0,
934 'min_cursor': 0,
935 'retry_type': 'no_retry',
3584b839 936 'device_id': self._DEVICE_ID, # Some endpoints don't like randomized device_id, so it isn't directly set in _call_api.
0fd6661e
M
937 }
938
0fd6661e 939 for page in itertools.count(1):
be5c1ae8 940 for retry in self.RetryManager():
0fd6661e 941 try:
be5c1ae8 942 post_list = self._call_api(
943 'aweme/post', query, username, note=f'Downloading user video list page {page}',
944 errnote='Unable to download user video list')
0fd6661e 945 except ExtractorError as e:
be5c1ae8 946 if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0:
947 retry.error = e
0fd6661e
M
948 continue
949 raise
b3187433 950 yield from post_list.get('aweme_list', [])
0fd6661e
M
951 if not post_list.get('has_more'):
952 break
953 query['max_cursor'] = post_list['max_cursor']
f7f18f90 954
b3187433 955 def _entries_api(self, user_id, videos):
956 for video in videos:
957 yield {
958 **self._parse_aweme_video_app(video),
959 'extractor_key': TikTokIE.ie_key(),
960 'extractor': 'TikTok',
961 'webpage_url': f'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
962 }
963
f7f18f90 964 def _real_extract(self, url):
0481e266 965 user_name = self._match_id(url)
966 webpage = self._download_webpage(url, user_name, headers={
0fd6661e
M
967 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
968 })
5fa3c9a8 969 user_id = self._html_search_regex(r'snssdk\d*://user/profile/(\d+)', webpage, 'user ID', default=None) or user_name
b3187433 970
971 videos = LazyList(self._video_entries_api(webpage, user_id, user_name))
972 thumbnail = traverse_obj(videos, (0, 'author', 'avatar_larger', 'url_list', 0))
973
974 return self.playlist_result(self._entries_api(user_id, videos), user_id, user_name, thumbnail=thumbnail)
943d5ab1
M
975
976
6368e2e6 977class TikTokBaseListIE(TikTokBaseIE): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
8126298c
M
978 def _entries(self, list_id, display_id):
979 query = {
980 self._QUERY_NAME: list_id,
981 'cursor': 0,
982 'count': 20,
983 'type': 5,
3584b839 984 'device_id': self._DEVICE_ID,
8126298c
M
985 }
986
8126298c 987 for page in itertools.count(1):
be5c1ae8 988 for retry in self.RetryManager():
8126298c 989 try:
be5c1ae8 990 post_list = self._call_api(
991 self._API_ENDPOINT, query, display_id, note=f'Downloading video list page {page}',
992 errnote='Unable to download video list')
8126298c 993 except ExtractorError as e:
be5c1ae8 994 if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0:
995 retry.error = e
8126298c
M
996 continue
997 raise
8126298c
M
998 for video in post_list.get('aweme_list', []):
999 yield {
1000 **self._parse_aweme_video_app(video),
0b77924a 1001 'extractor_key': TikTokIE.ie_key(),
8126298c
M
1002 'extractor': 'TikTok',
1003 'webpage_url': f'https://tiktok.com/@_/video/{video["aweme_id"]}',
1004 }
1005 if not post_list.get('has_more'):
1006 break
1007 query['cursor'] = post_list['cursor']
1008
1009 def _real_extract(self, url):
1010 list_id = self._match_id(url)
1011 return self.playlist_result(self._entries(list_id, list_id), list_id)
1012
1013
1014class TikTokSoundIE(TikTokBaseListIE):
1015 IE_NAME = 'tiktok:sound'
1016 _VALID_URL = r'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
f7c5a5e9 1017 _WORKING = False
8126298c
M
1018 _QUERY_NAME = 'music_id'
1019 _API_ENDPOINT = 'music/aweme'
1020 _TESTS = [{
1021 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
1022 'playlist_mincount': 100,
1023 'info_dict': {
1024 'id': '6956990112127585029'
1025 },
1026 'expected_warnings': ['Retrying']
1027 }, {
1028 # Actual entries are less than listed video count
1029 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
1030 'playlist_mincount': 2182,
1031 'info_dict': {
1032 'id': '7036843036118469381'
1033 },
1034 'expected_warnings': ['Retrying']
1035 }]
1036
1037
1038class TikTokEffectIE(TikTokBaseListIE):
1039 IE_NAME = 'tiktok:effect'
1040 _VALID_URL = r'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
f7c5a5e9 1041 _WORKING = False
8126298c
M
1042 _QUERY_NAME = 'sticker_id'
1043 _API_ENDPOINT = 'sticker/aweme'
1044 _TESTS = [{
1045 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
1046 'playlist_mincount': 100,
1047 'info_dict': {
1048 'id': '1258156',
1049 },
1050 'expected_warnings': ['Retrying']
1051 }, {
1052 # Different entries between mobile and web, depending on region
1053 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
1054 'only_matching': True
1055 }]
1056
1057
1058class TikTokTagIE(TikTokBaseListIE):
1059 IE_NAME = 'tiktok:tag'
1060 _VALID_URL = r'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
f7c5a5e9 1061 _WORKING = False
8126298c
M
1062 _QUERY_NAME = 'ch_id'
1063 _API_ENDPOINT = 'challenge/aweme'
1064 _TESTS = [{
1065 'url': 'https://tiktok.com/tag/hello2018',
1066 'playlist_mincount': 39,
1067 'info_dict': {
1068 'id': '46294678',
1069 'title': 'hello2018',
1070 },
1071 'expected_warnings': ['Retrying']
1072 }, {
1073 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
1074 'only_matching': True
1075 }]
1076
1077 def _real_extract(self, url):
1078 display_id = self._match_id(url)
1079 webpage = self._download_webpage(url, display_id, headers={
1080 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
1081 })
1082 tag_id = self._html_search_regex(r'snssdk\d*://challenge/detail/(\d+)', webpage, 'tag ID')
1083 return self.playlist_result(self._entries(tag_id, display_id), tag_id, display_id)
1084
1085
ba723997 1086class DouyinIE(TikTokBaseIE):
943d5ab1
M
1087 _VALID_URL = r'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
1088 _TESTS = [{
1089 'url': 'https://www.douyin.com/video/6961737553342991651',
9ff94664 1090 'md5': '9ecce7bc5b302601018ecb2871c63a75',
943d5ab1
M
1091 'info_dict': {
1092 'id': '6961737553342991651',
1093 'ext': 'mp4',
1094 'title': '#杨超越 小小水手带你去远航❤️',
ba723997 1095 'description': '#杨超越 小小水手带你去远航❤️',
9ff94664 1096 'uploader': '6897520xka',
943d5ab1 1097 'uploader_id': '110403406559',
ba723997 1098 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
92593690 1099 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
f4f9f6d0 1100 'channel': '杨超越',
9ff94664 1101 'creators': ['杨超越'],
1102 'duration': 19,
ba723997 1103 'timestamp': 1620905839,
1104 'upload_date': '20210513',
1105 'track': '@杨超越创作的原声',
9ff94664 1106 'artists': ['杨超越'],
943d5ab1
M
1107 'view_count': int,
1108 'like_count': int,
1109 'repost_count': int,
1110 'comment_count': int,
92593690 1111 'thumbnail': r're:https?://.+\.jpe?g',
ba723997 1112 },
943d5ab1
M
1113 }, {
1114 'url': 'https://www.douyin.com/video/6982497745948921092',
9ff94664 1115 'md5': '15c5e660b7048af3707304e3cc02bbb5',
943d5ab1
M
1116 'info_dict': {
1117 'id': '6982497745948921092',
1118 'ext': 'mp4',
1119 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
ba723997 1120 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
9ff94664 1121 'uploader': '0731chaoyue',
943d5ab1 1122 'uploader_id': '408654318141572',
ba723997 1123 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
92593690 1124 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
f4f9f6d0 1125 'channel': '杨超越工作室',
9ff94664 1126 'creators': ['杨超越工作室'],
1127 'duration': 42,
ba723997 1128 'timestamp': 1625739481,
1129 'upload_date': '20210708',
1130 'track': '@杨超越工作室创作的原声',
9ff94664 1131 'artists': ['杨超越工作室'],
943d5ab1
M
1132 'view_count': int,
1133 'like_count': int,
1134 'repost_count': int,
1135 'comment_count': int,
92593690 1136 'thumbnail': r're:https?://.+\.jpe?g',
ba723997 1137 },
943d5ab1
M
1138 }, {
1139 'url': 'https://www.douyin.com/video/6953975910773099811',
9ff94664 1140 'md5': '0e6443758b8355db9a3c34864a4276be',
943d5ab1
M
1141 'info_dict': {
1142 'id': '6953975910773099811',
1143 'ext': 'mp4',
1144 'title': '#一起看海 出现在你的夏日里',
ba723997 1145 'description': '#一起看海 出现在你的夏日里',
9ff94664 1146 'uploader': '6897520xka',
943d5ab1 1147 'uploader_id': '110403406559',
ba723997 1148 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
92593690 1149 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
f4f9f6d0 1150 'channel': '杨超越',
9ff94664 1151 'creators': ['杨超越'],
1152 'duration': 17,
ba723997 1153 'timestamp': 1619098692,
1154 'upload_date': '20210422',
1155 'track': '@杨超越创作的原声',
9ff94664 1156 'artists': ['杨超越'],
943d5ab1
M
1157 'view_count': int,
1158 'like_count': int,
1159 'repost_count': int,
1160 'comment_count': int,
92593690 1161 'thumbnail': r're:https?://.+\.jpe?g',
ba723997 1162 },
943d5ab1
M
1163 }, {
1164 'url': 'https://www.douyin.com/video/6950251282489675042',
1165 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1166 'info_dict': {
1167 'id': '6950251282489675042',
1168 'ext': 'mp4',
1169 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1170 'uploader': '杨超越',
1171 'upload_date': '20210412',
1172 'timestamp': 1618231483,
1173 'uploader_id': '110403406559',
1174 'view_count': int,
1175 'like_count': int,
1176 'repost_count': int,
1177 'comment_count': int,
ba723997 1178 },
1179 'skip': 'No longer available',
943d5ab1
M
1180 }, {
1181 'url': 'https://www.douyin.com/video/6963263655114722595',
9ff94664 1182 'md5': '1440bcf59d8700f8e014da073a4dfea8',
943d5ab1
M
1183 'info_dict': {
1184 'id': '6963263655114722595',
1185 'ext': 'mp4',
1186 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
ba723997 1187 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
9ff94664 1188 'uploader': '6897520xka',
943d5ab1 1189 'uploader_id': '110403406559',
ba723997 1190 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
92593690 1191 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
f4f9f6d0 1192 'channel': '杨超越',
9ff94664 1193 'creators': ['杨超越'],
1194 'duration': 15,
ba723997 1195 'timestamp': 1621261163,
1196 'upload_date': '20210517',
1197 'track': '@杨超越创作的原声',
9ff94664 1198 'artists': ['杨超越'],
943d5ab1
M
1199 'view_count': int,
1200 'like_count': int,
1201 'repost_count': int,
1202 'comment_count': int,
92593690 1203 'thumbnail': r're:https?://.+\.jpe?g',
ba723997 1204 },
943d5ab1 1205 }]
943d5ab1 1206 _UPLOADER_URL_FORMAT = 'https://www.douyin.com/user/%s'
53dad39e 1207 _WEBPAGE_HOST = 'https://www.douyin.com/'
943d5ab1
M
1208
1209 def _real_extract(self, url):
1210 video_id = self._match_id(url)
1211
9ff94664 1212 detail = traverse_obj(self._download_json(
1213 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id,
1214 'Downloading web detail JSON', 'Failed to download web detail JSON',
1215 query={'aweme_id': video_id}, fatal=False), ('aweme_detail', {dict}))
1216 if not detail:
943d5ab1 1217 # TODO: Run verification challenge code to generate signature cookies
ba723997 1218 raise ExtractorError(
9ff94664 1219 'Fresh cookies (not necessarily logged in) are needed',
1220 expected=not self._get_cookies(self._WEBPAGE_HOST).get('s_v_web_id'))
943d5ab1 1221
9ff94664 1222 return self._parse_aweme_video_app(detail)
88afe056 1223
1224
49895f06 1225class TikTokVMIE(InfoExtractor):
ba723997 1226 _VALID_URL = r'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
88afe056 1227 IE_NAME = 'vm.tiktok'
1228
49895f06 1229 _TESTS = [{
ba723997 1230 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
49895f06 1231 'info_dict': {
ba723997 1232 'id': '7170520270497680683',
49895f06 1233 'ext': 'mp4',
ba723997 1234 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1235 'uploader_id': '6687535061741700102',
1236 'upload_date': '20221127',
49895f06 1237 'view_count': int,
ba723997 1238 'like_count': int,
49895f06 1239 'comment_count': int,
ba723997 1240 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1241 'album': 'Wave of Mutilation: Best of Pixies',
1242 'thumbnail': r're:https://.+\.webp.*',
1243 'duration': 5,
1244 'timestamp': 1669516858,
49895f06 1245 'repost_count': int,
ba723997 1246 'artist': 'Pixies',
1247 'track': 'Where Is My Mind?',
1248 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1249 'uploader': 'sigmachaddeus',
1250 'creator': 'SigmaChad',
1251 },
1252 }, {
c4cbd3be 1253 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1254 'info_dict': {
1255 'id': '7106798200794926362',
1256 'ext': 'mp4',
1257 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1258 'uploader_id': '6997695878846268418',
1259 'upload_date': '20220608',
1260 'view_count': int,
1261 'like_count': int,
1262 'comment_count': int,
1263 'thumbnail': r're:https://.+\.webp.*',
1264 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1265 'duration': 29,
1266 'timestamp': 1654680400,
1267 'repost_count': int,
1268 'artist': 'Akihitoko',
1269 'track': 'original sound',
1270 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1271 'uploader': 'akihitoko1',
1272 'creator': 'Akihitoko',
1273 },
49895f06 1274 }, {
1275 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1276 'only_matching': True,
1277 }]
1278
88afe056 1279 def _real_extract(self, url):
11e1c2e3 1280 new_url = self._request_webpage(
3d2623a8 1281 HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).url
11e1c2e3 1282 if self.suitable(new_url): # Prevent infinite loop in case redirect fails
1283 raise UnsupportedError(new_url)
1284 return self.url_result(new_url)
933ed882
JC
1285
1286
216bcb66 1287class TikTokLiveIE(TikTokBaseIE):
1288 _VALID_URL = r'''(?x)https?://(?:
1289 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1290 m\.tiktok\.com/share/live/(?P<id>\d+)
1291 )'''
933ed882
JC
1292 IE_NAME = 'tiktok:live'
1293
1294 _TESTS = [{
216bcb66 1295 'url': 'https://www.tiktok.com/@weathernewslive/live',
1296 'info_dict': {
1297 'id': '7210809319192726273',
1298 'ext': 'mp4',
1299 'title': r're:ウェザーニュースLiVE[\d\s:-]*',
1300 'creator': 'ウェザーニュースLiVE',
1301 'uploader': 'weathernewslive',
1302 'uploader_id': '6621496731283095554',
1303 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1304 'live_status': 'is_live',
1305 'concurrent_view_count': int,
1306 },
1307 'params': {'skip_download': 'm3u8'},
1308 }, {
1309 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1310 'info_dict': {
1311 'id': '7209423610325322522',
1312 'ext': 'mp4',
1313 'title': str,
1314 'creator': 'Pilarmagenta',
1315 'uploader': 'pilarmagenta',
1316 'uploader_id': '6624846890674683909',
1317 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1318 'live_status': 'is_live',
1319 'concurrent_view_count': int,
1320 },
1321 'skip': 'Livestream',
1322 }, {
1323 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1324 'only_matching': True,
1325 }, {
933ed882
JC
1326 'url': 'https://www.tiktok.com/@iris04201/live',
1327 'only_matching': True,
1328 }]
1329
216bcb66 1330 def _call_api(self, url, param, room_id, uploader, key=None):
1331 response = traverse_obj(self._download_json(
1332 url, room_id, fatal=False, query={
1333 'aid': '1988',
1334 param: room_id,
1335 }), (key, {dict}), default={})
1336
1337 # status == 2 if live else 4
1338 if int_or_none(response.get('status')) == 2:
1339 return response
1340 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1341 elif not uploader:
1342 raise ExtractorError('This livestream has ended', expected=True)
1343 raise UserNotLive(video_id=uploader)
1344
933ed882 1345 def _real_extract(self, url):
216bcb66 1346 uploader, room_id = self._match_valid_url(url).group('uploader', 'id')
1347 webpage = self._download_webpage(
1348 url, uploader or room_id, headers={'User-Agent': 'Mozilla/5.0'}, fatal=not room_id)
1349
1350 if webpage:
d9b4154c 1351 data = self._get_sigi_state(webpage, uploader or room_id)
216bcb66 1352 room_id = (traverse_obj(data, ('UserModule', 'users', ..., 'roomId', {str_or_none}), get_all=False)
1353 or self._search_regex(r'snssdk\d*://live\?room_id=(\d+)', webpage, 'room ID', default=None)
1354 or room_id)
1355 uploader = uploader or traverse_obj(
1356 data, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1357 ('UserModule', 'users', ..., 'uniqueId'), get_all=False, expected_type=str)
1358
933ed882
JC
1359 if not room_id:
1360 raise UserNotLive(video_id=uploader)
933ed882 1361
216bcb66 1362 formats = []
1363 live_info = self._call_api(
1364 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id, uploader, key='data')
1365
1366 get_quality = qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1367 parse_inner = lambda x: self._parse_json(x, None)
1368
1369 for quality, stream in traverse_obj(live_info, (
1370 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1371 {parse_inner}, 'data', {dict}), default={}).items():
1372
1373 sdk_params = traverse_obj(stream, ('main', 'sdk_params', {parse_inner}, {
1374 'vcodec': ('VCodec', {str}),
1375 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}),
1376 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}),
1377 }))
1378
1379 flv_url = traverse_obj(stream, ('main', 'flv', {url_or_none}))
1380 if flv_url:
1381 formats.append({
1382 'url': flv_url,
1383 'ext': 'flv',
1384 'format_id': f'flv-{quality}',
1385 'quality': get_quality(quality),
1386 **sdk_params,
1387 })
1388
1389 hls_url = traverse_obj(stream, ('main', 'hls', {url_or_none}))
1390 if hls_url:
1391 formats.append({
1392 'url': hls_url,
1393 'ext': 'mp4',
1394 'protocol': 'm3u8_native',
1395 'format_id': f'hls-{quality}',
1396 'quality': get_quality(quality),
1397 **sdk_params,
1398 })
1399
1400 def get_vcodec(*keys):
1401 return traverse_obj(live_info, (
1402 'stream_url', *keys, {parse_inner}, 'VCodec', {str}))
1403
1404 for stream in ('hls', 'rtmp'):
1405 stream_url = traverse_obj(live_info, ('stream_url', f'{stream}_pull_url', {url_or_none}))
1406 if stream_url:
1407 formats.append({
1408 'url': stream_url,
1409 'ext': 'mp4' if stream == 'hls' else 'flv',
1410 'protocol': 'm3u8_native' if stream == 'hls' else 'https',
1411 'format_id': f'{stream}-pull',
1412 'vcodec': get_vcodec(f'{stream}_pull_url_params'),
1413 'quality': get_quality('ORIGION'),
1414 })
1415
1416 for f_id, f_url in traverse_obj(live_info, ('stream_url', 'flv_pull_url', {dict}), default={}).items():
1417 if not url_or_none(f_url):
1418 continue
1419 formats.append({
1420 'url': f_url,
1421 'ext': 'flv',
1422 'format_id': f'flv-{f_id}'.lower(),
1423 'vcodec': get_vcodec('flv_pull_url_params', f_id),
1424 'quality': get_quality(f_id),
1425 })
1426
1427 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1428 if not traverse_obj(formats, lambda _, v: v['ext'] == 'mp4'):
1429 live_info = merge_dicts(live_info, self._call_api(
1430 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id, uploader, key='LiveRoomInfo'))
1431 if url_or_none(live_info.get('liveUrl')):
1432 formats.append({
1433 'url': live_info['liveUrl'],
1434 'ext': 'mp4',
1435 'protocol': 'm3u8_native',
1436 'format_id': 'hls-fallback',
1437 'vcodec': 'h264',
1438 'quality': get_quality('origin'),
1439 })
1440
1441 uploader = uploader or traverse_obj(live_info, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
933ed882
JC
1442
1443 return {
1444 'id': room_id,
933ed882 1445 'uploader': uploader,
216bcb66 1446 'uploader_url': format_field(uploader, None, self._UPLOADER_URL_FORMAT) or None,
933ed882 1447 'is_live': True,
216bcb66 1448 'formats': formats,
1449 '_format_sort_fields': ('quality', 'ext'),
1450 **traverse_obj(live_info, {
1451 'title': 'title',
1452 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}),
1453 'creator': (('ownerInfo', 'owner'), 'nickname'),
1454 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}),
1455 }, get_all=False),
933ed882 1456 }