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>')
55 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
56 note
='Downloading API JSON', errnote
='Unable to download API page'):
57 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choices('0123456789abcdef', k
=160)))
58 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
59 if webpage_cookies
.get('sid_tt'):
60 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
61 return self
._download
_json
(
62 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
63 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
64 '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)',
65 'Accept': 'application/json',
68 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
71 'version_name': app_version
,
72 'version_code': manifest_app_version
,
73 'build_number': app_version
,
74 'manifest_version_code': manifest_app_version
,
75 'update_version_code': manifest_app_version
,
76 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
77 'uuid': ''.join(random
.choices(string
.digits
, k
=16)),
78 '_rticket': int(time
.time() * 1000),
79 'ts': int(time
.time()),
80 'device_brand': 'Google',
81 'device_type': 'Pixel 7',
82 'device_platform': 'android',
83 'resolution': '1080*2400',
87 'carrier_region': 'US',
90 'app_name': self
._APP
_NAME
,
93 'timezone_name': 'America/New_York',
94 'timezone_offset': '-14400',
95 'channel': 'googleplay',
102 'cp': 'cbfhckdckkde1',
105 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
106 note
='Downloading API JSON', errnote
='Unable to download API page'):
107 if not self
._WORKING
_APP
_VERSION
:
108 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
109 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
110 if app_version
and manifest_app_version
:
111 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
112 self
.write_debug('Imported app version combo from extractor arguments')
113 elif app_version
or manifest_app_version
:
114 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
116 if self
._WORKING
_APP
_VERSION
:
117 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
118 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
119 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
121 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
122 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
124 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
125 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
127 except ExtractorError
as e
:
128 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
129 if count
== len(self
._APP
_VERSIONS
):
133 self
.report_warning(str(e
.cause
or e
.msg
))
135 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
139 def _extract_aweme_app(self
, aweme_id
):
140 feed_list
= self
._call
_api
(
141 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
142 errnote
='Unable to download video feed').get('aweme_list') or []
143 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
145 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
146 return self
._parse
_aweme
_video
_app
(aweme_detail
)
148 def _get_subtitles(self
, aweme_detail
, aweme_id
):
149 # TODO: Extract text positioning info
151 # aweme/detail endpoint subs
152 captions_info
= traverse_obj(
153 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
154 for caption
in captions_info
:
155 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
158 caption_json
= self
._download
_json
(
159 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
162 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
165 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
166 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
170 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
171 if not caption
.get('url'):
173 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
174 'ext': remove_start(caption
.get('caption_format'), 'web'),
175 'url': caption
['url'],
179 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', ...), expected_type
=dict):
180 if not caption
.get('Url'):
182 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
183 'ext': remove_start(caption
.get('Format'), 'web'),
184 'url': caption
['Url'],
188 def _parse_aweme_video_app(self
, aweme_detail
):
189 aweme_id
= aweme_detail
['aweme_id']
190 video_info
= aweme_detail
['video']
192 def parse_url_key(url_key
):
193 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
194 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
195 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
199 'format_id': format_id
,
200 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
201 'tbr': int_or_none(bitrate
, scale
=1000) or None,
202 'quality': qualities(self
.QUALITIES
)(res
),
205 known_resolutions
= {}
208 ext
= determine_ext(url
, default_ext
='m4a')
210 'format_note': 'Music track',
212 'acodec': 'aac' if ext
== 'm4a' else ext
,
216 } if ext
== 'mp3' or '-music-' in url
else {}
218 def extract_addr(addr
, add_meta
={}):
219 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
221 known_resolutions
.setdefault(res
, {}).setdefault('height', int_or_none(addr
.get('height')))
222 known_resolutions
[res
].setdefault('width', int_or_none(addr
.get('width')))
223 parsed_meta
.update(known_resolutions
.get(res
, {}))
224 add_meta
.setdefault('height', int_or_none(res
[:-1]))
227 'filesize': int_or_none(addr
.get('data_size')),
230 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
231 **add_meta
, **parsed_meta
,
232 'format_note': join_nonempty(
233 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' '),
235 } for url
in addr
.get('url_list') or []]
237 # Hack: Add direct video links first to prioritize them when removing duplicate formats
239 width
= int_or_none(video_info
.get('width'))
240 height
= int_or_none(video_info
.get('height'))
241 if video_info
.get('play_addr'):
242 formats
.extend(extract_addr(video_info
['play_addr'], {
243 'format_id': 'play_addr',
244 'format_note': 'Direct video',
245 'vcodec': 'h265' if traverse_obj(
246 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
250 if video_info
.get('download_addr'):
251 download_addr
= video_info
['download_addr']
252 dl_width
= int_or_none(download_addr
.get('width'))
253 formats
.extend(extract_addr(download_addr
, {
254 'format_id': 'download_addr',
255 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
257 'width': dl_width
or width
,
258 'height': try_call(lambda: int(dl_width
/ 0.5625)) or height
, # download_addr['height'] is wrong
259 'preference': -2 if video_info
.get('has_watermark') else -1,
261 if video_info
.get('play_addr_h264'):
262 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
263 'format_id': 'play_addr_h264',
264 'format_note': 'Direct video',
267 if video_info
.get('play_addr_bytevc1'):
268 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
269 'format_id': 'play_addr_bytevc1',
270 'format_note': 'Direct video',
274 for bitrate
in video_info
.get('bit_rate', []):
275 if bitrate
.get('play_addr'):
276 formats
.extend(extract_addr(bitrate
['play_addr'], {
277 'format_id': bitrate
.get('gear_name'),
278 'format_note': 'Playback video',
279 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
280 'vcodec': 'h265' if traverse_obj(
281 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
282 'fps': bitrate
.get('FPS'),
285 self
._remove
_duplicate
_formats
(formats
)
286 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
289 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
292 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
293 'origin_cover', 'dynamic_cover'):
294 for cover_url
in traverse_obj(video_info
, (cover_id
, 'url_list', ...)):
300 stats_info
= aweme_detail
.get('statistics') or {}
301 author_info
= aweme_detail
.get('author') or {}
302 music_info
= aweme_detail
.get('music') or {}
303 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
304 'sec_uid', 'id', 'uid', 'unique_id',
305 expected_type
=str_or_none
, get_all
=False))
306 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str)
308 contained_music_track
= traverse_obj(
309 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
310 contained_music_author
= traverse_obj(
311 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
313 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
314 if is_generic_og_trackname
:
315 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
317 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
321 **traverse_obj(aweme_detail
, {
322 'title': ('desc', {str}
),
323 'description': ('desc', {str}
),
324 'timestamp': ('create_time', {int_or_none}
),
326 **traverse_obj(stats_info
, {
327 'view_count': 'play_count',
328 'like_count': 'digg_count',
329 'repost_count': 'share_count',
330 'comment_count': 'comment_count',
331 }, expected_type
=int_or_none
),
332 **traverse_obj(author_info
, {
333 'uploader': 'unique_id',
334 'uploader_id': 'uid',
335 'creator': 'nickname',
336 'channel_id': 'sec_uid',
337 }, expected_type
=str_or_none
),
338 'uploader_url': user_url
,
339 'track': music_track
,
340 'album': str_or_none(music_info
.get('album')) or None,
341 'artist': music_author
or None,
343 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
344 'thumbnails': thumbnails
,
345 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
346 'availability': self
._availability
(
347 is_private
='Private' in labels
,
348 needs_subscription
='Friends only' in labels
,
349 is_unlisted
='Followers only' in labels
),
350 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
353 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
, video_id
):
354 video_info
= aweme_detail
['video']
355 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
356 music_info
= aweme_detail
.get('music') or {}
357 stats_info
= aweme_detail
.get('stats') or {}
358 channel_id
= traverse_obj(author_info
or aweme_detail
, (('authorSecId', 'secUid'), {str}
), get_all
=False)
359 user_url
= self
._UPLOADER
_URL
_FORMAT
% channel_id
if channel_id
else None
362 width
= int_or_none(video_info
.get('width'))
363 height
= int_or_none(video_info
.get('height'))
365 for play_url
in traverse_obj(video_info
, ('playAddr', ((..., 'src'), None), {url_or_none}
)):
367 'url': self
._proto
_relative
_url
(play_url
),
373 for download_url
in traverse_obj(video_info
, (('downloadAddr', ('download', 'url')), {url_or_none}
)):
375 'format_id': 'download',
376 'url': self
._proto
_relative
_url
(download_url
),
382 self
._remove
_duplicate
_formats
(formats
)
385 for thumb_url
in traverse_obj(aweme_detail
, (
386 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none}
)):
388 'url': self
._proto
_relative
_url
(thumb_url
),
395 **traverse_obj(aweme_detail
, {
396 'title': ('desc', {str}
),
397 'description': ('desc', {str}
),
398 'duration': ('video', 'duration', {int_or_none}
),
399 'timestamp': ('createTime', {int_or_none}
),
401 **traverse_obj(author_info
or aweme_detail
, {
402 'creator': ('nickname', {str}
),
403 'uploader': (('uniqueId', 'author'), {str}
),
404 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}
),
406 **traverse_obj(stats_info
, {
407 'view_count': 'playCount',
408 'like_count': 'diggCount',
409 'repost_count': 'shareCount',
410 'comment_count': 'commentCount',
411 }, expected_type
=int_or_none
),
412 **traverse_obj(music_info
, {
414 'album': ('album', {lambda x: x or None}
),
415 'artist': 'authorName',
416 }, expected_type
=str),
417 'channel_id': channel_id
,
418 'uploader_url': user_url
,
420 'thumbnails': thumbnails
,
422 'Referer': webpage_url
,
427 class TikTokIE(TikTokBaseIE
):
428 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
429 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
432 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
433 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
435 'id': '6748451240264420610',
437 'title': '#jassmanak #lehanga #leenabhushan',
438 'description': '#jassmanak #lehanga #leenabhushan',
442 'uploader': 'leenabhushan',
443 'uploader_id': '6691488002098119685',
444 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
445 'creator': 'facestoriesbyleenabh',
446 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
447 'upload_date': '20191016',
448 'timestamp': 1571246252,
452 'comment_count': int,
453 'artist': 'Ysrbeats',
457 'skip': '404 Not Found',
459 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
460 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
462 'id': '6742501081818877190',
464 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
465 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
469 'uploader': 'patrox',
470 'uploader_id': '18702747',
471 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
472 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
474 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
475 'upload_date': '20190930',
476 'timestamp': 1569860870,
480 'comment_count': int,
481 'artist': 'Evan Todd, Jessica Keenan Wynn, Alice Lee, Barrett Wilbert Weed & Jon Eidson',
485 # Banned audio, only available on the app
486 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
488 'id': '6984138651336838402',
490 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
491 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
492 'uploader': 'barudakhb_',
493 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
494 'uploader_id': '6974687867511718913',
495 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
496 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
497 'track': 'Boka Dance',
498 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
499 'timestamp': 1626121503,
501 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
502 'upload_date': '20210712',
506 'comment_count': int,
509 # Sponsored video, only available with feed workaround
510 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
512 'id': '7042692929109986561',
514 'title': 'Slap and Run!',
515 'description': 'Slap and Run!',
516 'uploader': 'user440922249',
517 'creator': 'Slap And Run',
518 'uploader_id': '7036055384943690754',
519 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
520 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
521 'track': 'Promoted Music',
522 'timestamp': 1639754738,
524 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
525 'upload_date': '20211217',
529 'comment_count': int,
531 'params': {'skip_download': True}
, # XXX: unable to download video data: HTTP Error 403: Forbidden
533 # Video without title and description
534 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
536 'id': '7059698374567611694',
538 'title': 'TikTok video #7059698374567611694',
540 'uploader': 'pokemonlife22',
541 'creator': 'Pokemon',
542 'uploader_id': '6820838815978423302',
543 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
544 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
545 'track': 'original sound',
546 'timestamp': 1643714123,
548 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
549 'upload_date': '20220201',
554 'comment_count': int,
557 # hydration JSON is sent in a <script> element
558 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
560 'id': '7065799023130643713',
562 'title': '#denidil#денидил',
563 'description': '#denidil#денидил',
564 'uploader': 'denidil6',
565 'uploader_id': '7046664115636405250',
566 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
567 'artist': 'Holocron Music',
568 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
569 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
570 'timestamp': 1645134536,
572 'upload_date': '20220217',
576 'comment_count': int,
578 'skip': 'This video is unavailable',
580 # slideshow audio-only mp3 format
581 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
583 'id': '7139980461132074283',
585 'title': 'TikTok video #7139980461132074283',
587 'creator': 'Antaura',
588 'uploader': '_le_cannibale_',
589 'uploader_id': '6604511138619654149',
590 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
591 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
592 'artist': 'nathan !',
593 'track': 'grahamscott canon',
594 'upload_date': '20220905',
595 'timestamp': 1662406249,
599 'comment_count': int,
600 'thumbnail': r
're:^https://.+\.webp',
603 # only available via web
604 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662',
605 'md5': '6aba7fad816e8709ff2c149679ace165',
607 'id': '7206382937372134662',
609 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
610 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
611 'creator': 'MoxyPatch',
612 'uploader': 'moxypatch',
613 'uploader_id': '7039142049363379205',
614 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
615 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
616 'artist': 'your worst nightmare',
617 'track': 'original sound',
618 'upload_date': '20230303',
619 'timestamp': 1677866781,
624 'comment_count': int,
625 'thumbnail': r
're:^https://.+',
626 'thumbnails': 'count:3',
628 'expected_warnings': ['Unable to find video in feed'],
631 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830',
632 'md5': '982512017a8a917124d5a08c8ae79621',
634 'id': '7107337212743830830',
636 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
637 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
638 'uploader': 'tatemcrae',
639 'uploader_id': '86328792343818240',
640 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
641 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
642 'creator': 'tate mcrae',
643 'artist': 'tate mcrae',
644 'track': 'original sound',
645 'upload_date': '20220609',
646 'timestamp': 1654805899,
651 'comment_count': int,
652 'thumbnail': r
're:^https://.+\.webp',
654 'params': {'format': 'bytevc1_1080p_808907-0'}
,
656 # Slideshow, audio-only m4a format
657 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
658 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
660 'id': '7253412088251534594',
662 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
663 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
664 'uploader': 'hara_yoimiya',
665 'uploader_id': '6582536342634676230',
666 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
667 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
668 'creator': 'лампочка',
669 'artist': 'Øneheart',
670 'album': 'watching the stars',
671 'track': 'watching the stars',
672 'upload_date': '20230708',
673 'timestamp': 1688816612,
676 'comment_count': int,
678 'thumbnail': r
're:^https://.+\.webp',
681 # Auto-captions available
682 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
683 'only_matching': True
686 def _real_extract(self
, url
):
687 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
689 return self
._extract
_aweme
_app
(video_id
)
690 except ExtractorError
as e
:
691 self
.report_warning(f
'{e}; trying with webpage')
693 url
= self
._create
_url
(user_id
, video_id
)
694 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'Mozilla/5.0'}
)
695 next_data
= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}')
697 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode'), expected_type
=int) or 0
698 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type
=dict)
700 sigi_data
= self
._get
_sigi
_state
(webpage
, video_id
)
701 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode'), expected_type
=int) or 0
702 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
), expected_type
=dict)
705 return self
._parse
_aweme
_video
_web
(video_data
, url
, video_id
)
706 elif status
== 10216:
707 raise ExtractorError('This video is private', expected
=True)
708 raise ExtractorError('Video not available', video_id
=video_id
)
711 class TikTokUserIE(TikTokBaseIE
):
712 IE_NAME
= 'tiktok:user'
713 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
716 'url': 'https://tiktok.com/@corgibobaa?lang=en',
717 'playlist_mincount': 45,
719 'id': '6935371178089399301',
720 'title': 'corgibobaa',
721 'thumbnail': r
're:https://.+_1080x1080\.webp'
723 'expected_warnings': ['Retrying']
725 'url': 'https://www.tiktok.com/@6820838815978423302',
726 'playlist_mincount': 5,
728 'id': '6820838815978423302',
729 'title': '6820838815978423302',
730 'thumbnail': r
're:https://.+_1080x1080\.webp'
732 'expected_warnings': ['Retrying']
734 'url': 'https://www.tiktok.com/@meme',
735 'playlist_mincount': 593,
737 'id': '79005827461758976',
739 'thumbnail': r
're:https://.+_1080x1080\.webp'
741 'expected_warnings': ['Retrying']
744 r
''' # TODO: Fix by adding _signature to api_url
745 def _entries(self, webpage, user_id, username):
746 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
747 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
748 if not verifyfp_cookie:
749 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
750 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='
752 for page in itertools.count():
753 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
754 for video in data_json.get('itemList', []):
755 video_id = video['id']
756 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
757 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
758 if not data_json.get('hasMore'):
760 cursor = data_json['cursor']
763 def _video_entries_api(self
, webpage
, user_id
, username
):
769 'retry_type': 'no_retry',
770 '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.
773 for page
in itertools
.count(1):
774 for retry
in self
.RetryManager():
776 post_list
= self
._call
_api
(
777 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
778 errnote
='Unable to download user video list')
779 except ExtractorError
as e
:
780 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
784 yield from post_list
.get('aweme_list', [])
785 if not post_list
.get('has_more'):
787 query
['max_cursor'] = post_list
['max_cursor']
789 def _entries_api(self
, user_id
, videos
):
792 **self
._parse
_aweme
_video
_app
(video
),
793 'extractor_key': TikTokIE
.ie_key(),
794 'extractor': 'TikTok',
795 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
798 def _real_extract(self
, url
):
799 user_name
= self
._match
_id
(url
)
800 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
801 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
803 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
805 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
806 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
808 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
811 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
812 def _entries(self
, list_id
, display_id
):
814 self
._QUERY
_NAME
: list_id
,
818 'device_id': ''.join(random
.choices(string
.digits
, k
=19))
821 for page
in itertools
.count(1):
822 for retry
in self
.RetryManager():
824 post_list
= self
._call
_api
(
825 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
826 errnote
='Unable to download video list')
827 except ExtractorError
as e
:
828 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
832 for video
in post_list
.get('aweme_list', []):
834 **self
._parse
_aweme
_video
_app
(video
),
835 'extractor_key': TikTokIE
.ie_key(),
836 'extractor': 'TikTok',
837 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
839 if not post_list
.get('has_more'):
841 query
['cursor'] = post_list
['cursor']
843 def _real_extract(self
, url
):
844 list_id
= self
._match
_id
(url
)
845 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
848 class TikTokSoundIE(TikTokBaseListIE
):
849 IE_NAME
= 'tiktok:sound'
850 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
852 _QUERY_NAME
= 'music_id'
853 _API_ENDPOINT
= 'music/aweme'
855 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
856 'playlist_mincount': 100,
858 'id': '6956990112127585029'
860 'expected_warnings': ['Retrying']
862 # Actual entries are less than listed video count
863 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
864 'playlist_mincount': 2182,
866 'id': '7036843036118469381'
868 'expected_warnings': ['Retrying']
872 class TikTokEffectIE(TikTokBaseListIE
):
873 IE_NAME
= 'tiktok:effect'
874 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
876 _QUERY_NAME
= 'sticker_id'
877 _API_ENDPOINT
= 'sticker/aweme'
879 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
880 'playlist_mincount': 100,
884 'expected_warnings': ['Retrying']
886 # Different entries between mobile and web, depending on region
887 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
888 'only_matching': True
892 class TikTokTagIE(TikTokBaseListIE
):
893 IE_NAME
= 'tiktok:tag'
894 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
896 _QUERY_NAME
= 'ch_id'
897 _API_ENDPOINT
= 'challenge/aweme'
899 'url': 'https://tiktok.com/tag/hello2018',
900 'playlist_mincount': 39,
903 'title': 'hello2018',
905 'expected_warnings': ['Retrying']
907 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
908 'only_matching': True
911 def _real_extract(self
, url
):
912 display_id
= self
._match
_id
(url
)
913 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
914 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
916 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
917 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
920 class DouyinIE(TikTokBaseIE
):
921 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
923 'url': 'https://www.douyin.com/video/6961737553342991651',
924 'md5': '9ecce7bc5b302601018ecb2871c63a75',
926 'id': '6961737553342991651',
928 'title': '#杨超越 小小水手带你去远航❤️',
929 'description': '#杨超越 小小水手带你去远航❤️',
930 'uploader': '6897520xka',
931 'uploader_id': '110403406559',
932 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
933 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
937 'timestamp': 1620905839,
938 'upload_date': '20210513',
939 'track': '@杨超越创作的原声',
944 'comment_count': int,
945 'thumbnail': r
're:https?://.+\.jpe?g',
948 'url': 'https://www.douyin.com/video/6982497745948921092',
949 'md5': '15c5e660b7048af3707304e3cc02bbb5',
951 'id': '6982497745948921092',
953 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
954 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
955 'uploader': '0731chaoyue',
956 'uploader_id': '408654318141572',
957 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
958 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
960 'creators': ['杨超越工作室'],
962 'timestamp': 1625739481,
963 'upload_date': '20210708',
964 'track': '@杨超越工作室创作的原声',
965 'artists': ['杨超越工作室'],
969 'comment_count': int,
970 'thumbnail': r
're:https?://.+\.jpe?g',
973 'url': 'https://www.douyin.com/video/6953975910773099811',
974 'md5': '0e6443758b8355db9a3c34864a4276be',
976 'id': '6953975910773099811',
978 'title': '#一起看海 出现在你的夏日里',
979 'description': '#一起看海 出现在你的夏日里',
980 'uploader': '6897520xka',
981 'uploader_id': '110403406559',
982 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
983 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
987 'timestamp': 1619098692,
988 'upload_date': '20210422',
989 'track': '@杨超越创作的原声',
994 'comment_count': int,
995 'thumbnail': r
're:https?://.+\.jpe?g',
998 'url': 'https://www.douyin.com/video/6950251282489675042',
999 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1001 'id': '6950251282489675042',
1003 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1005 'upload_date': '20210412',
1006 'timestamp': 1618231483,
1007 'uploader_id': '110403406559',
1010 'repost_count': int,
1011 'comment_count': int,
1013 'skip': 'No longer available',
1015 'url': 'https://www.douyin.com/video/6963263655114722595',
1016 'md5': '1440bcf59d8700f8e014da073a4dfea8',
1018 'id': '6963263655114722595',
1020 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1021 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1022 'uploader': '6897520xka',
1023 'uploader_id': '110403406559',
1024 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1025 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1027 'creators': ['杨超越'],
1029 'timestamp': 1621261163,
1030 'upload_date': '20210517',
1031 'track': '@杨超越创作的原声',
1035 'repost_count': int,
1036 'comment_count': int,
1037 'thumbnail': r
're:https?://.+\.jpe?g',
1040 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
1041 _WEBPAGE_HOST
= 'https://www.douyin.com/'
1043 def _real_extract(self
, url
):
1044 video_id
= self
._match
_id
(url
)
1046 detail
= traverse_obj(self
._download
_json
(
1047 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id
,
1048 'Downloading web detail JSON', 'Failed to download web detail JSON',
1049 query
={'aweme_id': video_id}
, fatal
=False), ('aweme_detail', {dict}
))
1051 # TODO: Run verification challenge code to generate signature cookies
1052 raise ExtractorError(
1053 'Fresh cookies (not necessarily logged in) are needed',
1054 expected
=not self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('s_v_web_id'))
1056 return self
._parse
_aweme
_video
_app
(detail
)
1059 class TikTokVMIE(InfoExtractor
):
1060 _VALID_URL
= r
'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
1061 IE_NAME
= 'vm.tiktok'
1064 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
1066 'id': '7170520270497680683',
1068 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1069 'uploader_id': '6687535061741700102',
1070 'upload_date': '20221127',
1073 'comment_count': int,
1074 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1075 'album': 'Wave of Mutilation: Best of Pixies',
1076 'thumbnail': r
're:https://.+\.webp.*',
1078 'timestamp': 1669516858,
1079 'repost_count': int,
1081 'track': 'Where Is My Mind?',
1082 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1083 'uploader': 'sigmachaddeus',
1084 'creator': 'SigmaChad',
1087 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1089 'id': '7106798200794926362',
1091 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1092 'uploader_id': '6997695878846268418',
1093 'upload_date': '20220608',
1096 'comment_count': int,
1097 'thumbnail': r
're:https://.+\.webp.*',
1098 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1100 'timestamp': 1654680400,
1101 'repost_count': int,
1102 'artist': 'Akihitoko',
1103 'track': 'original sound',
1104 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1105 'uploader': 'akihitoko1',
1106 'creator': 'Akihitoko',
1109 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1110 'only_matching': True,
1113 def _real_extract(self
, url
):
1114 new_url
= self
._request
_webpage
(
1115 HEADRequest(url
), self
._match
_id
(url
), headers
={'User-Agent': 'facebookexternalhit/1.1'}
).url
1116 if self
.suitable(new_url
): # Prevent infinite loop in case redirect fails
1117 raise UnsupportedError(new_url
)
1118 return self
.url_result(new_url
)
1121 class TikTokLiveIE(TikTokBaseIE
):
1122 _VALID_URL
= r
'''(?x)https?://(?:
1123 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1124 m\.tiktok\.com/share/live/(?P<id>\d+)
1126 IE_NAME
= 'tiktok:live'
1129 'url': 'https://www.tiktok.com/@weathernewslive/live',
1131 'id': '7210809319192726273',
1133 'title': r
're:ウェザーニュースLiVE[\d\s:-]*',
1134 'creator': 'ウェザーニュースLiVE',
1135 'uploader': 'weathernewslive',
1136 'uploader_id': '6621496731283095554',
1137 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1138 'live_status': 'is_live',
1139 'concurrent_view_count': int,
1141 'params': {'skip_download': 'm3u8'}
,
1143 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1145 'id': '7209423610325322522',
1148 'creator': 'Pilarmagenta',
1149 'uploader': 'pilarmagenta',
1150 'uploader_id': '6624846890674683909',
1151 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1152 'live_status': 'is_live',
1153 'concurrent_view_count': int,
1155 'skip': 'Livestream',
1157 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1158 'only_matching': True,
1160 'url': 'https://www.tiktok.com/@iris04201/live',
1161 'only_matching': True,
1164 def _call_api(self
, url
, param
, room_id
, uploader
, key
=None):
1165 response
= traverse_obj(self
._download
_json
(
1166 url
, room_id
, fatal
=False, query
={
1169 }), (key
, {dict}
), default
={})
1171 # status == 2 if live else 4
1172 if int_or_none(response
.get('status')) == 2:
1174 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1176 raise ExtractorError('This livestream has ended', expected
=True)
1177 raise UserNotLive(video_id
=uploader
)
1179 def _real_extract(self
, url
):
1180 uploader
, room_id
= self
._match
_valid
_url
(url
).group('uploader', 'id')
1181 webpage
= self
._download
_webpage
(
1182 url
, uploader
or room_id
, headers
={'User-Agent': 'Mozilla/5.0'}
, fatal
=not room_id
)
1185 data
= try_call(lambda: self
._get
_sigi
_state
(webpage
, uploader
or room_id
))
1186 room_id
= (traverse_obj(data
, ('UserModule', 'users', ..., 'roomId', {str_or_none}
), get_all
=False)
1187 or self
._search
_regex
(r
'snssdk\d*://live\?room_id=(\d+)', webpage
, 'room ID', default
=None)
1189 uploader
= uploader
or traverse_obj(
1190 data
, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1191 ('UserModule', 'users', ..., 'uniqueId'), get_all
=False, expected_type
=str)
1194 raise UserNotLive(video_id
=uploader
)
1197 live_info
= self
._call
_api
(
1198 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id
, uploader
, key
='data')
1200 get_quality
= qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1201 parse_inner
= lambda x
: self
._parse
_json
(x
, None)
1203 for quality
, stream
in traverse_obj(live_info
, (
1204 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1205 {parse_inner}
, 'data', {dict}
), default
={}).items():
1207 sdk_params
= traverse_obj(stream
, ('main', 'sdk_params', {parse_inner}
, {
1208 'vcodec': ('VCodec', {str}
),
1209 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}
),
1210 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}
),
1213 flv_url
= traverse_obj(stream
, ('main', 'flv', {url_or_none}
))
1218 'format_id': f
'flv-{quality}',
1219 'quality': get_quality(quality
),
1223 hls_url
= traverse_obj(stream
, ('main', 'hls', {url_or_none}
))
1228 'protocol': 'm3u8_native',
1229 'format_id': f
'hls-{quality}',
1230 'quality': get_quality(quality
),
1234 def get_vcodec(*keys
):
1235 return traverse_obj(live_info
, (
1236 'stream_url', *keys
, {parse_inner}
, 'VCodec', {str}
))
1238 for stream
in ('hls', 'rtmp'):
1239 stream_url
= traverse_obj(live_info
, ('stream_url', f
'{stream}_pull_url', {url_or_none}
))
1243 'ext': 'mp4' if stream
== 'hls' else 'flv',
1244 'protocol': 'm3u8_native' if stream
== 'hls' else 'https',
1245 'format_id': f
'{stream}-pull',
1246 'vcodec': get_vcodec(f
'{stream}_pull_url_params'),
1247 'quality': get_quality('ORIGION'),
1250 for f_id
, f_url
in traverse_obj(live_info
, ('stream_url', 'flv_pull_url', {dict}
), default
={}).items():
1251 if not url_or_none(f_url
):
1256 'format_id': f
'flv-{f_id}'.lower(),
1257 'vcodec': get_vcodec('flv_pull_url_params', f_id
),
1258 'quality': get_quality(f_id
),
1261 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1262 if not traverse_obj(formats
, lambda _
, v
: v
['ext'] == 'mp4'):
1263 live_info
= merge_dicts(live_info
, self
._call
_api
(
1264 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id
, uploader
, key
='LiveRoomInfo'))
1265 if url_or_none(live_info
.get('liveUrl')):
1267 'url': live_info
['liveUrl'],
1269 'protocol': 'm3u8_native',
1270 'format_id': 'hls-fallback',
1272 'quality': get_quality('origin'),
1275 uploader
= uploader
or traverse_obj(live_info
, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
1279 'uploader': uploader
,
1280 'uploader_url': format_field(uploader
, None, self
._UPLOADER
_URL
_FORMAT
) or None,
1283 '_format_sort_fields': ('quality', 'ext'),
1284 **traverse_obj(live_info
, {
1286 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}
),
1287 'creator': (('ownerInfo', 'owner'), 'nickname'),
1288 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}
),