8 from .common
import InfoExtractor
9 from ..compat
import compat_urllib_parse_urlparse
10 from ..networking
import HEADRequest
23 srt_subtitles_timecode
,
32 class TikTokBaseIE(InfoExtractor
):
33 _APP_VERSIONS
= [('26.1.3', '260103'), ('26.1.2', '260102'), ('26.1.1', '260101'), ('25.6.2', '250602')]
34 _WORKING_APP_VERSION
= None
37 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
38 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
39 QUALITIES
= ('360p', '540p', '720p', '1080p')
42 def _API_HOSTNAME(self
):
43 return self
._configuration
_arg
(
44 'api_hostname', ['api16-normal-c-useast1a.tiktokv.com'], ie_key
=TikTokIE
)[0]
47 def _create_url(user_id
, video_id
):
48 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
50 def _get_sigi_state(self
, webpage
, display_id
):
51 return self
._search
_json
(
52 r
'<script[^>]+\bid="(?:SIGI_STATE|sigi-persisted-data)"[^>]*>', webpage
,
53 'sigi state', display_id
, end_pattern
=r
'</script>', default
={})
55 def _get_universal_data(self
, webpage
, display_id
):
56 return traverse_obj(self
._search
_json
(
57 r
'<script[^>]+\bid="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>', webpage
,
58 'universal data', display_id
, end_pattern
=r
'</script>', default
={}),
59 ('__DEFAULT_SCOPE__', {dict}
)) or {}
61 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
62 note
='Downloading API JSON', errnote
='Unable to download API page'):
63 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choices('0123456789abcdef', k
=160)))
64 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
65 if webpage_cookies
.get('sid_tt'):
66 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
67 return self
._download
_json
(
68 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
69 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
70 'User-Agent': f
'com.ss.android.ugc.{self._APP_NAME}/{manifest_app_version} (Linux; U; Android 13; en_US; Pixel 7; Build/TD1A.220804.031; Cronet/58.0.2991.0)',
71 'Accept': 'application/json',
74 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
77 'version_name': app_version
,
78 'version_code': manifest_app_version
,
79 'build_number': app_version
,
80 'manifest_version_code': manifest_app_version
,
81 'update_version_code': manifest_app_version
,
82 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
83 'uuid': ''.join(random
.choices(string
.digits
, k
=16)),
84 '_rticket': int(time
.time() * 1000),
85 'ts': int(time
.time()),
86 'device_brand': 'Google',
87 'device_type': 'Pixel 7',
88 'device_platform': 'android',
89 'resolution': '1080*2400',
93 'carrier_region': 'US',
96 'app_name': self
._APP
_NAME
,
99 'timezone_name': 'America/New_York',
100 'timezone_offset': '-14400',
101 'channel': 'googleplay',
108 'cp': 'cbfhckdckkde1',
111 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
112 note
='Downloading API JSON', errnote
='Unable to download API page'):
113 if not self
._WORKING
_APP
_VERSION
:
114 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
115 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
116 if app_version
and manifest_app_version
:
117 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
118 self
.write_debug('Imported app version combo from extractor arguments')
119 elif app_version
or manifest_app_version
:
120 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
122 if self
._WORKING
_APP
_VERSION
:
123 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
124 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
125 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
127 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
128 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
130 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
131 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
133 except ExtractorError
as e
:
134 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
135 if count
== len(self
._APP
_VERSIONS
):
139 self
.report_warning(str(e
.cause
or e
.msg
))
141 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
145 def _extract_aweme_app(self
, aweme_id
):
146 feed_list
= self
._call
_api
(
147 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
148 errnote
='Unable to download video feed').get('aweme_list') or []
149 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
151 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
152 return self
._parse
_aweme
_video
_app
(aweme_detail
)
154 def _get_subtitles(self
, aweme_detail
, aweme_id
):
155 # TODO: Extract text positioning info
157 # aweme/detail endpoint subs
158 captions_info
= traverse_obj(
159 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
160 for caption
in captions_info
:
161 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
164 caption_json
= self
._download
_json
(
165 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
168 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
171 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
172 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
176 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
177 if not caption
.get('url'):
179 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
180 'ext': remove_start(caption
.get('caption_format'), 'web'),
181 'url': caption
['url'],
185 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', ...), expected_type
=dict):
186 if not caption
.get('Url'):
188 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
189 'ext': remove_start(caption
.get('Format'), 'web'),
190 'url': caption
['Url'],
194 def _parse_aweme_video_app(self
, aweme_detail
):
195 aweme_id
= aweme_detail
['aweme_id']
196 video_info
= aweme_detail
['video']
198 def parse_url_key(url_key
):
199 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
200 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
201 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
205 'format_id': format_id
,
206 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
207 'tbr': int_or_none(bitrate
, scale
=1000) or None,
208 'quality': qualities(self
.QUALITIES
)(res
),
211 known_resolutions
= {}
214 ext
= determine_ext(url
, default_ext
='m4a')
216 'format_note': 'Music track',
218 'acodec': 'aac' if ext
== 'm4a' else ext
,
222 } if ext
== 'mp3' or '-music-' in url
else {}
224 def extract_addr(addr
, add_meta
={}):
225 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
227 known_resolutions
.setdefault(res
, {}).setdefault('height', int_or_none(addr
.get('height')))
228 known_resolutions
[res
].setdefault('width', int_or_none(addr
.get('width')))
229 parsed_meta
.update(known_resolutions
.get(res
, {}))
230 add_meta
.setdefault('height', int_or_none(res
[:-1]))
233 'filesize': int_or_none(addr
.get('data_size')),
236 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
237 **add_meta
, **parsed_meta
,
238 'format_note': join_nonempty(
239 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' '),
241 } for url
in addr
.get('url_list') or []]
243 # Hack: Add direct video links first to prioritize them when removing duplicate formats
245 width
= int_or_none(video_info
.get('width'))
246 height
= int_or_none(video_info
.get('height'))
247 if video_info
.get('play_addr'):
248 formats
.extend(extract_addr(video_info
['play_addr'], {
249 'format_id': 'play_addr',
250 'format_note': 'Direct video',
251 'vcodec': 'h265' if traverse_obj(
252 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
256 if video_info
.get('download_addr'):
257 download_addr
= video_info
['download_addr']
258 dl_width
= int_or_none(download_addr
.get('width'))
259 formats
.extend(extract_addr(download_addr
, {
260 'format_id': 'download_addr',
261 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
263 'width': dl_width
or width
,
264 'height': try_call(lambda: int(dl_width
/ 0.5625)) or height
, # download_addr['height'] is wrong
265 'preference': -2 if video_info
.get('has_watermark') else -1,
267 if video_info
.get('play_addr_h264'):
268 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
269 'format_id': 'play_addr_h264',
270 'format_note': 'Direct video',
273 if video_info
.get('play_addr_bytevc1'):
274 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
275 'format_id': 'play_addr_bytevc1',
276 'format_note': 'Direct video',
280 for bitrate
in video_info
.get('bit_rate', []):
281 if bitrate
.get('play_addr'):
282 formats
.extend(extract_addr(bitrate
['play_addr'], {
283 'format_id': bitrate
.get('gear_name'),
284 'format_note': 'Playback video',
285 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
286 'vcodec': 'h265' if traverse_obj(
287 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
288 'fps': bitrate
.get('FPS'),
291 self
._remove
_duplicate
_formats
(formats
)
292 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
295 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
298 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
299 'origin_cover', 'dynamic_cover'):
300 for cover_url
in traverse_obj(video_info
, (cover_id
, 'url_list', ...)):
306 stats_info
= aweme_detail
.get('statistics') or {}
307 author_info
= aweme_detail
.get('author') or {}
308 music_info
= aweme_detail
.get('music') or {}
309 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
310 'sec_uid', 'id', 'uid', 'unique_id',
311 expected_type
=str_or_none
, get_all
=False))
312 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str)
314 contained_music_track
= traverse_obj(
315 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
316 contained_music_author
= traverse_obj(
317 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
319 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
320 if is_generic_og_trackname
:
321 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
323 music_track
, music_author
= music_info
.get('title'), traverse_obj(music_info
, ('author', {str}
))
327 **traverse_obj(aweme_detail
, {
328 'title': ('desc', {str}
),
329 'description': ('desc', {str}
),
330 'timestamp': ('create_time', {int_or_none}
),
332 **traverse_obj(stats_info
, {
333 'view_count': 'play_count',
334 'like_count': 'digg_count',
335 'repost_count': 'share_count',
336 'comment_count': 'comment_count',
337 }, expected_type
=int_or_none
),
338 **traverse_obj(author_info
, {
339 'uploader': ('unique_id', {str}
),
340 'uploader_id': ('uid', {str_or_none}
),
341 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
342 'channel': ('nickname', {str}
),
343 'channel_id': ('sec_uid', {str}
),
345 'uploader_url': user_url
,
346 'track': music_track
,
347 'album': str_or_none(music_info
.get('album')) or None,
348 'artists': re
.split(r
'(?:, | & )', music_author
) if music_author
else None,
350 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
351 'thumbnails': thumbnails
,
352 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
353 'availability': self
._availability
(
354 is_private
='Private' in labels
,
355 needs_subscription
='Friends only' in labels
,
356 is_unlisted
='Followers only' in labels
),
357 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
360 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
, video_id
):
361 video_info
= aweme_detail
['video']
362 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
363 music_info
= aweme_detail
.get('music') or {}
364 stats_info
= aweme_detail
.get('stats') or {}
365 channel_id
= traverse_obj(author_info
or aweme_detail
, (('authorSecId', 'secUid'), {str}
), get_all
=False)
366 user_url
= self
._UPLOADER
_URL
_FORMAT
% channel_id
if channel_id
else None
369 width
= int_or_none(video_info
.get('width'))
370 height
= int_or_none(video_info
.get('height'))
372 for play_url
in traverse_obj(video_info
, ('playAddr', ((..., 'src'), None), {url_or_none}
)):
374 'url': self
._proto
_relative
_url
(play_url
),
380 for download_url
in traverse_obj(video_info
, (('downloadAddr', ('download', 'url')), {url_or_none}
)):
382 'format_id': 'download',
383 'url': self
._proto
_relative
_url
(download_url
),
389 self
._remove
_duplicate
_formats
(formats
)
392 for thumb_url
in traverse_obj(aweme_detail
, (
393 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none}
)):
395 'url': self
._proto
_relative
_url
(thumb_url
),
402 **traverse_obj(aweme_detail
, {
403 'title': ('desc', {str}
),
404 'description': ('desc', {str}
),
405 'duration': ('video', 'duration', {int_or_none}
),
406 'timestamp': ('createTime', {int_or_none}
),
408 **traverse_obj(author_info
or aweme_detail
, {
409 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
410 'channel': ('nickname', {str}
),
411 'uploader': (('uniqueId', 'author'), {str}
),
412 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}
),
414 **traverse_obj(stats_info
, {
415 'view_count': 'playCount',
416 'like_count': 'diggCount',
417 'repost_count': 'shareCount',
418 'comment_count': 'commentCount',
419 }, expected_type
=int_or_none
),
420 **traverse_obj(music_info
, {
421 'track': ('title', {str}
),
422 'album': ('album', {str}
, {lambda x: x or None}
),
423 'artists': ('authorName', {str}
, {lambda x: [x] if x else None}
),
425 'channel_id': channel_id
,
426 'uploader_url': user_url
,
428 'thumbnails': thumbnails
,
430 'Referer': webpage_url
,
435 class TikTokIE(TikTokBaseIE
):
436 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
437 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
440 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
441 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
443 'id': '6748451240264420610',
445 'title': '#jassmanak #lehanga #leenabhushan',
446 'description': '#jassmanak #lehanga #leenabhushan',
450 'uploader': 'leenabhushan',
451 'uploader_id': '6691488002098119685',
452 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
453 'creator': 'facestoriesbyleenabh',
454 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
455 'upload_date': '20191016',
456 'timestamp': 1571246252,
460 'comment_count': int,
461 'artist': 'Ysrbeats',
465 'skip': '404 Not Found',
467 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
468 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
470 'id': '6742501081818877190',
472 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
473 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
477 'uploader': 'patrox',
478 'uploader_id': '18702747',
479 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
480 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
482 'creators': ['patroX'],
483 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
484 'upload_date': '20190930',
485 'timestamp': 1569860870,
489 'comment_count': int,
490 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'],
494 # Banned audio, only available on the app
495 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
497 'id': '6984138651336838402',
499 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
500 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
501 'uploader': 'barudakhb_',
502 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
503 'creators': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
504 'uploader_id': '6974687867511718913',
505 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
506 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
507 'track': 'Boka Dance',
508 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
509 'timestamp': 1626121503,
511 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
512 'upload_date': '20210712',
516 'comment_count': int,
519 # Sponsored video, only available with feed workaround
520 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
522 'id': '7042692929109986561',
524 'title': 'Slap and Run!',
525 'description': 'Slap and Run!',
526 'uploader': 'user440922249',
527 'channel': 'Slap And Run',
528 'creators': ['Slap And Run'],
529 'uploader_id': '7036055384943690754',
530 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
531 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
532 'track': 'Promoted Music',
533 'timestamp': 1639754738,
535 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
536 'upload_date': '20211217',
540 'comment_count': int,
542 'params': {'skip_download': True}
, # XXX: unable to download video data: HTTP Error 403: Forbidden
544 # Video without title and description
545 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
547 'id': '7059698374567611694',
549 'title': 'TikTok video #7059698374567611694',
551 'uploader': 'pokemonlife22',
552 'channel': 'Pokemon',
553 'creators': ['Pokemon'],
554 'uploader_id': '6820838815978423302',
555 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
556 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
557 'track': 'original sound',
558 'timestamp': 1643714123,
560 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
561 'upload_date': '20220201',
562 'artists': ['Pokemon'],
566 'comment_count': int,
569 # hydration JSON is sent in a <script> element
570 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
572 'id': '7065799023130643713',
574 'title': '#denidil#денидил',
575 'description': '#denidil#денидил',
576 'uploader': 'denidil6',
577 'uploader_id': '7046664115636405250',
578 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
579 'artist': 'Holocron Music',
580 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
581 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
582 'timestamp': 1645134536,
584 'upload_date': '20220217',
588 'comment_count': int,
590 'skip': 'This video is unavailable',
592 # slideshow audio-only mp3 format
593 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
595 'id': '7139980461132074283',
597 'title': 'TikTok video #7139980461132074283',
599 'channel': 'Antaura',
600 'creators': ['Antaura'],
601 'uploader': '_le_cannibale_',
602 'uploader_id': '6604511138619654149',
603 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
604 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
605 'artists': ['nathan !'],
606 'track': 'grahamscott canon',
607 'upload_date': '20220905',
608 'timestamp': 1662406249,
612 'comment_count': int,
613 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
616 # only available via web
617 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662', # FIXME
618 'md5': '6aba7fad816e8709ff2c149679ace165',
620 'id': '7206382937372134662',
622 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
623 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
624 'channel': 'MoxyPatch',
625 'creators': ['MoxyPatch'],
626 'uploader': 'moxypatch',
627 'uploader_id': '7039142049363379205',
628 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
629 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
630 'artists': ['your worst nightmare'],
631 'track': 'original sound',
632 'upload_date': '20230303',
633 'timestamp': 1677866781,
638 'comment_count': int,
639 'thumbnail': r
're:^https://.+',
640 'thumbnails': 'count:3',
642 'expected_warnings': ['Unable to find video in feed'],
645 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME
646 'md5': '982512017a8a917124d5a08c8ae79621',
648 'id': '7107337212743830830',
650 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
651 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
652 'uploader': 'tatemcrae',
653 'uploader_id': '86328792343818240',
654 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
655 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
656 'channel': 'tate mcrae',
657 'creators': ['tate mcrae'],
658 'artists': ['tate mcrae'],
659 'track': 'original sound',
660 'upload_date': '20220609',
661 'timestamp': 1654805899,
666 'comment_count': int,
667 'thumbnail': r
're:^https://.+\.webp',
669 'skip': 'Unavailable via feed API, no formats available via web',
671 # Slideshow, audio-only m4a format
672 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
673 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
675 'id': '7253412088251534594',
677 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
678 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
679 'uploader': 'hara_yoimiya',
680 'uploader_id': '6582536342634676230',
681 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
682 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
683 'channel': 'лампочка',
684 'creators': ['лампочка'],
685 'artists': ['Øneheart'],
686 'album': 'watching the stars',
687 'track': 'watching the stars',
688 'upload_date': '20230708',
689 'timestamp': 1688816612,
692 'comment_count': int,
694 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
697 # Auto-captions available
698 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
699 'only_matching': True
702 def _real_extract(self
, url
):
703 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
705 return self
._extract
_aweme
_app
(video_id
)
706 except ExtractorError
as e
:
708 self
.report_warning(f
'{e}; trying with webpage')
710 url
= self
._create
_url
(user_id
, video_id
)
711 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'Mozilla/5.0'}
)
713 if universal_data
:= self
._get
_universal
_data
(webpage
, video_id
):
714 self
.write_debug('Found universal data for rehydration')
715 status
= traverse_obj(universal_data
, ('webapp.video-detail', 'statusCode', {int}
)) or 0
716 video_data
= traverse_obj(universal_data
, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict}
))
718 elif sigi_data
:= self
._get
_sigi
_state
(webpage
, video_id
):
719 self
.write_debug('Found sigi state data')
720 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode', {int}
)) or 0
721 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
, {dict}
))
723 elif next_data
:= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}'):
724 self
.write_debug('Found next.js data')
725 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode', {int}
)) or 0
726 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict}
))
729 raise ExtractorError('Unable to extract webpage video data')
731 if video_data
and status
== 0:
732 return self
._parse
_aweme
_video
_web
(video_data
, url
, video_id
)
733 elif status
== 10216:
734 raise ExtractorError('This video is private', expected
=True)
735 raise ExtractorError(f
'Video not available, status code {status}', video_id
=video_id
)
738 class TikTokUserIE(TikTokBaseIE
):
739 IE_NAME
= 'tiktok:user'
740 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
743 'url': 'https://tiktok.com/@corgibobaa?lang=en',
744 'playlist_mincount': 45,
746 'id': '6935371178089399301',
747 'title': 'corgibobaa',
748 'thumbnail': r
're:https://.+_1080x1080\.webp'
750 'expected_warnings': ['Retrying']
752 'url': 'https://www.tiktok.com/@6820838815978423302',
753 'playlist_mincount': 5,
755 'id': '6820838815978423302',
756 'title': '6820838815978423302',
757 'thumbnail': r
're:https://.+_1080x1080\.webp'
759 'expected_warnings': ['Retrying']
761 'url': 'https://www.tiktok.com/@meme',
762 'playlist_mincount': 593,
764 'id': '79005827461758976',
766 'thumbnail': r
're:https://.+_1080x1080\.webp'
768 'expected_warnings': ['Retrying']
771 r
''' # TODO: Fix by adding _signature to api_url
772 def _entries(self, webpage, user_id, username):
773 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
774 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
775 if not verifyfp_cookie:
776 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
777 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='
779 for page in itertools.count():
780 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
781 for video in data_json.get('itemList', []):
782 video_id = video['id']
783 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
784 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
785 if not data_json.get('hasMore'):
787 cursor = data_json['cursor']
790 def _video_entries_api(self
, webpage
, user_id
, username
):
796 'retry_type': 'no_retry',
797 'device_id': ''.join(random
.choices(string
.digits
, k
=19)), # Some endpoints don't like randomized device_id, so it isn't directly set in _call_api.
800 for page
in itertools
.count(1):
801 for retry
in self
.RetryManager():
803 post_list
= self
._call
_api
(
804 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
805 errnote
='Unable to download user video list')
806 except ExtractorError
as e
:
807 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
811 yield from post_list
.get('aweme_list', [])
812 if not post_list
.get('has_more'):
814 query
['max_cursor'] = post_list
['max_cursor']
816 def _entries_api(self
, user_id
, videos
):
819 **self
._parse
_aweme
_video
_app
(video
),
820 'extractor_key': TikTokIE
.ie_key(),
821 'extractor': 'TikTok',
822 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
825 def _real_extract(self
, url
):
826 user_name
= self
._match
_id
(url
)
827 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
828 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
830 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
832 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
833 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
835 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
838 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
839 def _entries(self
, list_id
, display_id
):
841 self
._QUERY
_NAME
: list_id
,
845 'device_id': ''.join(random
.choices(string
.digits
, k
=19))
848 for page
in itertools
.count(1):
849 for retry
in self
.RetryManager():
851 post_list
= self
._call
_api
(
852 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
853 errnote
='Unable to download video list')
854 except ExtractorError
as e
:
855 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
859 for video
in post_list
.get('aweme_list', []):
861 **self
._parse
_aweme
_video
_app
(video
),
862 'extractor_key': TikTokIE
.ie_key(),
863 'extractor': 'TikTok',
864 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
866 if not post_list
.get('has_more'):
868 query
['cursor'] = post_list
['cursor']
870 def _real_extract(self
, url
):
871 list_id
= self
._match
_id
(url
)
872 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
875 class TikTokSoundIE(TikTokBaseListIE
):
876 IE_NAME
= 'tiktok:sound'
877 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
879 _QUERY_NAME
= 'music_id'
880 _API_ENDPOINT
= 'music/aweme'
882 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
883 'playlist_mincount': 100,
885 'id': '6956990112127585029'
887 'expected_warnings': ['Retrying']
889 # Actual entries are less than listed video count
890 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
891 'playlist_mincount': 2182,
893 'id': '7036843036118469381'
895 'expected_warnings': ['Retrying']
899 class TikTokEffectIE(TikTokBaseListIE
):
900 IE_NAME
= 'tiktok:effect'
901 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
903 _QUERY_NAME
= 'sticker_id'
904 _API_ENDPOINT
= 'sticker/aweme'
906 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
907 'playlist_mincount': 100,
911 'expected_warnings': ['Retrying']
913 # Different entries between mobile and web, depending on region
914 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
915 'only_matching': True
919 class TikTokTagIE(TikTokBaseListIE
):
920 IE_NAME
= 'tiktok:tag'
921 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
923 _QUERY_NAME
= 'ch_id'
924 _API_ENDPOINT
= 'challenge/aweme'
926 'url': 'https://tiktok.com/tag/hello2018',
927 'playlist_mincount': 39,
930 'title': 'hello2018',
932 'expected_warnings': ['Retrying']
934 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
935 'only_matching': True
938 def _real_extract(self
, url
):
939 display_id
= self
._match
_id
(url
)
940 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
941 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
943 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
944 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
947 class DouyinIE(TikTokBaseIE
):
948 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
950 'url': 'https://www.douyin.com/video/6961737553342991651',
951 'md5': '9ecce7bc5b302601018ecb2871c63a75',
953 'id': '6961737553342991651',
955 'title': '#杨超越 小小水手带你去远航❤️',
956 'description': '#杨超越 小小水手带你去远航❤️',
957 'uploader': '6897520xka',
958 'uploader_id': '110403406559',
959 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
960 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
964 'timestamp': 1620905839,
965 'upload_date': '20210513',
966 'track': '@杨超越创作的原声',
971 'comment_count': int,
972 'thumbnail': r
're:https?://.+\.jpe?g',
975 'url': 'https://www.douyin.com/video/6982497745948921092',
976 'md5': '15c5e660b7048af3707304e3cc02bbb5',
978 'id': '6982497745948921092',
980 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
981 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
982 'uploader': '0731chaoyue',
983 'uploader_id': '408654318141572',
984 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
985 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
987 'creators': ['杨超越工作室'],
989 'timestamp': 1625739481,
990 'upload_date': '20210708',
991 'track': '@杨超越工作室创作的原声',
992 'artists': ['杨超越工作室'],
996 'comment_count': int,
997 'thumbnail': r
're:https?://.+\.jpe?g',
1000 'url': 'https://www.douyin.com/video/6953975910773099811',
1001 'md5': '0e6443758b8355db9a3c34864a4276be',
1003 'id': '6953975910773099811',
1005 'title': '#一起看海 出现在你的夏日里',
1006 'description': '#一起看海 出现在你的夏日里',
1007 'uploader': '6897520xka',
1008 'uploader_id': '110403406559',
1009 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1010 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1012 'creators': ['杨超越'],
1014 'timestamp': 1619098692,
1015 'upload_date': '20210422',
1016 'track': '@杨超越创作的原声',
1020 'repost_count': int,
1021 'comment_count': int,
1022 'thumbnail': r
're:https?://.+\.jpe?g',
1025 'url': 'https://www.douyin.com/video/6950251282489675042',
1026 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1028 'id': '6950251282489675042',
1030 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1032 'upload_date': '20210412',
1033 'timestamp': 1618231483,
1034 'uploader_id': '110403406559',
1037 'repost_count': int,
1038 'comment_count': int,
1040 'skip': 'No longer available',
1042 'url': 'https://www.douyin.com/video/6963263655114722595',
1043 'md5': '1440bcf59d8700f8e014da073a4dfea8',
1045 'id': '6963263655114722595',
1047 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1048 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1049 'uploader': '6897520xka',
1050 'uploader_id': '110403406559',
1051 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1052 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1054 'creators': ['杨超越'],
1056 'timestamp': 1621261163,
1057 'upload_date': '20210517',
1058 'track': '@杨超越创作的原声',
1062 'repost_count': int,
1063 'comment_count': int,
1064 'thumbnail': r
're:https?://.+\.jpe?g',
1067 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
1068 _WEBPAGE_HOST
= 'https://www.douyin.com/'
1070 def _real_extract(self
, url
):
1071 video_id
= self
._match
_id
(url
)
1073 detail
= traverse_obj(self
._download
_json
(
1074 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id
,
1075 'Downloading web detail JSON', 'Failed to download web detail JSON',
1076 query
={'aweme_id': video_id}
, fatal
=False), ('aweme_detail', {dict}
))
1078 # TODO: Run verification challenge code to generate signature cookies
1079 raise ExtractorError(
1080 'Fresh cookies (not necessarily logged in) are needed',
1081 expected
=not self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('s_v_web_id'))
1083 return self
._parse
_aweme
_video
_app
(detail
)
1086 class TikTokVMIE(InfoExtractor
):
1087 _VALID_URL
= r
'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
1088 IE_NAME
= 'vm.tiktok'
1091 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
1093 'id': '7170520270497680683',
1095 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1096 'uploader_id': '6687535061741700102',
1097 'upload_date': '20221127',
1100 'comment_count': int,
1101 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1102 'album': 'Wave of Mutilation: Best of Pixies',
1103 'thumbnail': r
're:https://.+\.webp.*',
1105 'timestamp': 1669516858,
1106 'repost_count': int,
1108 'track': 'Where Is My Mind?',
1109 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1110 'uploader': 'sigmachaddeus',
1111 'creator': 'SigmaChad',
1114 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1116 'id': '7106798200794926362',
1118 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1119 'uploader_id': '6997695878846268418',
1120 'upload_date': '20220608',
1123 'comment_count': int,
1124 'thumbnail': r
're:https://.+\.webp.*',
1125 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1127 'timestamp': 1654680400,
1128 'repost_count': int,
1129 'artist': 'Akihitoko',
1130 'track': 'original sound',
1131 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1132 'uploader': 'akihitoko1',
1133 'creator': 'Akihitoko',
1136 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1137 'only_matching': True,
1140 def _real_extract(self
, url
):
1141 new_url
= self
._request
_webpage
(
1142 HEADRequest(url
), self
._match
_id
(url
), headers
={'User-Agent': 'facebookexternalhit/1.1'}
).url
1143 if self
.suitable(new_url
): # Prevent infinite loop in case redirect fails
1144 raise UnsupportedError(new_url
)
1145 return self
.url_result(new_url
)
1148 class TikTokLiveIE(TikTokBaseIE
):
1149 _VALID_URL
= r
'''(?x)https?://(?:
1150 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1151 m\.tiktok\.com/share/live/(?P<id>\d+)
1153 IE_NAME
= 'tiktok:live'
1156 'url': 'https://www.tiktok.com/@weathernewslive/live',
1158 'id': '7210809319192726273',
1160 'title': r
're:ウェザーニュースLiVE[\d\s:-]*',
1161 'creator': 'ウェザーニュースLiVE',
1162 'uploader': 'weathernewslive',
1163 'uploader_id': '6621496731283095554',
1164 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1165 'live_status': 'is_live',
1166 'concurrent_view_count': int,
1168 'params': {'skip_download': 'm3u8'}
,
1170 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1172 'id': '7209423610325322522',
1175 'creator': 'Pilarmagenta',
1176 'uploader': 'pilarmagenta',
1177 'uploader_id': '6624846890674683909',
1178 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1179 'live_status': 'is_live',
1180 'concurrent_view_count': int,
1182 'skip': 'Livestream',
1184 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1185 'only_matching': True,
1187 'url': 'https://www.tiktok.com/@iris04201/live',
1188 'only_matching': True,
1191 def _call_api(self
, url
, param
, room_id
, uploader
, key
=None):
1192 response
= traverse_obj(self
._download
_json
(
1193 url
, room_id
, fatal
=False, query
={
1196 }), (key
, {dict}
), default
={})
1198 # status == 2 if live else 4
1199 if int_or_none(response
.get('status')) == 2:
1201 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1203 raise ExtractorError('This livestream has ended', expected
=True)
1204 raise UserNotLive(video_id
=uploader
)
1206 def _real_extract(self
, url
):
1207 uploader
, room_id
= self
._match
_valid
_url
(url
).group('uploader', 'id')
1208 webpage
= self
._download
_webpage
(
1209 url
, uploader
or room_id
, headers
={'User-Agent': 'Mozilla/5.0'}
, fatal
=not room_id
)
1212 data
= self
._get
_sigi
_state
(webpage
, uploader
or room_id
)
1213 room_id
= (traverse_obj(data
, ('UserModule', 'users', ..., 'roomId', {str_or_none}
), get_all
=False)
1214 or self
._search
_regex
(r
'snssdk\d*://live\?room_id=(\d+)', webpage
, 'room ID', default
=None)
1216 uploader
= uploader
or traverse_obj(
1217 data
, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1218 ('UserModule', 'users', ..., 'uniqueId'), get_all
=False, expected_type
=str)
1221 raise UserNotLive(video_id
=uploader
)
1224 live_info
= self
._call
_api
(
1225 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id
, uploader
, key
='data')
1227 get_quality
= qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1228 parse_inner
= lambda x
: self
._parse
_json
(x
, None)
1230 for quality
, stream
in traverse_obj(live_info
, (
1231 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1232 {parse_inner}
, 'data', {dict}
), default
={}).items():
1234 sdk_params
= traverse_obj(stream
, ('main', 'sdk_params', {parse_inner}
, {
1235 'vcodec': ('VCodec', {str}
),
1236 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}
),
1237 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}
),
1240 flv_url
= traverse_obj(stream
, ('main', 'flv', {url_or_none}
))
1245 'format_id': f
'flv-{quality}',
1246 'quality': get_quality(quality
),
1250 hls_url
= traverse_obj(stream
, ('main', 'hls', {url_or_none}
))
1255 'protocol': 'm3u8_native',
1256 'format_id': f
'hls-{quality}',
1257 'quality': get_quality(quality
),
1261 def get_vcodec(*keys
):
1262 return traverse_obj(live_info
, (
1263 'stream_url', *keys
, {parse_inner}
, 'VCodec', {str}
))
1265 for stream
in ('hls', 'rtmp'):
1266 stream_url
= traverse_obj(live_info
, ('stream_url', f
'{stream}_pull_url', {url_or_none}
))
1270 'ext': 'mp4' if stream
== 'hls' else 'flv',
1271 'protocol': 'm3u8_native' if stream
== 'hls' else 'https',
1272 'format_id': f
'{stream}-pull',
1273 'vcodec': get_vcodec(f
'{stream}_pull_url_params'),
1274 'quality': get_quality('ORIGION'),
1277 for f_id
, f_url
in traverse_obj(live_info
, ('stream_url', 'flv_pull_url', {dict}
), default
={}).items():
1278 if not url_or_none(f_url
):
1283 'format_id': f
'flv-{f_id}'.lower(),
1284 'vcodec': get_vcodec('flv_pull_url_params', f_id
),
1285 'quality': get_quality(f_id
),
1288 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1289 if not traverse_obj(formats
, lambda _
, v
: v
['ext'] == 'mp4'):
1290 live_info
= merge_dicts(live_info
, self
._call
_api
(
1291 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id
, uploader
, key
='LiveRoomInfo'))
1292 if url_or_none(live_info
.get('liveUrl')):
1294 'url': live_info
['liveUrl'],
1296 'protocol': 'm3u8_native',
1297 'format_id': 'hls-fallback',
1299 'quality': get_quality('origin'),
1302 uploader
= uploader
or traverse_obj(live_info
, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
1306 'uploader': uploader
,
1307 'uploader_url': format_field(uploader
, None, self
._UPLOADER
_URL
_FORMAT
) or None,
1310 '_format_sort_fields': ('quality', 'ext'),
1311 **traverse_obj(live_info
, {
1313 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}
),
1314 'creator': (('ownerInfo', 'owner'), 'nickname'),
1315 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}
),