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