9 from .common
import InfoExtractor
10 from ..compat
import compat_urllib_parse_urlparse
11 from ..networking
import HEADRequest
24 srt_subtitles_timecode
,
33 class TikTokBaseIE(InfoExtractor
):
34 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
35 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
36 QUALITIES
= ('360p', '540p', '720p', '1080p')
38 _APP_INFO_DEFAULTS
= {
41 # TikTok (KR/PH/TW/TH/VN) = trill, TikTok (rest of world) = musical_ly, Douyin = aweme
42 'app_name': 'musical_ly',
43 'app_version': '34.1.2',
44 'manifest_app_version': '2023401020',
45 # "app id": aweme = 1128, trill = 1180, musical_ly = 1233, universal = 0
49 '7351144126450059040',
50 '7351149742343391009',
51 '7351153174894626592',
55 _APP_USER_AGENT
= None
58 def _API_HOSTNAME(self
):
59 return self
._configuration
_arg
(
60 'api_hostname', ['api22-normal-c-useast2a.tiktokv.com'], ie_key
=TikTokIE
)[0]
62 def _get_next_app_info(self
):
63 if self
._APP
_INFO
_POOL
is None:
65 key
: self
._configuration
_arg
(key
, [default
], ie_key
=TikTokIE
)[0]
66 for key
, default
in self
._APP
_INFO
_DEFAULTS
.items()
70 self
._configuration
_arg
('app_info', ie_key
=TikTokIE
)
71 or random
.sample(self
._KNOWN
_APP
_INFO
, len(self
._KNOWN
_APP
_INFO
)))
72 self
._APP
_INFO
_POOL
= [
74 (k
, v
) for k
, v
in zip(self
._APP
_INFO
_DEFAULTS
, app_info
.split('/')) if v
75 )} for app_info
in app_info_list
78 if not self
._APP
_INFO
_POOL
:
81 self
._APP
_INFO
= self
._APP
_INFO
_POOL
.pop(0)
83 app_name
= self
._APP
_INFO
['app_name']
84 version
= self
._APP
_INFO
['manifest_app_version']
85 if app_name
== 'musical_ly':
86 package
= f
'com.zhiliaoapp.musically/{version}'
88 package
= f
'com.ss.android.ugc.{app_name}/{version}'
89 self
._APP
_USER
_AGENT
= f
'{package} (Linux; U; Android 13; en_US; Pixel 7; Build/TD1A.220804.031; Cronet/58.0.2991.0)'
94 def _create_url(user_id
, video_id
):
95 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
97 def _get_sigi_state(self
, webpage
, display_id
):
98 return self
._search
_json
(
99 r
'<script[^>]+\bid="(?:SIGI_STATE|sigi-persisted-data)"[^>]*>', webpage
,
100 'sigi state', display_id
, end_pattern
=r
'</script>', default
={})
102 def _get_universal_data(self
, webpage
, display_id
):
103 return traverse_obj(self
._search
_json
(
104 r
'<script[^>]+\bid="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>', webpage
,
105 'universal data', display_id
, end_pattern
=r
'</script>', default
={}),
106 ('__DEFAULT_SCOPE__', {dict}
)) or {}
108 def _call_api_impl(self
, ep
, query
, video_id
, fatal
=True,
109 note
='Downloading API JSON', errnote
='Unable to download API page'):
110 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choices('0123456789abcdef', k
=160)))
111 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
112 if webpage_cookies
.get('sid_tt'):
113 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
114 return self
._download
_json
(
115 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
116 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
117 'User-Agent': self
._APP
_USER
_AGENT
,
118 'Accept': 'application/json',
121 def _build_api_query(self
, query
):
124 'device_platform': 'android',
127 '_rticket': int(time
.time() * 1000),
128 'cdid': str(uuid
.uuid4()),
129 'channel': 'googleplay',
130 'aid': self
._APP
_INFO
['aid'],
131 'app_name': self
._APP
_INFO
['app_name'],
132 'version_code': ''.join((f
'{int(v):02d}' for v
in self
._APP
_INFO
['app_version'].split('.'))),
133 'version_name': self
._APP
_INFO
['app_version'],
134 'manifest_version_code': self
._APP
_INFO
['manifest_app_version'],
135 'update_version_code': self
._APP
_INFO
['manifest_app_version'],
136 'ab_version': self
._APP
_INFO
['app_version'],
137 'resolution': '1080*2400',
139 'device_type': 'Pixel 7',
140 'device_brand': 'Google',
146 'current_region': 'US',
147 'app_type': 'normal',
149 'last_install_time': int(time
.time()) - random
.randint(86400, 1123200),
150 'timezone_name': 'America/New_York',
152 'app_language': 'en',
153 'timezone_offset': '-14400',
154 'host_abi': 'armeabi-v7a',
158 'carrier_region': 'US',
160 'build_number': self
._APP
_INFO
['app_version'],
162 'ts': int(time
.time()),
163 'iid': self
._APP
_INFO
['iid'],
164 'device_id': random
.randint(7250000000000000000, 7351147085025500000),
165 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
168 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
169 note
='Downloading API JSON', errnote
='Unable to download API page'):
170 if not self
._APP
_INFO
and not self
._get
_next
_app
_info
():
171 message
= 'No working app info is available'
173 raise ExtractorError(message
, expected
=True)
175 self
.report_warning(message
)
178 max_tries
= len(self
._APP
_INFO
_POOL
) + 1 # _APP_INFO_POOL + _APP_INFO
179 for count
in itertools
.count(1):
180 self
.write_debug(str(self
._APP
_INFO
))
181 real_query
= self
._build
_api
_query
(query
)
183 return self
._call
_api
_impl
(ep
, real_query
, video_id
, fatal
, note
, errnote
)
184 except ExtractorError
as e
:
185 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
186 message
= str(e
.cause
or e
.msg
)
187 if not self
._get
_next
_app
_info
():
191 self
.report_warning(message
)
193 self
.report_warning(f
'{message}. Retrying... (attempt {count} of {max_tries})')
197 def _extract_aweme_app(self
, aweme_id
):
198 feed_list
= self
._call
_api
(
199 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
200 errnote
='Unable to download video feed').get('aweme_list') or []
201 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
203 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
204 return self
._parse
_aweme
_video
_app
(aweme_detail
)
206 def _get_subtitles(self
, aweme_detail
, aweme_id
):
207 # TODO: Extract text positioning info
209 # aweme/detail endpoint subs
210 captions_info
= traverse_obj(
211 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
212 for caption
in captions_info
:
213 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
216 caption_json
= self
._download
_json
(
217 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
220 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
223 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
224 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
228 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
229 if not caption
.get('url'):
231 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
232 'ext': remove_start(caption
.get('caption_format'), 'web'),
233 'url': caption
['url'],
237 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', ...), expected_type
=dict):
238 if not caption
.get('Url'):
240 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
241 'ext': remove_start(caption
.get('Format'), 'web'),
242 'url': caption
['Url'],
246 def _parse_aweme_video_app(self
, aweme_detail
):
247 aweme_id
= aweme_detail
['aweme_id']
248 video_info
= aweme_detail
['video']
250 def parse_url_key(url_key
):
251 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
252 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
253 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
257 'format_id': format_id
,
258 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
259 'tbr': int_or_none(bitrate
, scale
=1000) or None,
260 'quality': qualities(self
.QUALITIES
)(res
),
263 known_resolutions
= {}
266 ext
= determine_ext(url
, default_ext
='m4a')
268 'format_note': 'Music track',
270 'acodec': 'aac' if ext
== 'm4a' else ext
,
274 } if ext
== 'mp3' or '-music-' in url
else {}
276 def extract_addr(addr
, add_meta
={}):
277 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
278 is_bytevc2
= parsed_meta
.get('vcodec') == 'bytevc2'
280 known_resolutions
.setdefault(res
, {}).setdefault('height', int_or_none(addr
.get('height')))
281 known_resolutions
[res
].setdefault('width', int_or_none(addr
.get('width')))
282 parsed_meta
.update(known_resolutions
.get(res
, {}))
283 add_meta
.setdefault('height', int_or_none(res
[:-1]))
286 'filesize': int_or_none(addr
.get('data_size')),
289 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
290 **add_meta
, **parsed_meta
,
291 # bytevc2 is bytedance's proprietary (unplayable) video codec
292 'preference': -100 if is_bytevc2
else -1,
293 'format_note': join_nonempty(
294 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None,
295 '(UNPLAYABLE)' if is_bytevc2
else None, delim
=' '),
297 } for url
in addr
.get('url_list') or []]
299 # Hack: Add direct video links first to prioritize them when removing duplicate formats
301 width
= int_or_none(video_info
.get('width'))
302 height
= int_or_none(video_info
.get('height'))
303 if video_info
.get('play_addr'):
304 formats
.extend(extract_addr(video_info
['play_addr'], {
305 'format_id': 'play_addr',
306 'format_note': 'Direct video',
307 'vcodec': 'h265' if traverse_obj(
308 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
312 if video_info
.get('download_addr'):
313 download_addr
= video_info
['download_addr']
314 dl_width
= int_or_none(download_addr
.get('width'))
315 formats
.extend(extract_addr(download_addr
, {
316 'format_id': 'download_addr',
317 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
319 'width': dl_width
or width
,
320 'height': try_call(lambda: int(dl_width
/ 0.5625)) or height
, # download_addr['height'] is wrong
321 'preference': -2 if video_info
.get('has_watermark') else -1,
323 if video_info
.get('play_addr_h264'):
324 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
325 'format_id': 'play_addr_h264',
326 'format_note': 'Direct video',
329 if video_info
.get('play_addr_bytevc1'):
330 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
331 'format_id': 'play_addr_bytevc1',
332 'format_note': 'Direct video',
336 for bitrate
in video_info
.get('bit_rate', []):
337 if bitrate
.get('play_addr'):
338 formats
.extend(extract_addr(bitrate
['play_addr'], {
339 'format_id': bitrate
.get('gear_name'),
340 'format_note': 'Playback video',
341 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
342 'vcodec': 'h265' if traverse_obj(
343 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
344 'fps': bitrate
.get('FPS'),
347 self
._remove
_duplicate
_formats
(formats
)
348 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
351 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
354 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
355 'origin_cover', 'dynamic_cover'):
356 for cover_url
in traverse_obj(video_info
, (cover_id
, 'url_list', ...)):
362 stats_info
= aweme_detail
.get('statistics') or {}
363 author_info
= aweme_detail
.get('author') or {}
364 music_info
= aweme_detail
.get('music') or {}
365 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
366 'sec_uid', 'id', 'uid', 'unique_id',
367 expected_type
=str_or_none
, get_all
=False))
368 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str)
370 contained_music_track
= traverse_obj(
371 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
372 contained_music_author
= traverse_obj(
373 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
375 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
376 if is_generic_og_trackname
:
377 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
379 music_track
, music_author
= music_info
.get('title'), traverse_obj(music_info
, ('author', {str}
))
383 **traverse_obj(aweme_detail
, {
384 'title': ('desc', {str}
),
385 'description': ('desc', {str}
),
386 'timestamp': ('create_time', {int_or_none}
),
388 **traverse_obj(stats_info
, {
389 'view_count': 'play_count',
390 'like_count': 'digg_count',
391 'repost_count': 'share_count',
392 'comment_count': 'comment_count',
393 }, expected_type
=int_or_none
),
394 **traverse_obj(author_info
, {
395 'uploader': ('unique_id', {str}
),
396 'uploader_id': ('uid', {str_or_none}
),
397 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
398 'channel': ('nickname', {str}
),
399 'channel_id': ('sec_uid', {str}
),
401 'uploader_url': user_url
,
402 'track': music_track
,
403 'album': str_or_none(music_info
.get('album')) or None,
404 'artists': re
.split(r
'(?:, | & )', music_author
) if music_author
else None,
406 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
407 'thumbnails': thumbnails
,
408 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
409 'availability': self
._availability
(
410 is_private
='Private' in labels
,
411 needs_subscription
='Friends only' in labels
,
412 is_unlisted
='Followers only' in labels
),
413 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
416 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
, video_id
):
417 video_info
= aweme_detail
['video']
418 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
419 music_info
= aweme_detail
.get('music') or {}
420 stats_info
= aweme_detail
.get('stats') or {}
421 channel_id
= traverse_obj(author_info
or aweme_detail
, (('authorSecId', 'secUid'), {str}
), get_all
=False)
422 user_url
= self
._UPLOADER
_URL
_FORMAT
% channel_id
if channel_id
else None
425 width
= int_or_none(video_info
.get('width'))
426 height
= int_or_none(video_info
.get('height'))
428 for play_url
in traverse_obj(video_info
, ('playAddr', ((..., 'src'), None), {url_or_none}
)):
430 'url': self
._proto
_relative
_url
(play_url
),
436 for download_url
in traverse_obj(video_info
, (('downloadAddr', ('download', 'url')), {url_or_none}
)):
438 'format_id': 'download',
439 'url': self
._proto
_relative
_url
(download_url
),
445 self
._remove
_duplicate
_formats
(formats
)
448 for thumb_url
in traverse_obj(aweme_detail
, (
449 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none}
)):
451 'url': self
._proto
_relative
_url
(thumb_url
),
458 **traverse_obj(aweme_detail
, {
459 'title': ('desc', {str}
),
460 'description': ('desc', {str}
),
461 'duration': ('video', 'duration', {int_or_none}
),
462 'timestamp': ('createTime', {int_or_none}
),
464 **traverse_obj(author_info
or aweme_detail
, {
465 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
466 'channel': ('nickname', {str}
),
467 'uploader': (('uniqueId', 'author'), {str}
),
468 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}
),
470 **traverse_obj(stats_info
, {
471 'view_count': 'playCount',
472 'like_count': 'diggCount',
473 'repost_count': 'shareCount',
474 'comment_count': 'commentCount',
475 }, expected_type
=int_or_none
),
476 **traverse_obj(music_info
, {
477 'track': ('title', {str}
),
478 'album': ('album', {str}
, {lambda x: x or None}
),
479 'artists': ('authorName', {str}
, {lambda x: [x] if x else None}
),
481 'channel_id': channel_id
,
482 'uploader_url': user_url
,
484 'thumbnails': thumbnails
,
486 'Referer': webpage_url
,
491 class TikTokIE(TikTokBaseIE
):
492 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
493 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
496 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
497 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
499 'id': '6748451240264420610',
501 'title': '#jassmanak #lehanga #leenabhushan',
502 'description': '#jassmanak #lehanga #leenabhushan',
506 'uploader': 'leenabhushan',
507 'uploader_id': '6691488002098119685',
508 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
509 'creator': 'facestoriesbyleenabh',
510 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
511 'upload_date': '20191016',
512 'timestamp': 1571246252,
516 'comment_count': int,
517 'artist': 'Ysrbeats',
521 'skip': '404 Not Found',
523 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
524 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
526 'id': '6742501081818877190',
528 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
529 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
533 'uploader': 'patrox',
534 'uploader_id': '18702747',
535 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
536 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
538 'creators': ['patroX'],
539 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
540 'upload_date': '20190930',
541 'timestamp': 1569860870,
545 'comment_count': int,
546 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'],
550 # Banned audio, only available on the app
551 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
553 'id': '6984138651336838402',
555 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
556 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
557 'uploader': 'barudakhb_',
558 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
559 'creators': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
560 'uploader_id': '6974687867511718913',
561 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
562 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
563 'track': 'Boka Dance',
564 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
565 'timestamp': 1626121503,
567 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
568 'upload_date': '20210712',
572 'comment_count': int,
575 # Sponsored video, only available with feed workaround
576 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
578 'id': '7042692929109986561',
580 'title': 'Slap and Run!',
581 'description': 'Slap and Run!',
582 'uploader': 'user440922249',
583 'channel': 'Slap And Run',
584 'creators': ['Slap And Run'],
585 'uploader_id': '7036055384943690754',
586 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
587 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
588 'track': 'Promoted Music',
589 'timestamp': 1639754738,
591 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
592 'upload_date': '20211217',
596 'comment_count': int,
598 'params': {'skip_download': True}
, # XXX: unable to download video data: HTTP Error 403: Forbidden
600 # Video without title and description
601 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
603 'id': '7059698374567611694',
605 'title': 'TikTok video #7059698374567611694',
607 'uploader': 'pokemonlife22',
608 'channel': 'Pokemon',
609 'creators': ['Pokemon'],
610 'uploader_id': '6820838815978423302',
611 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
612 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
613 'track': 'original sound',
614 'timestamp': 1643714123,
616 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
617 'upload_date': '20220201',
618 'artists': ['Pokemon'],
622 'comment_count': int,
625 # hydration JSON is sent in a <script> element
626 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
628 'id': '7065799023130643713',
630 'title': '#denidil#денидил',
631 'description': '#denidil#денидил',
632 'uploader': 'denidil6',
633 'uploader_id': '7046664115636405250',
634 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
635 'artist': 'Holocron Music',
636 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
637 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
638 'timestamp': 1645134536,
640 'upload_date': '20220217',
644 'comment_count': int,
646 'skip': 'This video is unavailable',
648 # slideshow audio-only mp3 format
649 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
651 'id': '7139980461132074283',
653 'title': 'TikTok video #7139980461132074283',
655 'channel': 'Antaura',
656 'creators': ['Antaura'],
657 'uploader': '_le_cannibale_',
658 'uploader_id': '6604511138619654149',
659 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
660 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
661 'artists': ['nathan !'],
662 'track': 'grahamscott canon',
663 'upload_date': '20220905',
664 'timestamp': 1662406249,
668 'comment_count': int,
669 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
672 # only available via web
673 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662', # FIXME
674 'md5': '6aba7fad816e8709ff2c149679ace165',
676 'id': '7206382937372134662',
678 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
679 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
680 'channel': 'MoxyPatch',
681 'creators': ['MoxyPatch'],
682 'uploader': 'moxypatch',
683 'uploader_id': '7039142049363379205',
684 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
685 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
686 'artists': ['your worst nightmare'],
687 'track': 'original sound',
688 'upload_date': '20230303',
689 'timestamp': 1677866781,
694 'comment_count': int,
695 'thumbnail': r
're:^https://.+',
696 'thumbnails': 'count:3',
698 'expected_warnings': ['Unable to find video in feed'],
701 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME
702 'md5': '982512017a8a917124d5a08c8ae79621',
704 'id': '7107337212743830830',
706 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
707 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
708 'uploader': 'tatemcrae',
709 'uploader_id': '86328792343818240',
710 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
711 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
712 'channel': 'tate mcrae',
713 'creators': ['tate mcrae'],
714 'artists': ['tate mcrae'],
715 'track': 'original sound',
716 'upload_date': '20220609',
717 'timestamp': 1654805899,
722 'comment_count': int,
723 'thumbnail': r
're:^https://.+\.webp',
725 'skip': 'Unavailable via feed API, no formats available via web',
727 # Slideshow, audio-only m4a format
728 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
729 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
731 'id': '7253412088251534594',
733 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
734 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
735 'uploader': 'hara_yoimiya',
736 'uploader_id': '6582536342634676230',
737 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
738 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
739 'channel': 'лампочка',
740 'creators': ['лампочка'],
741 'artists': ['Øneheart'],
742 'album': 'watching the stars',
743 'track': 'watching the stars',
744 'upload_date': '20230708',
745 'timestamp': 1688816612,
748 'comment_count': int,
750 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
753 # Auto-captions available
754 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
755 'only_matching': True
758 def _real_extract(self
, url
):
759 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
761 return self
._extract
_aweme
_app
(video_id
)
762 except ExtractorError
as e
:
764 self
.report_warning(f
'{e}; trying with webpage')
766 url
= self
._create
_url
(user_id
, video_id
)
767 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'Mozilla/5.0'}
)
769 if universal_data
:= self
._get
_universal
_data
(webpage
, video_id
):
770 self
.write_debug('Found universal data for rehydration')
771 status
= traverse_obj(universal_data
, ('webapp.video-detail', 'statusCode', {int}
)) or 0
772 video_data
= traverse_obj(universal_data
, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict}
))
774 elif sigi_data
:= self
._get
_sigi
_state
(webpage
, video_id
):
775 self
.write_debug('Found sigi state data')
776 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode', {int}
)) or 0
777 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
, {dict}
))
779 elif next_data
:= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}'):
780 self
.write_debug('Found next.js data')
781 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode', {int}
)) or 0
782 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict}
))
785 raise ExtractorError('Unable to extract webpage video data')
787 if video_data
and status
== 0:
788 return self
._parse
_aweme
_video
_web
(video_data
, url
, video_id
)
789 elif status
== 10216:
790 raise ExtractorError('This video is private', expected
=True)
791 raise ExtractorError(f
'Video not available, status code {status}', video_id
=video_id
)
794 class TikTokUserIE(TikTokBaseIE
):
795 IE_NAME
= 'tiktok:user'
796 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
799 'url': 'https://tiktok.com/@corgibobaa?lang=en',
800 'playlist_mincount': 45,
802 'id': '6935371178089399301',
803 'title': 'corgibobaa',
804 'thumbnail': r
're:https://.+_1080x1080\.webp'
806 'expected_warnings': ['Retrying']
808 'url': 'https://www.tiktok.com/@6820838815978423302',
809 'playlist_mincount': 5,
811 'id': '6820838815978423302',
812 'title': '6820838815978423302',
813 'thumbnail': r
're:https://.+_1080x1080\.webp'
815 'expected_warnings': ['Retrying']
817 'url': 'https://www.tiktok.com/@meme',
818 'playlist_mincount': 593,
820 'id': '79005827461758976',
822 'thumbnail': r
're:https://.+_1080x1080\.webp'
824 'expected_warnings': ['Retrying']
827 r
''' # TODO: Fix by adding _signature to api_url
828 def _entries(self, webpage, user_id, username):
829 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
830 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
831 if not verifyfp_cookie:
832 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
833 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='
835 for page in itertools.count():
836 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
837 for video in data_json.get('itemList', []):
838 video_id = video['id']
839 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
840 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
841 if not data_json.get('hasMore'):
843 cursor = data_json['cursor']
846 def _video_entries_api(self
, webpage
, user_id
, username
):
852 'retry_type': 'no_retry',
853 '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.
856 for page
in itertools
.count(1):
857 for retry
in self
.RetryManager():
859 post_list
= self
._call
_api
(
860 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
861 errnote
='Unable to download user video list')
862 except ExtractorError
as e
:
863 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
867 yield from post_list
.get('aweme_list', [])
868 if not post_list
.get('has_more'):
870 query
['max_cursor'] = post_list
['max_cursor']
872 def _entries_api(self
, user_id
, videos
):
875 **self
._parse
_aweme
_video
_app
(video
),
876 'extractor_key': TikTokIE
.ie_key(),
877 'extractor': 'TikTok',
878 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
881 def _real_extract(self
, url
):
882 user_name
= self
._match
_id
(url
)
883 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
884 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
886 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
888 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
889 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
891 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
894 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
895 def _entries(self
, list_id
, display_id
):
897 self
._QUERY
_NAME
: list_id
,
901 'device_id': ''.join(random
.choices(string
.digits
, k
=19))
904 for page
in itertools
.count(1):
905 for retry
in self
.RetryManager():
907 post_list
= self
._call
_api
(
908 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
909 errnote
='Unable to download video list')
910 except ExtractorError
as e
:
911 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
915 for video
in post_list
.get('aweme_list', []):
917 **self
._parse
_aweme
_video
_app
(video
),
918 'extractor_key': TikTokIE
.ie_key(),
919 'extractor': 'TikTok',
920 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
922 if not post_list
.get('has_more'):
924 query
['cursor'] = post_list
['cursor']
926 def _real_extract(self
, url
):
927 list_id
= self
._match
_id
(url
)
928 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
931 class TikTokSoundIE(TikTokBaseListIE
):
932 IE_NAME
= 'tiktok:sound'
933 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
935 _QUERY_NAME
= 'music_id'
936 _API_ENDPOINT
= 'music/aweme'
938 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
939 'playlist_mincount': 100,
941 'id': '6956990112127585029'
943 'expected_warnings': ['Retrying']
945 # Actual entries are less than listed video count
946 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
947 'playlist_mincount': 2182,
949 'id': '7036843036118469381'
951 'expected_warnings': ['Retrying']
955 class TikTokEffectIE(TikTokBaseListIE
):
956 IE_NAME
= 'tiktok:effect'
957 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
959 _QUERY_NAME
= 'sticker_id'
960 _API_ENDPOINT
= 'sticker/aweme'
962 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
963 'playlist_mincount': 100,
967 'expected_warnings': ['Retrying']
969 # Different entries between mobile and web, depending on region
970 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
971 'only_matching': True
975 class TikTokTagIE(TikTokBaseListIE
):
976 IE_NAME
= 'tiktok:tag'
977 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
979 _QUERY_NAME
= 'ch_id'
980 _API_ENDPOINT
= 'challenge/aweme'
982 'url': 'https://tiktok.com/tag/hello2018',
983 'playlist_mincount': 39,
986 'title': 'hello2018',
988 'expected_warnings': ['Retrying']
990 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
991 'only_matching': True
994 def _real_extract(self
, url
):
995 display_id
= self
._match
_id
(url
)
996 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
997 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
999 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
1000 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
1003 class DouyinIE(TikTokBaseIE
):
1004 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
1006 'url': 'https://www.douyin.com/video/6961737553342991651',
1007 'md5': '9ecce7bc5b302601018ecb2871c63a75',
1009 'id': '6961737553342991651',
1011 'title': '#杨超越 小小水手带你去远航❤️',
1012 'description': '#杨超越 小小水手带你去远航❤️',
1013 'uploader': '6897520xka',
1014 'uploader_id': '110403406559',
1015 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1016 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1018 'creators': ['杨超越'],
1020 'timestamp': 1620905839,
1021 'upload_date': '20210513',
1022 'track': '@杨超越创作的原声',
1026 'repost_count': int,
1027 'comment_count': int,
1028 'thumbnail': r
're:https?://.+\.jpe?g',
1031 'url': 'https://www.douyin.com/video/6982497745948921092',
1032 'md5': '15c5e660b7048af3707304e3cc02bbb5',
1034 'id': '6982497745948921092',
1036 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1037 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1038 'uploader': '0731chaoyue',
1039 'uploader_id': '408654318141572',
1040 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1041 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1042 'channel': '杨超越工作室',
1043 'creators': ['杨超越工作室'],
1045 'timestamp': 1625739481,
1046 'upload_date': '20210708',
1047 'track': '@杨超越工作室创作的原声',
1048 'artists': ['杨超越工作室'],
1051 'repost_count': int,
1052 'comment_count': int,
1053 'thumbnail': r
're:https?://.+\.jpe?g',
1056 'url': 'https://www.douyin.com/video/6953975910773099811',
1057 'md5': '0e6443758b8355db9a3c34864a4276be',
1059 'id': '6953975910773099811',
1061 'title': '#一起看海 出现在你的夏日里',
1062 'description': '#一起看海 出现在你的夏日里',
1063 'uploader': '6897520xka',
1064 'uploader_id': '110403406559',
1065 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1066 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1068 'creators': ['杨超越'],
1070 'timestamp': 1619098692,
1071 'upload_date': '20210422',
1072 'track': '@杨超越创作的原声',
1076 'repost_count': int,
1077 'comment_count': int,
1078 'thumbnail': r
're:https?://.+\.jpe?g',
1081 'url': 'https://www.douyin.com/video/6950251282489675042',
1082 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1084 'id': '6950251282489675042',
1086 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1088 'upload_date': '20210412',
1089 'timestamp': 1618231483,
1090 'uploader_id': '110403406559',
1093 'repost_count': int,
1094 'comment_count': int,
1096 'skip': 'No longer available',
1098 'url': 'https://www.douyin.com/video/6963263655114722595',
1099 'md5': '1440bcf59d8700f8e014da073a4dfea8',
1101 'id': '6963263655114722595',
1103 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1104 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1105 'uploader': '6897520xka',
1106 'uploader_id': '110403406559',
1107 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1108 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1110 'creators': ['杨超越'],
1112 'timestamp': 1621261163,
1113 'upload_date': '20210517',
1114 'track': '@杨超越创作的原声',
1118 'repost_count': int,
1119 'comment_count': int,
1120 'thumbnail': r
're:https?://.+\.jpe?g',
1123 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
1124 _WEBPAGE_HOST
= 'https://www.douyin.com/'
1126 def _real_extract(self
, url
):
1127 video_id
= self
._match
_id
(url
)
1129 detail
= traverse_obj(self
._download
_json
(
1130 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id
,
1131 'Downloading web detail JSON', 'Failed to download web detail JSON',
1132 query
={'aweme_id': video_id}
, fatal
=False), ('aweme_detail', {dict}
))
1134 # TODO: Run verification challenge code to generate signature cookies
1135 raise ExtractorError(
1136 'Fresh cookies (not necessarily logged in) are needed',
1137 expected
=not self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('s_v_web_id'))
1139 return self
._parse
_aweme
_video
_app
(detail
)
1142 class TikTokVMIE(InfoExtractor
):
1143 _VALID_URL
= r
'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
1144 IE_NAME
= 'vm.tiktok'
1147 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
1149 'id': '7170520270497680683',
1151 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1152 'uploader_id': '6687535061741700102',
1153 'upload_date': '20221127',
1156 'comment_count': int,
1157 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1158 'album': 'Wave of Mutilation: Best of Pixies',
1159 'thumbnail': r
're:https://.+\.webp.*',
1161 'timestamp': 1669516858,
1162 'repost_count': int,
1164 'track': 'Where Is My Mind?',
1165 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1166 'uploader': 'sigmachaddeus',
1167 'creator': 'SigmaChad',
1170 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1172 'id': '7106798200794926362',
1174 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1175 'uploader_id': '6997695878846268418',
1176 'upload_date': '20220608',
1179 'comment_count': int,
1180 'thumbnail': r
're:https://.+\.webp.*',
1181 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1183 'timestamp': 1654680400,
1184 'repost_count': int,
1185 'artist': 'Akihitoko',
1186 'track': 'original sound',
1187 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1188 'uploader': 'akihitoko1',
1189 'creator': 'Akihitoko',
1192 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1193 'only_matching': True,
1196 def _real_extract(self
, url
):
1197 new_url
= self
._request
_webpage
(
1198 HEADRequest(url
), self
._match
_id
(url
), headers
={'User-Agent': 'facebookexternalhit/1.1'}
).url
1199 if self
.suitable(new_url
): # Prevent infinite loop in case redirect fails
1200 raise UnsupportedError(new_url
)
1201 return self
.url_result(new_url
)
1204 class TikTokLiveIE(TikTokBaseIE
):
1205 _VALID_URL
= r
'''(?x)https?://(?:
1206 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1207 m\.tiktok\.com/share/live/(?P<id>\d+)
1209 IE_NAME
= 'tiktok:live'
1212 'url': 'https://www.tiktok.com/@weathernewslive/live',
1214 'id': '7210809319192726273',
1216 'title': r
're:ウェザーニュースLiVE[\d\s:-]*',
1217 'creator': 'ウェザーニュースLiVE',
1218 'uploader': 'weathernewslive',
1219 'uploader_id': '6621496731283095554',
1220 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1221 'live_status': 'is_live',
1222 'concurrent_view_count': int,
1224 'params': {'skip_download': 'm3u8'}
,
1226 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1228 'id': '7209423610325322522',
1231 'creator': 'Pilarmagenta',
1232 'uploader': 'pilarmagenta',
1233 'uploader_id': '6624846890674683909',
1234 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1235 'live_status': 'is_live',
1236 'concurrent_view_count': int,
1238 'skip': 'Livestream',
1240 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1241 'only_matching': True,
1243 'url': 'https://www.tiktok.com/@iris04201/live',
1244 'only_matching': True,
1247 def _call_api(self
, url
, param
, room_id
, uploader
, key
=None):
1248 response
= traverse_obj(self
._download
_json
(
1249 url
, room_id
, fatal
=False, query
={
1252 }), (key
, {dict}
), default
={})
1254 # status == 2 if live else 4
1255 if int_or_none(response
.get('status')) == 2:
1257 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1259 raise ExtractorError('This livestream has ended', expected
=True)
1260 raise UserNotLive(video_id
=uploader
)
1262 def _real_extract(self
, url
):
1263 uploader
, room_id
= self
._match
_valid
_url
(url
).group('uploader', 'id')
1264 webpage
= self
._download
_webpage
(
1265 url
, uploader
or room_id
, headers
={'User-Agent': 'Mozilla/5.0'}
, fatal
=not room_id
)
1268 data
= self
._get
_sigi
_state
(webpage
, uploader
or room_id
)
1269 room_id
= (traverse_obj(data
, ('UserModule', 'users', ..., 'roomId', {str_or_none}
), get_all
=False)
1270 or self
._search
_regex
(r
'snssdk\d*://live\?room_id=(\d+)', webpage
, 'room ID', default
=None)
1272 uploader
= uploader
or traverse_obj(
1273 data
, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1274 ('UserModule', 'users', ..., 'uniqueId'), get_all
=False, expected_type
=str)
1277 raise UserNotLive(video_id
=uploader
)
1280 live_info
= self
._call
_api
(
1281 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id
, uploader
, key
='data')
1283 get_quality
= qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1284 parse_inner
= lambda x
: self
._parse
_json
(x
, None)
1286 for quality
, stream
in traverse_obj(live_info
, (
1287 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1288 {parse_inner}
, 'data', {dict}
), default
={}).items():
1290 sdk_params
= traverse_obj(stream
, ('main', 'sdk_params', {parse_inner}
, {
1291 'vcodec': ('VCodec', {str}
),
1292 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}
),
1293 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}
),
1296 flv_url
= traverse_obj(stream
, ('main', 'flv', {url_or_none}
))
1301 'format_id': f
'flv-{quality}',
1302 'quality': get_quality(quality
),
1306 hls_url
= traverse_obj(stream
, ('main', 'hls', {url_or_none}
))
1311 'protocol': 'm3u8_native',
1312 'format_id': f
'hls-{quality}',
1313 'quality': get_quality(quality
),
1317 def get_vcodec(*keys
):
1318 return traverse_obj(live_info
, (
1319 'stream_url', *keys
, {parse_inner}
, 'VCodec', {str}
))
1321 for stream
in ('hls', 'rtmp'):
1322 stream_url
= traverse_obj(live_info
, ('stream_url', f
'{stream}_pull_url', {url_or_none}
))
1326 'ext': 'mp4' if stream
== 'hls' else 'flv',
1327 'protocol': 'm3u8_native' if stream
== 'hls' else 'https',
1328 'format_id': f
'{stream}-pull',
1329 'vcodec': get_vcodec(f
'{stream}_pull_url_params'),
1330 'quality': get_quality('ORIGION'),
1333 for f_id
, f_url
in traverse_obj(live_info
, ('stream_url', 'flv_pull_url', {dict}
), default
={}).items():
1334 if not url_or_none(f_url
):
1339 'format_id': f
'flv-{f_id}'.lower(),
1340 'vcodec': get_vcodec('flv_pull_url_params', f_id
),
1341 'quality': get_quality(f_id
),
1344 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1345 if not traverse_obj(formats
, lambda _
, v
: v
['ext'] == 'mp4'):
1346 live_info
= merge_dicts(live_info
, self
._call
_api
(
1347 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id
, uploader
, key
='LiveRoomInfo'))
1348 if url_or_none(live_info
.get('liveUrl')):
1350 'url': live_info
['liveUrl'],
1352 'protocol': 'm3u8_native',
1353 'format_id': 'hls-fallback',
1355 'quality': get_quality('origin'),
1358 uploader
= uploader
or traverse_obj(live_info
, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
1362 'uploader': uploader
,
1363 'uploader_url': format_field(uploader
, None, self
._UPLOADER
_URL
_FORMAT
) or None,
1366 '_format_sort_fields': ('quality', 'ext'),
1367 **traverse_obj(live_info
, {
1369 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}
),
1370 'creator': (('ownerInfo', 'owner'), 'nickname'),
1371 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}
),