9 from .common
import InfoExtractor
10 from ..compat
import compat_urllib_parse_urlparse
11 from ..networking
import HEADRequest
27 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': '34.1.2',
47 'manifest_app_version': '2023401020',
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
, query
, video_id
, 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 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
125 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
126 'User-Agent': self
._APP
_USER
_AGENT
,
127 'Accept': 'application/json',
130 def _build_api_query(self
, query
):
133 'device_platform': 'android',
136 '_rticket': int(time
.time() * 1000),
137 'cdid': str(uuid
.uuid4()),
138 'channel': 'googleplay',
139 'aid': self
._APP
_INFO
['aid'],
140 'app_name': self
._APP
_INFO
['app_name'],
141 'version_code': ''.join((f
'{int(v):02d}' for v
in self
._APP
_INFO
['app_version'].split('.'))),
142 'version_name': self
._APP
_INFO
['app_version'],
143 'manifest_version_code': self
._APP
_INFO
['manifest_app_version'],
144 'update_version_code': self
._APP
_INFO
['manifest_app_version'],
145 'ab_version': self
._APP
_INFO
['app_version'],
146 'resolution': '1080*2400',
148 'device_type': 'Pixel 7',
149 'device_brand': 'Google',
155 'current_region': 'US',
156 'app_type': 'normal',
158 'last_install_time': int(time
.time()) - random
.randint(86400, 1123200),
159 'timezone_name': 'America/New_York',
161 'app_language': 'en',
162 'timezone_offset': '-14400',
163 'host_abi': 'armeabi-v7a',
167 'carrier_region': 'US',
169 'build_number': self
._APP
_INFO
['app_version'],
171 'ts': int(time
.time()),
172 'iid': self
._APP
_INFO
.get('iid'),
173 'device_id': self
._DEVICE
_ID
,
174 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
177 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
178 note
='Downloading API JSON', errnote
='Unable to download API page'):
179 if not self
._APP
_INFO
and not self
._get
_next
_app
_info
():
180 message
= 'No working app info is available'
182 raise ExtractorError(message
, expected
=True)
184 self
.report_warning(message
)
187 max_tries
= len(self
._APP
_INFO
_POOL
) + 1 # _APP_INFO_POOL + _APP_INFO
188 for count
in itertools
.count(1):
189 self
.write_debug(str(self
._APP
_INFO
))
190 real_query
= self
._build
_api
_query
(query
)
192 return self
._call
_api
_impl
(ep
, real_query
, video_id
, fatal
, note
, errnote
)
193 except ExtractorError
as e
:
194 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
195 message
= str(e
.cause
or e
.msg
)
196 if not self
._get
_next
_app
_info
():
200 self
.report_warning(message
)
202 self
.report_warning(f
'{message}. Retrying... (attempt {count} of {max_tries})')
206 def _extract_aweme_app(self
, aweme_id
):
207 feed_list
= self
._call
_api
(
208 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
209 errnote
='Unable to download video feed').get('aweme_list') or []
210 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
212 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
213 return self
._parse
_aweme
_video
_app
(aweme_detail
)
215 def _extract_web_data_and_status(self
, url
, video_id
, fatal
=True):
216 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'Mozilla/5.0'}
, fatal
=fatal
) or ''
217 video_data
, status
= {}, None
219 if universal_data
:= self
._get
_universal
_data
(webpage
, video_id
):
220 self
.write_debug('Found universal data for rehydration')
221 status
= traverse_obj(universal_data
, ('webapp.video-detail', 'statusCode', {int}
)) or 0
222 video_data
= traverse_obj(universal_data
, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict}
))
224 elif sigi_data
:= self
._get
_sigi
_state
(webpage
, video_id
):
225 self
.write_debug('Found sigi state data')
226 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode', {int}
)) or 0
227 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
, {dict}
))
229 elif next_data
:= self
._search
_nextjs
_data
(webpage
, video_id
, default
={}):
230 self
.write_debug('Found next.js data')
231 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode', {int}
)) or 0
232 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict}
))
235 raise ExtractorError('Unable to extract webpage video data')
237 return video_data
, status
239 def _get_subtitles(self
, aweme_detail
, aweme_id
, user_url
):
240 # TODO: Extract text positioning info
242 # aweme/detail endpoint subs
243 captions_info
= traverse_obj(
244 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
245 for caption
in captions_info
:
246 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
249 caption_json
= self
._download
_json
(
250 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
253 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
256 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
257 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
261 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
262 if not caption
.get('url'):
264 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
265 'ext': remove_start(caption
.get('caption_format'), 'web'),
266 'url': caption
['url'],
270 if user_url
: # only _parse_aweme_video_app needs to extract the webpage here
271 aweme_detail
, _
= self
._extract
_web
_data
_and
_status
(
272 f
'{user_url}/video/{aweme_id}', aweme_id
, fatal
=False)
273 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', lambda _
, v
: v
['Url'])):
274 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
275 'ext': remove_start(caption
.get('Format'), 'web'),
276 'url': caption
['Url'],
280 def _parse_url_key(self
, url_key
):
281 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
282 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
283 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
287 'format_id': format_id
,
288 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
289 'tbr': int_or_none(bitrate
, scale
=1000) or None,
290 'quality': qualities(self
.QUALITIES
)(res
),
293 def _parse_aweme_video_app(self
, aweme_detail
):
294 aweme_id
= aweme_detail
['aweme_id']
295 video_info
= aweme_detail
['video']
296 known_resolutions
= {}
299 ext
= determine_ext(url
, default_ext
='m4a')
301 'format_note': 'Music track',
303 'acodec': 'aac' if ext
== 'm4a' else ext
,
307 } if ext
== 'mp3' or '-music-' in url
else {}
309 def extract_addr(addr
, add_meta
={}):
310 parsed_meta
, res
= self
._parse
_url
_key
(addr
.get('url_key', ''))
311 is_bytevc2
= parsed_meta
.get('vcodec') == 'bytevc2'
313 known_resolutions
.setdefault(res
, {}).setdefault('height', int_or_none(addr
.get('height')))
314 known_resolutions
[res
].setdefault('width', int_or_none(addr
.get('width')))
315 parsed_meta
.update(known_resolutions
.get(res
, {}))
316 add_meta
.setdefault('height', int_or_none(res
[:-1]))
319 'filesize': int_or_none(addr
.get('data_size')),
322 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
323 **add_meta
, **parsed_meta
,
324 # bytevc2 is bytedance's own custom h266/vvc codec, as-of-yet unplayable
325 'preference': -100 if is_bytevc2
else -1,
326 'format_note': join_nonempty(
327 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None,
328 '(UNPLAYABLE)' if is_bytevc2
else None, delim
=' '),
330 } for url
in addr
.get('url_list') or []]
332 # Hack: Add direct video links first to prioritize them when removing duplicate formats
334 width
= int_or_none(video_info
.get('width'))
335 height
= int_or_none(video_info
.get('height'))
336 ratio
= try_call(lambda: width
/ height
) or 0.5625
337 if video_info
.get('play_addr'):
338 formats
.extend(extract_addr(video_info
['play_addr'], {
339 'format_id': 'play_addr',
340 'format_note': 'Direct video',
341 'vcodec': 'h265' if traverse_obj(
342 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
346 if video_info
.get('download_addr'):
347 download_addr
= video_info
['download_addr']
348 dl_width
= int_or_none(download_addr
.get('width'))
349 formats
.extend(extract_addr(download_addr
, {
350 'format_id': 'download_addr',
351 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
354 'height': try_call(lambda: int(dl_width
/ ratio
)), # download_addr['height'] is wrong
355 'preference': -2 if video_info
.get('has_watermark') else -1,
357 if video_info
.get('play_addr_h264'):
358 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
359 'format_id': 'play_addr_h264',
360 'format_note': 'Direct video',
363 if video_info
.get('play_addr_bytevc1'):
364 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
365 'format_id': 'play_addr_bytevc1',
366 'format_note': 'Direct video',
370 for bitrate
in video_info
.get('bit_rate', []):
371 if bitrate
.get('play_addr'):
372 formats
.extend(extract_addr(bitrate
['play_addr'], {
373 'format_id': bitrate
.get('gear_name'),
374 'format_note': 'Playback video',
375 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
376 'vcodec': 'h265' if traverse_obj(
377 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
378 'fps': bitrate
.get('FPS'),
381 self
._remove
_duplicate
_formats
(formats
)
382 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
385 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
388 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
389 'origin_cover', 'dynamic_cover'):
390 for cover_url
in traverse_obj(video_info
, (cover_id
, 'url_list', ...)):
396 stats_info
= aweme_detail
.get('statistics') or {}
397 author_info
= aweme_detail
.get('author') or {}
398 music_info
= aweme_detail
.get('music') or {}
399 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
400 'sec_uid', 'id', 'uid', 'unique_id',
401 expected_type
=str_or_none
, get_all
=False))
402 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str)
404 contained_music_track
= traverse_obj(
405 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
406 contained_music_author
= traverse_obj(
407 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
409 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
410 if is_generic_og_trackname
:
411 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
413 music_track
, music_author
= music_info
.get('title'), traverse_obj(music_info
, ('author', {str}
))
417 **traverse_obj(aweme_detail
, {
418 'title': ('desc', {str}
),
419 'description': ('desc', {str}
),
420 'timestamp': ('create_time', {int_or_none}
),
422 **traverse_obj(stats_info
, {
423 'view_count': 'play_count',
424 'like_count': 'digg_count',
425 'repost_count': 'share_count',
426 'comment_count': 'comment_count',
427 }, expected_type
=int_or_none
),
428 **traverse_obj(author_info
, {
429 'uploader': ('unique_id', {str}
),
430 'uploader_id': ('uid', {str_or_none}
),
431 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
432 'channel': ('nickname', {str}
),
433 'channel_id': ('sec_uid', {str}
),
435 'uploader_url': user_url
,
436 'track': music_track
,
437 'album': str_or_none(music_info
.get('album')) or None,
438 'artists': re
.split(r
'(?:, | & )', music_author
) if music_author
else None,
440 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
, user_url
),
441 'thumbnails': thumbnails
,
442 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
443 'availability': self
._availability
(
444 is_private
='Private' in labels
,
445 needs_subscription
='Friends only' in labels
,
446 is_unlisted
='Followers only' in labels
),
447 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
450 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
, video_id
):
451 video_info
= aweme_detail
['video']
452 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
453 music_info
= aweme_detail
.get('music') or {}
454 stats_info
= aweme_detail
.get('stats') or {}
455 channel_id
= traverse_obj(author_info
or aweme_detail
, (('authorSecId', 'secUid'), {str}
), get_all
=False)
456 user_url
= self
._UPLOADER
_URL
_FORMAT
% channel_id
if channel_id
else None
459 width
= int_or_none(video_info
.get('width'))
460 height
= int_or_none(video_info
.get('height'))
461 ratio
= try_call(lambda: width
/ height
) or 0.5625
462 COMMON_FORMAT_INFO
= {
468 for bitrate_info
in traverse_obj(video_info
, ('bitrateInfo', lambda _
, v
: v
['PlayAddr']['UrlList'])):
469 format_info
, res
= self
._parse
_url
_key
(
470 traverse_obj(bitrate_info
, ('PlayAddr', 'UrlKey', {str}
)) or '')
471 # bytevc2 is bytedance's own custom h266/vvc codec, as-of-yet unplayable
472 is_bytevc2
= format_info
.get('vcodec') == 'bytevc2'
474 'format_note': 'UNPLAYABLE' if is_bytevc2
else None,
475 'preference': -100 if is_bytevc2
else -1,
476 'filesize': traverse_obj(bitrate_info
, ('PlayAddr', 'DataSize', {int_or_none}
)),
479 if dimension
:= (res
and int(res
[:-1])):
480 if dimension
== 540: # '540p' is actually 576p
482 if ratio
< 1: # portrait: res/dimension is width
483 y
= int(dimension
/ ratio
)
486 'height': y
- (y
% 2),
488 else: # landscape: res/dimension is height
489 x
= int(dimension
* ratio
)
491 'width': x
- (x
% 2),
495 for video_url
in traverse_obj(bitrate_info
, ('PlayAddr', 'UrlList', ..., {url_or_none}
)):
497 **COMMON_FORMAT_INFO
,
499 'url': self
._proto
_relative
_url
(video_url
),
502 # We don't have res string for play formats, but need quality for sorting & de-duplication
503 play_quality
= traverse_obj(formats
, (lambda _
, v
: v
['width'] == width
, 'quality', any
))
505 for play_url
in traverse_obj(video_info
, ('playAddr', ((..., 'src'), None), {url_or_none}
)):
507 **COMMON_FORMAT_INFO
,
509 'url': self
._proto
_relative
_url
(play_url
),
512 'quality': play_quality
,
515 for download_url
in traverse_obj(video_info
, (('downloadAddr', ('download', 'url')), {url_or_none}
)):
517 **COMMON_FORMAT_INFO
,
518 'format_id': 'download',
519 'url': self
._proto
_relative
_url
(download_url
),
522 self
._remove
_duplicate
_formats
(formats
)
524 for f
in traverse_obj(formats
, lambda _
, v
: 'unwatermarked' not in v
['url']):
526 'format_note': join_nonempty(f
.get('format_note'), 'watermarked', delim
=', '),
527 'preference': f
.get('preference') or -2,
530 # Is it a slideshow with only audio for download?
531 if not formats
and traverse_obj(music_info
, ('playUrl', {url_or_none}
)):
532 audio_url
= music_info
['playUrl']
533 ext
= traverse_obj(parse_qs(audio_url
), (
534 'mime_type', -1, {lambda x: x.replace('_', '/')}
, {mimetype2ext}
)) or 'm4a'
536 'format_id': 'audio',
537 'url': self
._proto
_relative
_url
(audio_url
),
539 'acodec': 'aac' if ext
== 'm4a' else ext
,
544 for thumb_url
in traverse_obj(aweme_detail
, (
545 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none}
)):
547 'url': self
._proto
_relative
_url
(thumb_url
),
554 **traverse_obj(music_info
, {
555 'track': ('title', {str}
),
556 'album': ('album', {str}
, {lambda x: x or None}
),
557 'artists': ('authorName', {str}
, {lambda x: [x] if x else None}
),
558 'duration': ('duration', {int_or_none}
),
560 **traverse_obj(aweme_detail
, {
561 'title': ('desc', {str}
),
562 'description': ('desc', {str}
),
563 # audio-only slideshows have a video duration of 0 and an actual audio duration
564 'duration': ('video', 'duration', {int_or_none}
, {lambda x: x or None}
),
565 'timestamp': ('createTime', {int_or_none}
),
567 **traverse_obj(author_info
or aweme_detail
, {
568 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
569 'channel': ('nickname', {str}
),
570 'uploader': (('uniqueId', 'author'), {str}
),
571 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}
),
573 **traverse_obj(stats_info
, {
574 'view_count': 'playCount',
575 'like_count': 'diggCount',
576 'repost_count': 'shareCount',
577 'comment_count': 'commentCount',
578 }, expected_type
=int_or_none
),
579 'channel_id': channel_id
,
580 'uploader_url': user_url
,
582 'subtitles': self
.extract_subtitles(aweme_detail
, video_id
, None),
583 'thumbnails': thumbnails
,
585 'Referer': webpage_url
,
590 class TikTokIE(TikTokBaseIE
):
591 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
592 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
595 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
596 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
598 'id': '6748451240264420610',
600 'title': '#jassmanak #lehanga #leenabhushan',
601 'description': '#jassmanak #lehanga #leenabhushan',
605 'uploader': 'leenabhushan',
606 'uploader_id': '6691488002098119685',
607 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
608 'creator': 'facestoriesbyleenabh',
609 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
610 'upload_date': '20191016',
611 'timestamp': 1571246252,
615 'comment_count': int,
616 'artist': 'Ysrbeats',
620 'skip': '404 Not Found',
622 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
623 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
625 'id': '6742501081818877190',
627 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
628 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
632 'uploader': 'patrox',
633 'uploader_id': '18702747',
634 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
635 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
637 'creators': ['patroX'],
638 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
639 'upload_date': '20190930',
640 'timestamp': 1569860870,
644 'comment_count': int,
645 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'],
649 # Banned audio, only available on the app
650 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
652 'id': '6984138651336838402',
654 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
655 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
656 'uploader': 'barudakhb_',
657 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
658 'creators': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
659 'uploader_id': '6974687867511718913',
660 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
661 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
662 'track': 'Boka Dance',
663 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
664 'timestamp': 1626121503,
666 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
667 'upload_date': '20210712',
671 'comment_count': int,
674 # Sponsored video, only available with feed workaround
675 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
677 'id': '7042692929109986561',
679 'title': 'Slap and Run!',
680 'description': 'Slap and Run!',
681 'uploader': 'user440922249',
682 'channel': 'Slap And Run',
683 'creators': ['Slap And Run'],
684 'uploader_id': '7036055384943690754',
685 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
686 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
687 'track': 'Promoted Music',
688 'timestamp': 1639754738,
690 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
691 'upload_date': '20211217',
695 'comment_count': int,
697 'params': {'skip_download': True}
, # XXX: unable to download video data: HTTP Error 403: Forbidden
699 # Video without title and description
700 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
702 'id': '7059698374567611694',
704 'title': 'TikTok video #7059698374567611694',
706 'uploader': 'pokemonlife22',
707 'channel': 'Pokemon',
708 'creators': ['Pokemon'],
709 'uploader_id': '6820838815978423302',
710 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
711 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
712 'track': 'original sound',
713 'timestamp': 1643714123,
715 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
716 'upload_date': '20220201',
717 'artists': ['Pokemon'],
721 'comment_count': int,
724 # hydration JSON is sent in a <script> element
725 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
727 'id': '7065799023130643713',
729 'title': '#denidil#денидил',
730 'description': '#denidil#денидил',
731 'uploader': 'denidil6',
732 'uploader_id': '7046664115636405250',
733 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
734 'artist': 'Holocron Music',
735 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
736 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
737 'timestamp': 1645134536,
739 'upload_date': '20220217',
743 'comment_count': int,
745 'skip': 'This video is unavailable',
747 # slideshow audio-only mp3 format
748 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
750 'id': '7139980461132074283',
752 'title': 'TikTok video #7139980461132074283',
754 'channel': 'Antaura',
755 'creators': ['Antaura'],
756 'uploader': '_le_cannibale_',
757 'uploader_id': '6604511138619654149',
758 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
759 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
760 'artists': ['nathan !'],
761 'track': 'grahamscott canon',
762 'upload_date': '20220905',
763 'timestamp': 1662406249,
767 'comment_count': int,
768 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
771 # only available via web
772 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662', # FIXME
773 'md5': '6aba7fad816e8709ff2c149679ace165',
775 'id': '7206382937372134662',
777 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
778 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
779 'channel': 'MoxyPatch',
780 'creators': ['MoxyPatch'],
781 'uploader': 'moxypatch',
782 'uploader_id': '7039142049363379205',
783 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
784 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
785 'artists': ['your worst nightmare'],
786 'track': 'original sound',
787 'upload_date': '20230303',
788 'timestamp': 1677866781,
793 'comment_count': int,
794 'thumbnail': r
're:^https://.+',
795 'thumbnails': 'count:3',
797 'expected_warnings': ['Unable to find video in feed'],
800 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME
801 'md5': '982512017a8a917124d5a08c8ae79621',
803 'id': '7107337212743830830',
805 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
806 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
807 'uploader': 'tatemcrae',
808 'uploader_id': '86328792343818240',
809 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
810 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
811 'channel': 'tate mcrae',
812 'creators': ['tate mcrae'],
813 'artists': ['tate mcrae'],
814 'track': 'original sound',
815 'upload_date': '20220609',
816 'timestamp': 1654805899,
821 'comment_count': int,
822 'thumbnail': r
're:^https://.+\.webp',
824 'skip': 'Unavailable via feed API, no formats available via web',
826 # Slideshow, audio-only m4a format
827 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
828 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
830 'id': '7253412088251534594',
832 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
833 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
834 'uploader': 'hara_yoimiya',
835 'uploader_id': '6582536342634676230',
836 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
837 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
838 'channel': 'лампочка',
839 'creators': ['лампочка'],
840 'artists': ['Øneheart'],
841 'album': 'watching the stars',
842 'track': 'watching the stars',
843 'upload_date': '20230708',
844 'timestamp': 1688816612,
847 'comment_count': int,
849 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
852 # Auto-captions available
853 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
854 'only_matching': True
857 def _real_extract(self
, url
):
858 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
860 if self
._KNOWN
_APP
_INFO
:
862 return self
._extract
_aweme
_app
(video_id
)
863 except ExtractorError
as e
:
865 self
.report_warning(f
'{e}; trying with webpage')
867 url
= self
._create
_url
(user_id
, video_id
)
868 video_data
, status
= self
._extract
_web
_data
_and
_status
(url
, video_id
)
870 if video_data
and status
== 0:
871 return self
._parse
_aweme
_video
_web
(video_data
, url
, video_id
)
872 elif status
== 10216:
873 raise ExtractorError('This video is private', expected
=True)
874 raise ExtractorError(f
'Video not available, status code {status}', video_id
=video_id
)
877 class TikTokUserIE(TikTokBaseIE
):
878 IE_NAME
= 'tiktok:user'
879 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
882 'url': 'https://tiktok.com/@corgibobaa?lang=en',
883 'playlist_mincount': 45,
885 'id': '6935371178089399301',
886 'title': 'corgibobaa',
887 'thumbnail': r
're:https://.+_1080x1080\.webp'
889 'expected_warnings': ['Retrying']
891 'url': 'https://www.tiktok.com/@6820838815978423302',
892 'playlist_mincount': 5,
894 'id': '6820838815978423302',
895 'title': '6820838815978423302',
896 'thumbnail': r
're:https://.+_1080x1080\.webp'
898 'expected_warnings': ['Retrying']
900 'url': 'https://www.tiktok.com/@meme',
901 'playlist_mincount': 593,
903 'id': '79005827461758976',
905 'thumbnail': r
're:https://.+_1080x1080\.webp'
907 'expected_warnings': ['Retrying']
910 r
''' # TODO: Fix by adding _signature to api_url
911 def _entries(self, webpage, user_id, username):
912 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
913 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
914 if not verifyfp_cookie:
915 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
916 api_url = f'https://m.tiktok.com/api/post/item_list/?aid=1988&cookie_enabled=true&count=30&verifyFp={verifyfp_cookie.value}&secUid={secuid}&cursor='
918 for page in itertools.count():
919 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
920 for video in data_json.get('itemList', []):
921 video_id = video['id']
922 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
923 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
924 if not data_json.get('hasMore'):
926 cursor = data_json['cursor']
929 def _video_entries_api(self
, webpage
, user_id
, username
):
935 'retry_type': 'no_retry',
936 'device_id': self
._DEVICE
_ID
, # Some endpoints don't like randomized device_id, so it isn't directly set in _call_api.
939 for page
in itertools
.count(1):
940 for retry
in self
.RetryManager():
942 post_list
= self
._call
_api
(
943 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
944 errnote
='Unable to download user video list')
945 except ExtractorError
as e
:
946 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
950 yield from post_list
.get('aweme_list', [])
951 if not post_list
.get('has_more'):
953 query
['max_cursor'] = post_list
['max_cursor']
955 def _entries_api(self
, user_id
, videos
):
958 **self
._parse
_aweme
_video
_app
(video
),
959 'extractor_key': TikTokIE
.ie_key(),
960 'extractor': 'TikTok',
961 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
964 def _real_extract(self
, url
):
965 user_name
= self
._match
_id
(url
)
966 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
967 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
969 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
971 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
972 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
974 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
977 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
978 def _entries(self
, list_id
, display_id
):
980 self
._QUERY
_NAME
: list_id
,
984 'device_id': self
._DEVICE
_ID
,
987 for page
in itertools
.count(1):
988 for retry
in self
.RetryManager():
990 post_list
= self
._call
_api
(
991 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
992 errnote
='Unable to download video list')
993 except ExtractorError
as e
:
994 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
998 for video
in post_list
.get('aweme_list', []):
1000 **self
._parse
_aweme
_video
_app
(video
),
1001 'extractor_key': TikTokIE
.ie_key(),
1002 'extractor': 'TikTok',
1003 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
1005 if not post_list
.get('has_more'):
1007 query
['cursor'] = post_list
['cursor']
1009 def _real_extract(self
, url
):
1010 list_id
= self
._match
_id
(url
)
1011 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
1014 class TikTokSoundIE(TikTokBaseListIE
):
1015 IE_NAME
= 'tiktok:sound'
1016 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
1018 _QUERY_NAME
= 'music_id'
1019 _API_ENDPOINT
= 'music/aweme'
1021 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
1022 'playlist_mincount': 100,
1024 'id': '6956990112127585029'
1026 'expected_warnings': ['Retrying']
1028 # Actual entries are less than listed video count
1029 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
1030 'playlist_mincount': 2182,
1032 'id': '7036843036118469381'
1034 'expected_warnings': ['Retrying']
1038 class TikTokEffectIE(TikTokBaseListIE
):
1039 IE_NAME
= 'tiktok:effect'
1040 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
1042 _QUERY_NAME
= 'sticker_id'
1043 _API_ENDPOINT
= 'sticker/aweme'
1045 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
1046 'playlist_mincount': 100,
1050 'expected_warnings': ['Retrying']
1052 # Different entries between mobile and web, depending on region
1053 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
1054 'only_matching': True
1058 class TikTokTagIE(TikTokBaseListIE
):
1059 IE_NAME
= 'tiktok:tag'
1060 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
1062 _QUERY_NAME
= 'ch_id'
1063 _API_ENDPOINT
= 'challenge/aweme'
1065 'url': 'https://tiktok.com/tag/hello2018',
1066 'playlist_mincount': 39,
1069 'title': 'hello2018',
1071 'expected_warnings': ['Retrying']
1073 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
1074 'only_matching': True
1077 def _real_extract(self
, url
):
1078 display_id
= self
._match
_id
(url
)
1079 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
1080 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
1082 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
1083 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
1086 class DouyinIE(TikTokBaseIE
):
1087 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
1089 'url': 'https://www.douyin.com/video/6961737553342991651',
1090 'md5': '9ecce7bc5b302601018ecb2871c63a75',
1092 'id': '6961737553342991651',
1094 'title': '#杨超越 小小水手带你去远航❤️',
1095 'description': '#杨超越 小小水手带你去远航❤️',
1096 'uploader': '6897520xka',
1097 'uploader_id': '110403406559',
1098 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1099 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1101 'creators': ['杨超越'],
1103 'timestamp': 1620905839,
1104 'upload_date': '20210513',
1105 'track': '@杨超越创作的原声',
1109 'repost_count': int,
1110 'comment_count': int,
1111 'thumbnail': r
're:https?://.+\.jpe?g',
1114 'url': 'https://www.douyin.com/video/6982497745948921092',
1115 'md5': '15c5e660b7048af3707304e3cc02bbb5',
1117 'id': '6982497745948921092',
1119 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1120 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1121 'uploader': '0731chaoyue',
1122 'uploader_id': '408654318141572',
1123 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1124 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1125 'channel': '杨超越工作室',
1126 'creators': ['杨超越工作室'],
1128 'timestamp': 1625739481,
1129 'upload_date': '20210708',
1130 'track': '@杨超越工作室创作的原声',
1131 'artists': ['杨超越工作室'],
1134 'repost_count': int,
1135 'comment_count': int,
1136 'thumbnail': r
're:https?://.+\.jpe?g',
1139 'url': 'https://www.douyin.com/video/6953975910773099811',
1140 'md5': '0e6443758b8355db9a3c34864a4276be',
1142 'id': '6953975910773099811',
1144 'title': '#一起看海 出现在你的夏日里',
1145 'description': '#一起看海 出现在你的夏日里',
1146 'uploader': '6897520xka',
1147 'uploader_id': '110403406559',
1148 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1149 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1151 'creators': ['杨超越'],
1153 'timestamp': 1619098692,
1154 'upload_date': '20210422',
1155 'track': '@杨超越创作的原声',
1159 'repost_count': int,
1160 'comment_count': int,
1161 'thumbnail': r
're:https?://.+\.jpe?g',
1164 'url': 'https://www.douyin.com/video/6950251282489675042',
1165 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1167 'id': '6950251282489675042',
1169 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1171 'upload_date': '20210412',
1172 'timestamp': 1618231483,
1173 'uploader_id': '110403406559',
1176 'repost_count': int,
1177 'comment_count': int,
1179 'skip': 'No longer available',
1181 'url': 'https://www.douyin.com/video/6963263655114722595',
1182 'md5': '1440bcf59d8700f8e014da073a4dfea8',
1184 'id': '6963263655114722595',
1186 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1187 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1188 'uploader': '6897520xka',
1189 'uploader_id': '110403406559',
1190 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1191 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1193 'creators': ['杨超越'],
1195 'timestamp': 1621261163,
1196 'upload_date': '20210517',
1197 'track': '@杨超越创作的原声',
1201 'repost_count': int,
1202 'comment_count': int,
1203 'thumbnail': r
're:https?://.+\.jpe?g',
1206 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
1207 _WEBPAGE_HOST
= 'https://www.douyin.com/'
1209 def _real_extract(self
, url
):
1210 video_id
= self
._match
_id
(url
)
1212 detail
= traverse_obj(self
._download
_json
(
1213 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id
,
1214 'Downloading web detail JSON', 'Failed to download web detail JSON',
1215 query
={'aweme_id': video_id}
, fatal
=False), ('aweme_detail', {dict}
))
1217 # TODO: Run verification challenge code to generate signature cookies
1218 raise ExtractorError(
1219 'Fresh cookies (not necessarily logged in) are needed',
1220 expected
=not self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('s_v_web_id'))
1222 return self
._parse
_aweme
_video
_app
(detail
)
1225 class TikTokVMIE(InfoExtractor
):
1226 _VALID_URL
= r
'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
1227 IE_NAME
= 'vm.tiktok'
1230 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
1232 'id': '7170520270497680683',
1234 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1235 'uploader_id': '6687535061741700102',
1236 'upload_date': '20221127',
1239 'comment_count': int,
1240 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1241 'album': 'Wave of Mutilation: Best of Pixies',
1242 'thumbnail': r
're:https://.+\.webp.*',
1244 'timestamp': 1669516858,
1245 'repost_count': int,
1247 'track': 'Where Is My Mind?',
1248 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1249 'uploader': 'sigmachaddeus',
1250 'creator': 'SigmaChad',
1253 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1255 'id': '7106798200794926362',
1257 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1258 'uploader_id': '6997695878846268418',
1259 'upload_date': '20220608',
1262 'comment_count': int,
1263 'thumbnail': r
're:https://.+\.webp.*',
1264 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1266 'timestamp': 1654680400,
1267 'repost_count': int,
1268 'artist': 'Akihitoko',
1269 'track': 'original sound',
1270 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1271 'uploader': 'akihitoko1',
1272 'creator': 'Akihitoko',
1275 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1276 'only_matching': True,
1279 def _real_extract(self
, url
):
1280 new_url
= self
._request
_webpage
(
1281 HEADRequest(url
), self
._match
_id
(url
), headers
={'User-Agent': 'facebookexternalhit/1.1'}
).url
1282 if self
.suitable(new_url
): # Prevent infinite loop in case redirect fails
1283 raise UnsupportedError(new_url
)
1284 return self
.url_result(new_url
)
1287 class TikTokLiveIE(TikTokBaseIE
):
1288 _VALID_URL
= r
'''(?x)https?://(?:
1289 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1290 m\.tiktok\.com/share/live/(?P<id>\d+)
1292 IE_NAME
= 'tiktok:live'
1295 'url': 'https://www.tiktok.com/@weathernewslive/live',
1297 'id': '7210809319192726273',
1299 'title': r
're:ウェザーニュースLiVE[\d\s:-]*',
1300 'creator': 'ウェザーニュースLiVE',
1301 'uploader': 'weathernewslive',
1302 'uploader_id': '6621496731283095554',
1303 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1304 'live_status': 'is_live',
1305 'concurrent_view_count': int,
1307 'params': {'skip_download': 'm3u8'}
,
1309 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1311 'id': '7209423610325322522',
1314 'creator': 'Pilarmagenta',
1315 'uploader': 'pilarmagenta',
1316 'uploader_id': '6624846890674683909',
1317 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1318 'live_status': 'is_live',
1319 'concurrent_view_count': int,
1321 'skip': 'Livestream',
1323 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1324 'only_matching': True,
1326 'url': 'https://www.tiktok.com/@iris04201/live',
1327 'only_matching': True,
1330 def _call_api(self
, url
, param
, room_id
, uploader
, key
=None):
1331 response
= traverse_obj(self
._download
_json
(
1332 url
, room_id
, fatal
=False, query
={
1335 }), (key
, {dict}
), default
={})
1337 # status == 2 if live else 4
1338 if int_or_none(response
.get('status')) == 2:
1340 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1342 raise ExtractorError('This livestream has ended', expected
=True)
1343 raise UserNotLive(video_id
=uploader
)
1345 def _real_extract(self
, url
):
1346 uploader
, room_id
= self
._match
_valid
_url
(url
).group('uploader', 'id')
1347 webpage
= self
._download
_webpage
(
1348 url
, uploader
or room_id
, headers
={'User-Agent': 'Mozilla/5.0'}
, fatal
=not room_id
)
1351 data
= self
._get
_sigi
_state
(webpage
, uploader
or room_id
)
1352 room_id
= (traverse_obj(data
, ('UserModule', 'users', ..., 'roomId', {str_or_none}
), get_all
=False)
1353 or self
._search
_regex
(r
'snssdk\d*://live\?room_id=(\d+)', webpage
, 'room ID', default
=None)
1355 uploader
= uploader
or traverse_obj(
1356 data
, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1357 ('UserModule', 'users', ..., 'uniqueId'), get_all
=False, expected_type
=str)
1360 raise UserNotLive(video_id
=uploader
)
1363 live_info
= self
._call
_api
(
1364 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id
, uploader
, key
='data')
1366 get_quality
= qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1367 parse_inner
= lambda x
: self
._parse
_json
(x
, None)
1369 for quality
, stream
in traverse_obj(live_info
, (
1370 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1371 {parse_inner}
, 'data', {dict}
), default
={}).items():
1373 sdk_params
= traverse_obj(stream
, ('main', 'sdk_params', {parse_inner}
, {
1374 'vcodec': ('VCodec', {str}
),
1375 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}
),
1376 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}
),
1379 flv_url
= traverse_obj(stream
, ('main', 'flv', {url_or_none}
))
1384 'format_id': f
'flv-{quality}',
1385 'quality': get_quality(quality
),
1389 hls_url
= traverse_obj(stream
, ('main', 'hls', {url_or_none}
))
1394 'protocol': 'm3u8_native',
1395 'format_id': f
'hls-{quality}',
1396 'quality': get_quality(quality
),
1400 def get_vcodec(*keys
):
1401 return traverse_obj(live_info
, (
1402 'stream_url', *keys
, {parse_inner}
, 'VCodec', {str}
))
1404 for stream
in ('hls', 'rtmp'):
1405 stream_url
= traverse_obj(live_info
, ('stream_url', f
'{stream}_pull_url', {url_or_none}
))
1409 'ext': 'mp4' if stream
== 'hls' else 'flv',
1410 'protocol': 'm3u8_native' if stream
== 'hls' else 'https',
1411 'format_id': f
'{stream}-pull',
1412 'vcodec': get_vcodec(f
'{stream}_pull_url_params'),
1413 'quality': get_quality('ORIGION'),
1416 for f_id
, f_url
in traverse_obj(live_info
, ('stream_url', 'flv_pull_url', {dict}
), default
={}).items():
1417 if not url_or_none(f_url
):
1422 'format_id': f
'flv-{f_id}'.lower(),
1423 'vcodec': get_vcodec('flv_pull_url_params', f_id
),
1424 'quality': get_quality(f_id
),
1427 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1428 if not traverse_obj(formats
, lambda _
, v
: v
['ext'] == 'mp4'):
1429 live_info
= merge_dicts(live_info
, self
._call
_api
(
1430 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id
, uploader
, key
='LiveRoomInfo'))
1431 if url_or_none(live_info
.get('liveUrl')):
1433 'url': live_info
['liveUrl'],
1435 'protocol': 'm3u8_native',
1436 'format_id': 'hls-fallback',
1438 'quality': get_quality('origin'),
1441 uploader
= uploader
or traverse_obj(live_info
, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
1445 'uploader': uploader
,
1446 'uploader_url': format_field(uploader
, None, self
._UPLOADER
_URL
_FORMAT
) or None,
1449 '_format_sort_fields': ('quality', 'ext'),
1450 **traverse_obj(live_info
, {
1452 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}
),
1453 'creator': (('ownerInfo', 'owner'), 'nickname'),
1454 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}
),