11 from .common
import InfoExtractor
12 from ..networking
import HEADRequest
26 srt_subtitles_timecode
,
36 class TikTokBaseIE(InfoExtractor
):
37 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
38 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
39 QUALITIES
= ('360p', '540p', '720p', '1080p')
41 _APP_INFO_DEFAULTS
= {
44 # TikTok (KR/PH/TW/TH/VN) = trill, TikTok (rest of world) = musical_ly, Douyin = aweme
45 'app_name': 'musical_ly',
46 'app_version': '35.1.3',
47 'manifest_app_version': '2023501030',
48 # "app id": aweme = 1128, trill = 1180, musical_ly = 1233, universal = 0
53 _APP_USER_AGENT
= None
55 @functools.cached_property
56 def _KNOWN_APP_INFO(self
):
57 # If we have a genuine device ID, we may not need any IID
58 default
= [''] if self
._KNOWN
_DEVICE
_ID
else []
59 return self
._configuration
_arg
('app_info', default
, ie_key
=TikTokIE
)
61 @functools.cached_property
62 def _KNOWN_DEVICE_ID(self
):
63 return self
._configuration
_arg
('device_id', [None], ie_key
=TikTokIE
)[0]
65 @functools.cached_property
67 return self
._KNOWN
_DEVICE
_ID
or str(random
.randint(7250000000000000000, 7351147085025500000))
69 @functools.cached_property
70 def _API_HOSTNAME(self
):
71 return self
._configuration
_arg
(
72 'api_hostname', ['api16-normal-c-useast1a.tiktokv.com'], ie_key
=TikTokIE
)[0]
74 def _get_next_app_info(self
):
75 if self
._APP
_INFO
_POOL
is None:
77 key
: self
._configuration
_arg
(key
, [default
], ie_key
=TikTokIE
)[0]
78 for key
, default
in self
._APP
_INFO
_DEFAULTS
.items()
81 self
._APP
_INFO
_POOL
= [
83 (k
, v
) for k
, v
in zip(self
._APP
_INFO
_DEFAULTS
, app_info
.split('/')) if v
84 )} for app_info
in self
._KNOWN
_APP
_INFO
87 if not self
._APP
_INFO
_POOL
:
90 self
._APP
_INFO
= self
._APP
_INFO
_POOL
.pop(0)
92 app_name
= self
._APP
_INFO
['app_name']
93 version
= self
._APP
_INFO
['manifest_app_version']
94 if app_name
== 'musical_ly':
95 package
= f
'com.zhiliaoapp.musically/{version}'
97 package
= f
'com.ss.android.ugc.{app_name}/{version}'
98 self
._APP
_USER
_AGENT
= f
'{package} (Linux; U; Android 13; en_US; Pixel 7; Build/TD1A.220804.031; Cronet/58.0.2991.0)'
103 def _create_url(user_id
, video_id
):
104 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
106 def _get_sigi_state(self
, webpage
, display_id
):
107 return self
._search
_json
(
108 r
'<script[^>]+\bid="(?:SIGI_STATE|sigi-persisted-data)"[^>]*>', webpage
,
109 'sigi state', display_id
, end_pattern
=r
'</script>', default
={})
111 def _get_universal_data(self
, webpage
, display_id
):
112 return traverse_obj(self
._search
_json
(
113 r
'<script[^>]+\bid="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>', webpage
,
114 'universal data', display_id
, end_pattern
=r
'</script>', default
={}),
115 ('__DEFAULT_SCOPE__', {dict}
)) or {}
117 def _call_api_impl(self
, ep
, video_id
, query
=None, data
=None, headers
=None, fatal
=True,
118 note
='Downloading API JSON', errnote
='Unable to download API page'):
119 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choices('0123456789abcdef', k
=160)))
120 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
121 if webpage_cookies
.get('sid_tt'):
122 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
123 return self
._download
_json
(
124 f
'https://{self._API_HOSTNAME}/aweme/v1/{ep}/', video_id
=video_id
,
125 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
126 'User-Agent': self
._APP
_USER
_AGENT
,
127 'Accept': 'application/json',
129 }, query
=query
, data
=data
)
131 def _build_api_query(self
, query
):
134 'device_platform': 'android',
137 '_rticket': int(time
.time() * 1000),
138 'cdid': str(uuid
.uuid4()),
139 'channel': 'googleplay',
140 'aid': self
._APP
_INFO
['aid'],
141 'app_name': self
._APP
_INFO
['app_name'],
142 'version_code': ''.join(f
'{int(v):02d}' for v
in self
._APP
_INFO
['app_version'].split('.')),
143 'version_name': self
._APP
_INFO
['app_version'],
144 'manifest_version_code': self
._APP
_INFO
['manifest_app_version'],
145 'update_version_code': self
._APP
_INFO
['manifest_app_version'],
146 'ab_version': self
._APP
_INFO
['app_version'],
147 'resolution': '1080*2400',
149 'device_type': 'Pixel 7',
150 'device_brand': 'Google',
156 'current_region': 'US',
157 'app_type': 'normal',
159 'last_install_time': int(time
.time()) - random
.randint(86400, 1123200),
160 'timezone_name': 'America/New_York',
162 'app_language': 'en',
163 'timezone_offset': '-14400',
164 'host_abi': 'armeabi-v7a',
168 'carrier_region': 'US',
170 'build_number': self
._APP
_INFO
['app_version'],
172 'ts': int(time
.time()),
173 'iid': self
._APP
_INFO
.get('iid'),
174 'device_id': self
._DEVICE
_ID
,
175 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
178 def _call_api(self
, ep
, video_id
, query
=None, data
=None, headers
=None, fatal
=True,
179 note
='Downloading API JSON', errnote
='Unable to download API page'):
180 if not self
._APP
_INFO
and not self
._get
_next
_app
_info
():
181 message
= 'No working app info is available'
183 raise ExtractorError(message
, expected
=True)
185 self
.report_warning(message
)
188 max_tries
= len(self
._APP
_INFO
_POOL
) + 1 # _APP_INFO_POOL + _APP_INFO
189 for count
in itertools
.count(1):
190 self
.write_debug(str(self
._APP
_INFO
))
191 real_query
= self
._build
_api
_query
(query
or {})
193 return self
._call
_api
_impl
(
194 ep
, video_id
, query
=real_query
, data
=data
, headers
=headers
,
195 fatal
=fatal
, note
=note
, errnote
=errnote
)
196 except ExtractorError
as e
:
197 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
198 message
= str(e
.cause
or e
.msg
)
199 if not self
._get
_next
_app
_info
():
203 self
.report_warning(message
)
205 self
.report_warning(f
'{message}. Retrying... (attempt {count} of {max_tries})')
209 def _extract_aweme_app(self
, aweme_id
):
210 aweme_detail
= traverse_obj(
211 self
._call
_api
('multi/aweme/detail', aweme_id
, data
=urlencode_postdata({
212 'aweme_ids': f
'[{aweme_id}]',
213 'request_source': '0',
214 }), headers
={'X-Argus': ''}), ('aweme_details', 0, {dict}
))
216 raise ExtractorError('Unable to extract aweme detail info', video_id
=aweme_id
)
217 return self
._parse
_aweme
_video
_app
(aweme_detail
)
219 def _extract_web_data_and_status(self
, url
, video_id
, fatal
=True):
220 video_data
, status
= {}, -1
222 res
= self
._download
_webpage
_handle
(url
, video_id
, fatal
=fatal
, headers
={'User-Agent': 'Mozilla/5.0'})
224 return video_data
, status
227 if urllib
.parse
.urlparse(urlh
.url
).path
== '/login':
228 message
= 'TikTok is requiring login for access to this content'
230 self
.raise_login_required(message
)
231 self
.report_warning(f
'{message}. {self._login_hint()}')
232 return video_data
, status
234 if universal_data
:= self
._get
_universal
_data
(webpage
, video_id
):
235 self
.write_debug('Found universal data for rehydration')
236 status
= traverse_obj(universal_data
, ('webapp.video-detail', 'statusCode', {int}
)) or 0
237 video_data
= traverse_obj(universal_data
, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict}
))
239 elif sigi_data
:= self
._get
_sigi
_state
(webpage
, video_id
):
240 self
.write_debug('Found sigi state data')
241 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode', {int}
)) or 0
242 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
, {dict}
))
244 elif next_data
:= self
._search
_nextjs
_data
(webpage
, video_id
, default
={}):
245 self
.write_debug('Found next.js data')
246 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode', {int}
)) or 0
247 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict}
))
250 raise ExtractorError('Unable to extract webpage video data')
252 return video_data
, status
254 def _get_subtitles(self
, aweme_detail
, aweme_id
, user_name
):
255 # TODO: Extract text positioning info
257 EXT_MAP
= { # From lowest to highest preference
258 'creator_caption': 'json',
262 preference
= qualities(tuple(EXT_MAP
.values()))
266 # aweme/detail endpoint subs
267 captions_info
= traverse_obj(
268 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
269 for caption
in captions_info
:
270 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
273 caption_json
= self
._download
_json
(
274 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
277 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
280 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
281 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text')),
285 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
286 if not caption
.get('url'):
288 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
289 'url': caption
['url'],
290 'ext': EXT_MAP
.get(caption
.get('Format')),
294 if user_name
: # only _parse_aweme_video_app needs to extract the webpage here
295 aweme_detail
, _
= self
._extract
_web
_data
_and
_status
(
296 self
._create
_url
(user_name
, aweme_id
), aweme_id
, fatal
=False)
297 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', lambda _
, v
: v
['Url'])):
298 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
299 'url': caption
['Url'],
300 'ext': EXT_MAP
.get(caption
.get('Format')),
303 # Deprioritize creator_caption json since it can't be embedded or used by media players
304 for lang
, subs_list
in subtitles
.items():
305 subtitles
[lang
] = sorted(subs_list
, key
=lambda x
: preference(x
['ext']))
309 def _parse_url_key(self
, url_key
):
310 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
311 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
312 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
316 'format_id': format_id
,
317 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
318 'tbr': int_or_none(bitrate
, scale
=1000) or None,
319 'quality': qualities(self
.QUALITIES
)(res
),
322 def _parse_aweme_video_app(self
, aweme_detail
):
323 aweme_id
= aweme_detail
['aweme_id']
324 video_info
= aweme_detail
['video']
325 known_resolutions
= {}
328 ext
= determine_ext(url
, default_ext
='m4a')
330 'format_note': 'Music track',
332 'acodec': 'aac' if ext
== 'm4a' else ext
,
336 } if ext
== 'mp3' or '-music-' in url
else {}
338 def extract_addr(addr
, add_meta
={}):
339 parsed_meta
, res
= self
._parse
_url
_key
(addr
.get('url_key', ''))
340 is_bytevc2
= parsed_meta
.get('vcodec') == 'bytevc2'
342 known_resolutions
.setdefault(res
, {}).setdefault('height', int_or_none(addr
.get('height')))
343 known_resolutions
[res
].setdefault('width', int_or_none(addr
.get('width')))
344 parsed_meta
.update(known_resolutions
.get(res
, {}))
345 add_meta
.setdefault('height', int_or_none(res
[:-1]))
348 'filesize': int_or_none(addr
.get('data_size')),
351 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
352 **add_meta
, **parsed_meta
,
353 # bytevc2 is bytedance's own custom h266/vvc codec, as-of-yet unplayable
354 'preference': -100 if is_bytevc2
else -1,
355 'format_note': join_nonempty(
356 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None,
357 '(UNPLAYABLE)' if is_bytevc2
else None, delim
=' '),
359 } for url
in addr
.get('url_list') or []]
361 # Hack: Add direct video links first to prioritize them when removing duplicate formats
363 width
= int_or_none(video_info
.get('width'))
364 height
= int_or_none(video_info
.get('height'))
365 ratio
= try_call(lambda: width
/ height
) or 0.5625
366 if video_info
.get('play_addr'):
367 formats
.extend(extract_addr(video_info
['play_addr'], {
368 'format_id': 'play_addr',
369 'format_note': 'Direct video',
370 'vcodec': 'h265' if traverse_obj(
371 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
375 if video_info
.get('download_addr'):
376 download_addr
= video_info
['download_addr']
377 dl_width
= int_or_none(download_addr
.get('width'))
378 formats
.extend(extract_addr(download_addr
, {
379 'format_id': 'download_addr',
380 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
383 'height': try_call(lambda: int(dl_width
/ ratio
)), # download_addr['height'] is wrong
384 'preference': -2 if video_info
.get('has_watermark') else -1,
386 if video_info
.get('play_addr_h264'):
387 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
388 'format_id': 'play_addr_h264',
389 'format_note': 'Direct video',
392 if video_info
.get('play_addr_bytevc1'):
393 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
394 'format_id': 'play_addr_bytevc1',
395 'format_note': 'Direct video',
399 for bitrate
in video_info
.get('bit_rate', []):
400 if bitrate
.get('play_addr'):
401 formats
.extend(extract_addr(bitrate
['play_addr'], {
402 'format_id': bitrate
.get('gear_name'),
403 'format_note': 'Playback video',
404 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
405 'vcodec': 'h265' if traverse_obj(
406 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
407 'fps': bitrate
.get('FPS'),
410 self
._remove
_duplicate
_formats
(formats
)
411 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
414 self
._set
_cookie
(urllib
.parse
.urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
417 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
418 'origin_cover', 'dynamic_cover'):
419 for cover_url
in traverse_obj(video_info
, (cover_id
, 'url_list', ...)):
425 stats_info
= aweme_detail
.get('statistics') or {}
426 music_info
= aweme_detail
.get('music') or {}
427 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str)
429 contained_music_track
= traverse_obj(
430 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
431 contained_music_author
= traverse_obj(
432 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
434 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - {}'.format(music_info
.get('owner_handle'))
435 if is_generic_og_trackname
:
436 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
438 music_track
, music_author
= music_info
.get('title'), traverse_obj(music_info
, ('author', {str}
))
440 author_info
= traverse_obj(aweme_detail
, ('author', {
441 'uploader': ('unique_id', {str}
),
442 'uploader_id': ('uid', {str_or_none}
),
443 'channel': ('nickname', {str}
),
444 'channel_id': ('sec_uid', {str}
),
449 **traverse_obj(aweme_detail
, {
450 'title': ('desc', {str}
),
451 'description': ('desc', {str}
),
452 'timestamp': ('create_time', {int_or_none}
),
454 **traverse_obj(stats_info
, {
455 'view_count': 'play_count',
456 'like_count': 'digg_count',
457 'repost_count': 'share_count',
458 'comment_count': 'comment_count',
459 }, expected_type
=int_or_none
),
461 'channel_url': format_field(author_info
, 'channel_id', self
._UPLOADER
_URL
_FORMAT
, default
=None),
462 'uploader_url': format_field(
463 author_info
, ['uploader', 'uploader_id'], self
._UPLOADER
_URL
_FORMAT
, default
=None),
464 'track': music_track
,
465 'album': str_or_none(music_info
.get('album')) or None,
466 'artists': re
.split(r
'(?:, | & )', music_author
) if music_author
else None,
468 'subtitles': self
.extract_subtitles(
469 aweme_detail
, aweme_id
, traverse_obj(author_info
, 'uploader', 'uploader_id', 'channel_id')),
470 'thumbnails': thumbnails
,
471 'duration': (traverse_obj(video_info
, (
472 (None, 'download_addr'), 'duration', {int_or_none(scale
=1000)}, any
))
473 or traverse_obj(music_info
, ('duration', {int_or_none}
))),
474 'availability': self
._availability
(
475 is_private
='Private' in labels
,
476 needs_subscription
='Friends only' in labels
,
477 is_unlisted
='Followers only' in labels
),
478 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
481 def _extract_web_formats(self
, aweme_detail
):
482 COMMON_FORMAT_INFO
= {
487 video_info
= traverse_obj(aweme_detail
, ('video', {dict}
)) or {}
488 play_width
= int_or_none(video_info
.get('width'))
489 play_height
= int_or_none(video_info
.get('height'))
490 ratio
= try_call(lambda: play_width
/ play_height
) or 0.5625
493 for bitrate_info
in traverse_obj(video_info
, ('bitrateInfo', lambda _
, v
: v
['PlayAddr']['UrlList'])):
494 format_info
, res
= self
._parse
_url
_key
(
495 traverse_obj(bitrate_info
, ('PlayAddr', 'UrlKey', {str}
)) or '')
496 # bytevc2 is bytedance's own custom h266/vvc codec, as-of-yet unplayable
497 is_bytevc2
= format_info
.get('vcodec') == 'bytevc2'
499 'format_note': 'UNPLAYABLE' if is_bytevc2
else None,
500 'preference': -100 if is_bytevc2
else -1,
501 'filesize': traverse_obj(bitrate_info
, ('PlayAddr', 'DataSize', {int_or_none}
)),
504 if dimension
:= (res
and int(res
[:-1])):
505 if dimension
== 540: # '540p' is actually 576p
507 if ratio
< 1: # portrait: res/dimension is width
508 y
= int(dimension
/ ratio
)
511 'height': y
- (y
% 2),
513 else: # landscape: res/dimension is height
514 x
= int(dimension
* ratio
)
516 'width': x
+ (x
% 2),
520 for video_url
in traverse_obj(bitrate_info
, ('PlayAddr', 'UrlList', ..., {url_or_none}
)):
522 **COMMON_FORMAT_INFO
,
524 'url': self
._proto
_relative
_url
(video_url
),
527 # We don't have res string for play formats, but need quality for sorting & de-duplication
528 play_quality
= traverse_obj(formats
, (lambda _
, v
: v
['width'] == play_width
, 'quality', any
))
530 for play_url
in traverse_obj(video_info
, ('playAddr', ((..., 'src'), None), {url_or_none}
)):
532 **COMMON_FORMAT_INFO
,
534 'url': self
._proto
_relative
_url
(play_url
),
536 'height': play_height
,
537 'quality': play_quality
,
540 for download_url
in traverse_obj(video_info
, (('downloadAddr', ('download', 'url')), {url_or_none}
)):
542 **COMMON_FORMAT_INFO
,
543 'format_id': 'download',
544 'url': self
._proto
_relative
_url
(download_url
),
545 'format_note': 'watermarked',
549 self
._remove
_duplicate
_formats
(formats
)
551 # Is it a slideshow with only audio for download?
552 if not formats
and traverse_obj(aweme_detail
, ('music', 'playUrl', {url_or_none}
)):
553 audio_url
= aweme_detail
['music']['playUrl']
554 ext
= traverse_obj(parse_qs(audio_url
), (
555 'mime_type', -1, {lambda x
: x
.replace('_', '/')}, {mimetype2ext}
)) or 'm4a'
557 'format_id': 'audio',
558 'url': self
._proto
_relative
_url
(audio_url
),
560 'acodec': 'aac' if ext
== 'm4a' else ext
,
564 # Filter out broken formats, see https://github.com/yt-dlp/yt-dlp/issues/11034
565 return [f
for f
in formats
if urllib
.parse
.urlparse(f
['url']).hostname
!= 'www.tiktok.com']
567 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
, video_id
, extract_flat
=False):
568 author_info
= traverse_obj(aweme_detail
, (('authorInfo', 'author', None), {
569 'channel': ('nickname', {str}
),
570 'channel_id': (('authorSecId', 'secUid'), {str}
),
571 'uploader': (('uniqueId', 'author'), {str}
),
572 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}
),
577 'formats': None if extract_flat
else self
._extract
_web
_formats
(aweme_detail
),
578 'subtitles': None if extract_flat
else self
.extract_subtitles(aweme_detail
, video_id
, None),
579 'http_headers': {'Referer': webpage_url
},
581 'channel_url': format_field(author_info
, 'channel_id', self
._UPLOADER
_URL
_FORMAT
, default
=None),
582 'uploader_url': format_field(
583 author_info
, ['uploader', 'uploader_id'], self
._UPLOADER
_URL
_FORMAT
, default
=None),
584 **traverse_obj(aweme_detail
, ('music', {
585 'track': ('title', {str}
),
586 'album': ('album', {str}
, filter),
587 'artists': ('authorName', {str}
, {lambda x
: re
.split(r
'(?:, | & )', x
) if x
else None}),
588 'duration': ('duration', {int_or_none}
),
590 **traverse_obj(aweme_detail
, {
591 'title': ('desc', {str}
),
592 'description': ('desc', {str}
),
593 # audio-only slideshows have a video duration of 0 and an actual audio duration
594 'duration': ('video', 'duration', {int_or_none}
, filter),
595 'timestamp': ('createTime', {int_or_none}
),
597 **traverse_obj(aweme_detail
, ('stats', {
598 'view_count': 'playCount',
599 'like_count': 'diggCount',
600 'repost_count': 'shareCount',
601 'comment_count': 'commentCount',
602 }), expected_type
=int_or_none
),
603 'thumbnails': traverse_obj(aweme_detail
, (
604 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {
605 'url': ({url_or_none}
, {self
._proto
_relative
_url
}),
611 class TikTokIE(TikTokBaseIE
):
612 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
613 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
616 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
617 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
619 'id': '6748451240264420610',
621 'title': '#jassmanak #lehanga #leenabhushan',
622 'description': '#jassmanak #lehanga #leenabhushan',
626 'uploader': 'leenabhushan',
627 'uploader_id': '6691488002098119685',
628 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
629 'creator': 'facestoriesbyleenabh',
630 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
631 'upload_date': '20191016',
632 'timestamp': 1571246252,
636 'comment_count': int,
637 'artist': 'Ysrbeats',
641 'skip': '404 Not Found',
643 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
644 'md5': 'f21112672ee4ce05ca390fb6522e1b6f',
646 'id': '6742501081818877190',
648 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
649 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
653 'uploader': 'patrox',
654 'uploader_id': '18702747',
655 'uploader_url': 'https://www.tiktok.com/@patrox',
656 'channel_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
657 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
659 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
660 'upload_date': '20190930',
661 'timestamp': 1569860870,
665 'comment_count': int,
666 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'],
670 # Banned audio, was available on the app, now works with web too
671 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
673 'id': '6984138651336838402',
675 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
676 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
677 'uploader': 'barudakhb_',
678 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
679 'uploader_id': '6974687867511718913',
680 'uploader_url': 'https://www.tiktok.com/@barudakhb_',
681 'channel_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
682 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
683 'track': 'Boka Dance',
684 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
685 'timestamp': 1626121503,
687 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
688 'upload_date': '20210712',
692 'comment_count': int,
695 # Sponsored video, only available with feed workaround
696 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
698 'id': '7042692929109986561',
700 'title': 'Slap and Run!',
701 'description': 'Slap and Run!',
702 'uploader': 'user440922249',
703 'channel': 'Slap And Run',
704 'uploader_id': '7036055384943690754',
705 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
706 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
707 'track': 'Promoted Music',
708 'timestamp': 1639754738,
710 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
711 'upload_date': '20211217',
715 'comment_count': int,
717 'skip': 'This video is unavailable',
719 # Video without title and description
720 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
722 'id': '7059698374567611694',
724 'title': 'TikTok video #7059698374567611694',
726 'uploader': 'pokemonlife22',
727 'channel': 'Pokemon',
728 'uploader_id': '6820838815978423302',
729 'uploader_url': 'https://www.tiktok.com/@pokemonlife22',
730 'channel_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
731 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
732 'track': 'original sound',
733 'timestamp': 1643714123,
735 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
736 'upload_date': '20220201',
737 'artists': ['Pokemon'],
741 'comment_count': int,
744 # hydration JSON is sent in a <script> element
745 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
747 'id': '7065799023130643713',
749 'title': '#denidil#денидил',
750 'description': '#denidil#денидил',
751 'uploader': 'denidil6',
752 'uploader_id': '7046664115636405250',
753 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
754 'artist': 'Holocron Music',
755 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
756 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
757 'timestamp': 1645134536,
759 'upload_date': '20220217',
763 'comment_count': int,
765 'skip': 'This video is unavailable',
767 # slideshow audio-only mp3 format
768 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
770 'id': '7139980461132074283',
772 'title': 'TikTok video #7139980461132074283',
774 'channel': 'Antaura',
775 'uploader': '_le_cannibale_',
776 'uploader_id': '6604511138619654149',
777 'uploader_url': 'https://www.tiktok.com/@_le_cannibale_',
778 'channel_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
779 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
780 'artists': ['nathan !'],
781 'track': 'grahamscott canon',
783 'upload_date': '20220905',
784 'timestamp': 1662406249,
788 'comment_count': int,
789 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
792 # only available via web
793 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662',
794 'md5': '4cdefa501ac8ac20bf04986e10916fea',
796 'id': '7206382937372134662',
798 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
799 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
800 'channel': 'MoxyPatch',
801 'uploader': 'moxypatch',
802 'uploader_id': '7039142049363379205',
803 'uploader_url': 'https://www.tiktok.com/@moxypatch',
804 'channel_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
805 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
806 'artists': ['your worst nightmare'],
807 'track': 'original sound',
808 'upload_date': '20230303',
809 'timestamp': 1677866781,
814 'comment_count': int,
815 'thumbnail': r
're:^https://.+',
816 'thumbnails': 'count:3',
818 'expected_warnings': ['Unable to find video in feed'],
821 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME: Web can only get audio
822 'md5': '982512017a8a917124d5a08c8ae79621',
824 'id': '7107337212743830830',
826 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
827 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
828 'uploader': 'tatemcrae',
829 'uploader_id': '86328792343818240',
830 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
831 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
832 'channel': 'tate mcrae',
833 'artists': ['tate mcrae'],
834 'track': 'original sound',
835 'upload_date': '20220609',
836 'timestamp': 1654805899,
841 'comment_count': int,
842 'thumbnail': r
're:^https://.+\.webp',
844 'skip': 'Unavailable via feed API, only audio available via web',
846 # Slideshow, audio-only m4a format
847 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
848 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
850 'id': '7253412088251534594',
852 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
853 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
854 'uploader': 'hara_yoimiya',
855 'uploader_id': '6582536342634676230',
856 'uploader_url': 'https://www.tiktok.com/@hara_yoimiya',
857 'channel_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
858 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
859 'channel': 'лампочка(!)',
860 'artists': ['Øneheart'],
861 'album': 'watching the stars',
862 'track': 'watching the stars',
864 'upload_date': '20230708',
865 'timestamp': 1688816612,
868 'comment_count': int,
870 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
873 # Auto-captions available
874 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
875 'only_matching': True,
878 def _real_extract(self
, url
):
879 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
881 if self
._KNOWN
_APP
_INFO
:
883 return self
._extract
_aweme
_app
(video_id
)
884 except ExtractorError
as e
:
886 self
.report_warning(f
'{e}; trying with webpage')
888 url
= self
._create
_url
(user_id
, video_id
)
889 video_data
, status
= self
._extract
_web
_data
_and
_status
(url
, video_id
)
891 if video_data
and status
== 0:
892 return self
._parse
_aweme
_video
_web
(video_data
, url
, video_id
)
893 elif status
== 10216:
894 raise ExtractorError('This video is private', expected
=True)
895 raise ExtractorError(f
'Video not available, status code {status}', video_id
=video_id
)
898 class TikTokUserIE(TikTokBaseIE
):
899 IE_NAME
= 'tiktok:user'
900 _VALID_URL
= r
'(?:tiktokuser:|https?://(?:www\.)?tiktok\.com/@)(?P<id>[\w.-]+)/?(?:$|[#?])'
902 'url': 'https://tiktok.com/@corgibobaa?lang=en',
903 'playlist_mincount': 45,
905 'id': 'MS4wLjABAAAAepiJKgwWhulvCpSuUVsp7sgVVsFJbbNaLeQ6OQ0oAJERGDUIXhb2yxxHZedsItgT',
906 'title': 'corgibobaa',
909 'url': 'https://www.tiktok.com/@6820838815978423302',
910 'playlist_mincount': 5,
912 'id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
913 'title': '6820838815978423302',
916 'url': 'https://www.tiktok.com/@meme',
917 'playlist_mincount': 593,
919 'id': 'MS4wLjABAAAAiKfaDWeCsT3IHwY77zqWGtVRIy9v4ws1HbVi7auP1Vx7dJysU_hc5yRiGywojRD6',
923 'url': 'tiktokuser:MS4wLjABAAAAM3R2BtjzVT-uAtstkl2iugMzC6AtnpkojJbjiOdDDrdsTiTR75-8lyWJCY5VvDrZ',
924 'playlist_mincount': 31,
926 'id': 'MS4wLjABAAAAM3R2BtjzVT-uAtstkl2iugMzC6AtnpkojJbjiOdDDrdsTiTR75-8lyWJCY5VvDrZ',
929 _USER_AGENT
= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0'
930 _API_BASE_URL
= 'https://www.tiktok.com/api/creator/item_list/'
932 def _build_web_query(self
, sec_uid
, cursor
):
935 'app_language': 'en',
936 'app_name': 'tiktok_web',
937 'browser_language': 'en-US',
938 'browser_name': 'Mozilla',
939 'browser_online': 'true',
940 'browser_platform': 'Win32',
941 'browser_version': '5.0 (Windows)',
942 'channel': 'tiktok_web',
943 'cookie_enabled': 'true',
946 'device_id': self
._DEVICE
_ID
,
947 'device_platform': 'web_pc',
948 'focus_state': 'true',
951 'is_fullscreen': 'false',
952 'is_page_visible': 'true',
955 'priority_region': '',
958 'screen_height': '1080',
959 'screen_width': '1920',
961 'type': '1', # pagination type: 0 == oldest-to-newest, 1 == newest-to-oldest
963 'verifyFp': f
'verify_{"".join(random.choices(string.hexdigits, k=7))}',
964 'webcast_language': 'en',
967 def _entries(self
, sec_uid
, user_name
):
968 display_id
= user_name
or sec_uid
971 cursor
= int(time
.time() * 1E3
)
972 for page
in itertools
.count(1):
973 response
= self
._download
_json
(
974 self
._API
_BASE
_URL
, display_id
, f
'Downloading page {page}',
975 query
=self
._build
_web
_query
(sec_uid
, cursor
), headers
={'User-Agent': self
._USER
_AGENT
})
977 for video
in traverse_obj(response
, ('itemList', lambda _
, v
: v
['id'])):
978 video_id
= video
['id']
979 if video_id
in seen_ids
:
981 seen_ids
.add(video_id
)
982 webpage_url
= self
._create
_url
(display_id
, video_id
)
983 yield self
.url_result(
984 webpage_url
, TikTokIE
,
985 **self
._parse
_aweme
_video
_web
(video
, webpage_url
, video_id
, extract_flat
=True))
988 cursor
= traverse_obj(
989 response
, ('itemList', -1, 'createTime', {lambda x
: int(x
* 1E3
)}))
990 if not cursor
or old_cursor
== cursor
:
991 # User may not have posted within this ~1 week lookback, so manually adjust cursor
992 cursor
= old_cursor
- 7 * 86_400_000
993 # In case 'hasMorePrevious' is wrong, break if we have gone back before TikTok existed
994 if cursor
< 1472706000000 or not traverse_obj(response
, 'hasMorePrevious'):
997 def _get_sec_uid(self
, user_url
, user_name
, msg
):
998 webpage
= self
._download
_webpage
(
999 user_url
, user_name
, fatal
=False, headers
={'User-Agent': 'Mozilla/5.0'},
1000 note
=f
'Downloading {msg} webpage', errnote
=f
'Unable to download {msg} webpage') or ''
1001 return (traverse_obj(self
._get
_universal
_data
(webpage
, user_name
),
1002 ('webapp.user-detail', 'userInfo', 'user', 'secUid', {str}
))
1003 or traverse_obj(self
._get
_sigi
_state
(webpage
, user_name
),
1004 ('LiveRoom', 'liveRoomUserInfo', 'user', 'secUid', {str}
),
1005 ('UserModule', 'users', ..., 'secUid', {str}
, any
)))
1007 def _real_extract(self
, url
):
1008 user_name
, sec_uid
= self
._match
_id
(url
), None
1009 if mobj
:= re
.fullmatch(r
'MS4wLjABAAAA[\w-]{64}', user_name
):
1010 user_name
, sec_uid
= None, mobj
.group(0)
1012 sec_uid
= (self
._get
_sec
_uid
(self
._UPLOADER
_URL
_FORMAT
% user_name
, user_name
, 'user')
1013 or self
._get
_sec
_uid
(self
._UPLOADER
_URL
_FORMAT
% f
'{user_name}/live', user_name
, 'live'))
1016 webpage
= self
._download
_webpage
(
1017 f
'https://www.tiktok.com/embed/@{user_name}', user_name
,
1018 note
='Downloading user embed page', fatal
=False) or ''
1019 data
= traverse_obj(self
._search
_json
(
1020 r
'<script[^>]+\bid=[\'"]__FRONTITY_CONNECT_STATE__[\'"][^
>]*>',
1021 webpage, 'data
', user_name, default={}),
1022 ('source
', 'data
', f'/embed
/@{user_name}
', {dict}))
1024 for aweme_id in traverse_obj(data, ('videoList
', ..., 'id', {str})):
1025 webpage_url = self._create_url(user_name, aweme_id)
1026 video_data, _ = self._extract_web_data_and_status(webpage_url, aweme_id, fatal=False)
1027 sec_uid = self._parse_aweme_video_web(
1028 video_data, webpage_url, aweme_id, extract_flat=True).get('channel_id
')
1033 raise ExtractorError(
1034 'Unable to extract secondary user ID
. If you are able to get the channel_id
'
1035 'from a video posted by this user
, try using
"tiktokuser:channel_id" as the
'
1036 'input URL (replacing `channel_id` with its actual value
)', expected=True)
1038 return self.playlist_result(self._entries(sec_uid, user_name), sec_uid, user_name)
1041 class TikTokBaseListIE(TikTokBaseIE): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
1042 def _entries(self, list_id, display_id):
1044 self._QUERY_NAME: list_id,
1048 'device_id
': self._DEVICE_ID,
1051 for page in itertools.count(1):
1052 for retry in self.RetryManager():
1054 post_list = self._call_api(
1055 self._API_ENDPOINT, display_id, query=query,
1056 note=f'Downloading video
list page {page}
',
1057 errnote='Unable to download video
list')
1058 except ExtractorError as e:
1059 if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0:
1063 for video in post_list.get('aweme_list
', []):
1065 **self._parse_aweme_video_app(video),
1066 'extractor_key
': TikTokIE.ie_key(),
1067 'extractor
': 'TikTok
',
1068 'webpage_url
': f'https
://tiktok
.com
/@_/video
/{video
["aweme_id"]}',
1070 if not post_list.get('has_more
'):
1072 query['cursor
'] = post_list['cursor
']
1074 def _real_extract(self, url):
1075 list_id = self._match_id(url)
1076 return self.playlist_result(self._entries(list_id, list_id), list_id)
1079 class TikTokSoundIE(TikTokBaseListIE):
1080 IE_NAME = 'tiktok
:sound
'
1081 _VALID_URL = r'https?
://(?
:www\
.)?tiktok\
.com
/music
/[\w\
.-]+-(?P
<id>[\d
]+)[/?
#&]?'
1083 _QUERY_NAME
= 'music_id'
1084 _API_ENDPOINT
= 'music/aweme'
1086 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
1087 'playlist_mincount': 100,
1089 'id': '6956990112127585029',
1091 'expected_warnings': ['Retrying'],
1093 # Actual entries are less than listed video count
1094 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
1095 'playlist_mincount': 2182,
1097 'id': '7036843036118469381',
1099 'expected_warnings': ['Retrying'],
1103 class TikTokEffectIE(TikTokBaseListIE
):
1104 IE_NAME
= 'tiktok:effect'
1105 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
1107 _QUERY_NAME
= 'sticker_id'
1108 _API_ENDPOINT
= 'sticker/aweme'
1110 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
1111 'playlist_mincount': 100,
1115 'expected_warnings': ['Retrying'],
1117 # Different entries between mobile and web, depending on region
1118 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
1119 'only_matching': True,
1123 class TikTokTagIE(TikTokBaseListIE
):
1124 IE_NAME
= 'tiktok:tag'
1125 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
1127 _QUERY_NAME
= 'ch_id'
1128 _API_ENDPOINT
= 'challenge/aweme'
1130 'url': 'https://tiktok.com/tag/hello2018',
1131 'playlist_mincount': 39,
1134 'title': 'hello2018',
1136 'expected_warnings': ['Retrying'],
1138 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
1139 'only_matching': True,
1142 def _real_extract(self
, url
):
1143 display_id
= self
._match
_id
(url
)
1144 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
1145 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)',
1147 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
1148 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
1151 class TikTokCollectionIE(TikTokBaseIE
):
1152 IE_NAME
= 'tiktok:collection'
1153 _VALID_URL
= r
'https?://www\.tiktok\.com/@(?P<user_id>[\w.-]+)/collection/(?P<title>[^/?#]+)-(?P<id>\d+)/?(?:[?#]|$)'
1155 # playlist should have exactly 9 videos
1156 'url': 'https://www.tiktok.com/@imanoreotwe/collection/count-test-7371330159376370462',
1158 'id': '7371330159376370462',
1159 'title': 'imanoreotwe-count-test',
1161 'playlist_count': 9,
1163 # tests returning multiple pages of a large collection
1164 'url': 'https://www.tiktok.com/@imanoreotwe/collection/%F0%9F%98%82-7111887189571160875',
1166 'id': '7111887189571160875',
1167 'title': 'imanoreotwe-%F0%9F%98%82',
1169 'playlist_mincount': 100,
1171 _API_BASE_URL
= 'https://www.tiktok.com/api/collection/item_list/'
1174 def _build_web_query(self
, collection_id
, cursor
):
1177 'collectionId': collection_id
,
1178 'count': self
._PAGE
_COUNT
,
1180 'sourceType': '113',
1183 def _entries(self
, collection_id
):
1185 for page
in itertools
.count(1):
1186 response
= self
._download
_json
(
1187 self
._API
_BASE
_URL
, collection_id
, f
'Downloading page {page}',
1188 query
=self
._build
_web
_query
(collection_id
, cursor
))
1190 for video
in traverse_obj(response
, ('itemList', lambda _
, v
: v
['id'])):
1191 video_id
= video
['id']
1192 author
= traverse_obj(video
, ('author', ('uniqueId', 'secUid', 'id'), {str}
, any
)) or '_'
1193 webpage_url
= self
._create
_url
(author
, video_id
)
1194 yield self
.url_result(
1195 webpage_url
, TikTokIE
,
1196 **self
._parse
_aweme
_video
_web
(video
, webpage_url
, video_id
, extract_flat
=True))
1198 if not traverse_obj(response
, 'hasMore'):
1200 cursor
+= self
._PAGE
_COUNT
1202 def _real_extract(self
, url
):
1203 collection_id
, title
, user_name
= self
._match
_valid
_url
(url
).group('id', 'title', 'user_id')
1205 return self
.playlist_result(
1206 self
._entries
(collection_id
), collection_id
, '-'.join((user_name
, title
)))
1209 class DouyinIE(TikTokBaseIE
):
1210 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
1212 'url': 'https://www.douyin.com/video/6961737553342991651',
1213 'md5': '9ecce7bc5b302601018ecb2871c63a75',
1215 'id': '6961737553342991651',
1217 'title': '#杨超越 小小水手带你去远航❤️',
1218 'description': '#杨超越 小小水手带你去远航❤️',
1219 'uploader': '6897520xka',
1220 'uploader_id': '110403406559',
1221 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1222 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1225 'timestamp': 1620905839,
1226 'upload_date': '20210513',
1227 'track': '@杨超越创作的原声',
1231 'repost_count': int,
1232 'comment_count': int,
1233 'thumbnail': r
're:https?://.+\.jpe?g',
1236 'url': 'https://www.douyin.com/video/6982497745948921092',
1237 'md5': '15c5e660b7048af3707304e3cc02bbb5',
1239 'id': '6982497745948921092',
1241 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1242 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1243 'uploader': '0731chaoyue',
1244 'uploader_id': '408654318141572',
1245 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1246 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1247 'channel': '杨超越工作室',
1249 'timestamp': 1625739481,
1250 'upload_date': '20210708',
1251 'track': '@杨超越工作室创作的原声',
1252 'artists': ['杨超越工作室'],
1255 'repost_count': int,
1256 'comment_count': int,
1257 'thumbnail': r
're:https?://.+\.jpe?g',
1260 'url': 'https://www.douyin.com/video/6953975910773099811',
1261 'md5': '0e6443758b8355db9a3c34864a4276be',
1263 'id': '6953975910773099811',
1265 'title': '#一起看海 出现在你的夏日里',
1266 'description': '#一起看海 出现在你的夏日里',
1267 'uploader': '6897520xka',
1268 'uploader_id': '110403406559',
1269 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1270 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1273 'timestamp': 1619098692,
1274 'upload_date': '20210422',
1275 'track': '@杨超越创作的原声',
1279 'repost_count': int,
1280 'comment_count': int,
1281 'thumbnail': r
're:https?://.+\.jpe?g',
1284 'url': 'https://www.douyin.com/video/6950251282489675042',
1285 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1287 'id': '6950251282489675042',
1289 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1291 'upload_date': '20210412',
1292 'timestamp': 1618231483,
1293 'uploader_id': '110403406559',
1296 'repost_count': int,
1297 'comment_count': int,
1299 'skip': 'No longer available',
1301 'url': 'https://www.douyin.com/video/6963263655114722595',
1302 'md5': '1440bcf59d8700f8e014da073a4dfea8',
1304 'id': '6963263655114722595',
1306 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1307 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1308 'uploader': '6897520xka',
1309 'uploader_id': '110403406559',
1310 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1311 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1314 'timestamp': 1621261163,
1315 'upload_date': '20210517',
1316 'track': '@杨超越创作的原声',
1320 'repost_count': int,
1321 'comment_count': int,
1322 'thumbnail': r
're:https?://.+\.jpe?g',
1325 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
1326 _WEBPAGE_HOST
= 'https://www.douyin.com/'
1328 def _real_extract(self
, url
):
1329 video_id
= self
._match
_id
(url
)
1331 detail
= traverse_obj(self
._download
_json
(
1332 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id
,
1333 'Downloading web detail JSON', 'Failed to download web detail JSON',
1334 query
={'aweme_id': video_id
}, fatal
=False), ('aweme_detail', {dict}
))
1336 # TODO: Run verification challenge code to generate signature cookies
1337 raise ExtractorError(
1338 'Fresh cookies (not necessarily logged in) are needed',
1339 expected
=not self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('s_v_web_id'))
1341 return self
._parse
_aweme
_video
_app
(detail
)
1344 class TikTokVMIE(InfoExtractor
):
1345 _VALID_URL
= r
'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
1346 IE_NAME
= 'vm.tiktok'
1349 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
1351 'id': '7170520270497680683',
1353 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1354 'uploader_id': '6687535061741700102',
1355 'upload_date': '20221127',
1358 'comment_count': int,
1359 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1360 'album': 'Wave of Mutilation: Best of Pixies',
1361 'thumbnail': r
're:https://.+\.webp.*',
1363 'timestamp': 1669516858,
1364 'repost_count': int,
1366 'track': 'Where Is My Mind?',
1367 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1368 'uploader': 'sigmachaddeus',
1369 'creator': 'SigmaChad',
1372 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1374 'id': '7106798200794926362',
1376 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1377 'uploader_id': '6997695878846268418',
1378 'upload_date': '20220608',
1381 'comment_count': int,
1382 'thumbnail': r
're:https://.+\.webp.*',
1383 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1385 'timestamp': 1654680400,
1386 'repost_count': int,
1387 'artist': 'Akihitoko',
1388 'track': 'original sound',
1389 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1390 'uploader': 'akihitoko1',
1391 'creator': 'Akihitoko',
1394 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1395 'only_matching': True,
1398 def _real_extract(self
, url
):
1399 new_url
= self
._request
_webpage
(
1400 HEADRequest(url
), self
._match
_id
(url
), headers
={'User-Agent': 'facebookexternalhit/1.1'}).url
1401 if self
.suitable(new_url
): # Prevent infinite loop in case redirect fails
1402 raise UnsupportedError(new_url
)
1403 return self
.url_result(new_url
)
1406 class TikTokLiveIE(TikTokBaseIE
):
1407 _VALID_URL
= r
'''(?x)https?://(?:
1408 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1409 m\.tiktok\.com/share/live/(?P<id>\d+)
1411 IE_NAME
= 'tiktok:live'
1414 'url': 'https://www.tiktok.com/@weathernewslive/live',
1416 'id': '7210809319192726273',
1418 'title': r
're:ウェザーニュースLiVE[\d\s:-]*',
1419 'creator': 'ウェザーニュースLiVE',
1420 'uploader': 'weathernewslive',
1421 'uploader_id': '6621496731283095554',
1422 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1423 'live_status': 'is_live',
1424 'concurrent_view_count': int,
1426 'params': {'skip_download': 'm3u8'},
1428 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1430 'id': '7209423610325322522',
1433 'creator': 'Pilarmagenta',
1434 'uploader': 'pilarmagenta',
1435 'uploader_id': '6624846890674683909',
1436 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1437 'live_status': 'is_live',
1438 'concurrent_view_count': int,
1440 'skip': 'Livestream',
1442 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1443 'only_matching': True,
1445 'url': 'https://www.tiktok.com/@iris04201/live',
1446 'only_matching': True,
1449 def _call_api(self
, url
, param
, room_id
, uploader
, key
=None):
1450 response
= traverse_obj(self
._download
_json
(
1451 url
, room_id
, fatal
=False, query
={
1454 }), (key
, {dict}
), default
={})
1456 # status == 2 if live else 4
1457 if int_or_none(response
.get('status')) == 2:
1459 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1461 raise ExtractorError('This livestream has ended', expected
=True)
1462 raise UserNotLive(video_id
=uploader
)
1464 def _real_extract(self
, url
):
1465 uploader
, room_id
= self
._match
_valid
_url
(url
).group('uploader', 'id')
1466 webpage
= self
._download
_webpage
(
1467 url
, uploader
or room_id
, headers
={'User-Agent': 'Mozilla/5.0'}, fatal
=not room_id
)
1470 data
= self
._get
_sigi
_state
(webpage
, uploader
or room_id
)
1472 traverse_obj(data
, ((
1473 ('LiveRoom', 'liveRoomUserInfo', 'user'),
1474 ('UserModule', 'users', ...)), 'roomId', {str}
, any
))
1475 or self
._search
_regex
(r
'snssdk\d*://live\?room_id=(\d+)', webpage
, 'room ID', default
=room_id
))
1476 uploader
= uploader
or traverse_obj(
1477 data
, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1478 ('UserModule', 'users', ..., 'uniqueId'), get_all
=False, expected_type
=str)
1481 raise UserNotLive(video_id
=uploader
)
1484 live_info
= self
._call
_api
(
1485 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id
, uploader
, key
='data')
1487 get_quality
= qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1488 parse_inner
= lambda x
: self
._parse
_json
(x
, None)
1490 for quality
, stream
in traverse_obj(live_info
, (
1491 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1492 {parse_inner}
, 'data', {dict}
), default
={}).items():
1494 sdk_params
= traverse_obj(stream
, ('main', 'sdk_params', {parse_inner}
, {
1495 'vcodec': ('VCodec', {str}
),
1496 'tbr': ('vbitrate', {int_or_none(scale
=1000)}),
1497 'resolution': ('resolution', {lambda x
: re
.match(r
'(?i)\d+x\d+|\d+p', x
).group().lower()}),
1500 flv_url
= traverse_obj(stream
, ('main', 'flv', {url_or_none}
))
1505 'format_id': f
'flv-{quality}',
1506 'quality': get_quality(quality
),
1510 hls_url
= traverse_obj(stream
, ('main', 'hls', {url_or_none}
))
1515 'protocol': 'm3u8_native',
1516 'format_id': f
'hls-{quality}',
1517 'quality': get_quality(quality
),
1521 def get_vcodec(*keys
):
1522 return traverse_obj(live_info
, (
1523 'stream_url', *keys
, {parse_inner}
, 'VCodec', {str}
))
1525 for stream
in ('hls', 'rtmp'):
1526 stream_url
= traverse_obj(live_info
, ('stream_url', f
'{stream}_pull_url', {url_or_none}
))
1530 'ext': 'mp4' if stream
== 'hls' else 'flv',
1531 'protocol': 'm3u8_native' if stream
== 'hls' else 'https',
1532 'format_id': f
'{stream}-pull',
1533 'vcodec': get_vcodec(f
'{stream}_pull_url_params'),
1534 'quality': get_quality('ORIGION'),
1537 for f_id
, f_url
in traverse_obj(live_info
, ('stream_url', 'flv_pull_url', {dict}
), default
={}).items():
1538 if not url_or_none(f_url
):
1543 'format_id': f
'flv-{f_id}'.lower(),
1544 'vcodec': get_vcodec('flv_pull_url_params', f_id
),
1545 'quality': get_quality(f_id
),
1548 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1549 if not traverse_obj(formats
, lambda _
, v
: v
['ext'] == 'mp4'):
1550 live_info
= merge_dicts(live_info
, self
._call
_api
(
1551 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id
, uploader
, key
='LiveRoomInfo'))
1552 if url_or_none(live_info
.get('liveUrl')):
1554 'url': live_info
['liveUrl'],
1556 'protocol': 'm3u8_native',
1557 'format_id': 'hls-fallback',
1559 'quality': get_quality('origin'),
1562 uploader
= uploader
or traverse_obj(live_info
, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
1566 'uploader': uploader
,
1567 'uploader_url': format_field(uploader
, None, self
._UPLOADER
_URL
_FORMAT
) or None,
1570 '_format_sort_fields': ('quality', 'ext'),
1571 **traverse_obj(live_info
, {
1573 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}
),
1574 'creator': (('ownerInfo', 'owner'), 'nickname'),
1575 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}
),