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