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