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
50 _APP_USER_AGENT
= None
53 def _KNOWN_APP_INFO(self
):
54 return self
._configuration
_arg
('app_info', ie_key
=TikTokIE
)
57 def _API_HOSTNAME(self
):
58 return self
._configuration
_arg
(
59 'api_hostname', ['api16-normal-c-useast1a.tiktokv.com'], ie_key
=TikTokIE
)[0]
61 def _get_next_app_info(self
):
62 if self
._APP
_INFO
_POOL
is None:
64 key
: self
._configuration
_arg
(key
, [default
], ie_key
=TikTokIE
)[0]
65 for key
, default
in self
._APP
_INFO
_DEFAULTS
.items()
68 self
._APP
_INFO
_POOL
= [
70 (k
, v
) for k
, v
in zip(self
._APP
_INFO
_DEFAULTS
, app_info
.split('/')) if v
71 )} for app_info
in self
._KNOWN
_APP
_INFO
74 if not self
._APP
_INFO
_POOL
:
77 self
._APP
_INFO
= self
._APP
_INFO
_POOL
.pop(0)
79 app_name
= self
._APP
_INFO
['app_name']
80 version
= self
._APP
_INFO
['manifest_app_version']
81 if app_name
== 'musical_ly':
82 package
= f
'com.zhiliaoapp.musically/{version}'
84 package
= f
'com.ss.android.ugc.{app_name}/{version}'
85 self
._APP
_USER
_AGENT
= f
'{package} (Linux; U; Android 13; en_US; Pixel 7; Build/TD1A.220804.031; Cronet/58.0.2991.0)'
90 def _create_url(user_id
, video_id
):
91 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
93 def _get_sigi_state(self
, webpage
, display_id
):
94 return self
._search
_json
(
95 r
'<script[^>]+\bid="(?:SIGI_STATE|sigi-persisted-data)"[^>]*>', webpage
,
96 'sigi state', display_id
, end_pattern
=r
'</script>', default
={})
98 def _get_universal_data(self
, webpage
, display_id
):
99 return traverse_obj(self
._search
_json
(
100 r
'<script[^>]+\bid="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>', webpage
,
101 'universal data', display_id
, end_pattern
=r
'</script>', default
={}),
102 ('__DEFAULT_SCOPE__', {dict}
)) or {}
104 def _call_api_impl(self
, ep
, query
, video_id
, fatal
=True,
105 note
='Downloading API JSON', errnote
='Unable to download API page'):
106 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choices('0123456789abcdef', k
=160)))
107 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
108 if webpage_cookies
.get('sid_tt'):
109 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
110 return self
._download
_json
(
111 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
112 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
113 'User-Agent': self
._APP
_USER
_AGENT
,
114 'Accept': 'application/json',
117 def _build_api_query(self
, query
):
120 'device_platform': 'android',
123 '_rticket': int(time
.time() * 1000),
124 'cdid': str(uuid
.uuid4()),
125 'channel': 'googleplay',
126 'aid': self
._APP
_INFO
['aid'],
127 'app_name': self
._APP
_INFO
['app_name'],
128 'version_code': ''.join((f
'{int(v):02d}' for v
in self
._APP
_INFO
['app_version'].split('.'))),
129 'version_name': self
._APP
_INFO
['app_version'],
130 'manifest_version_code': self
._APP
_INFO
['manifest_app_version'],
131 'update_version_code': self
._APP
_INFO
['manifest_app_version'],
132 'ab_version': self
._APP
_INFO
['app_version'],
133 'resolution': '1080*2400',
135 'device_type': 'Pixel 7',
136 'device_brand': 'Google',
142 'current_region': 'US',
143 'app_type': 'normal',
145 'last_install_time': int(time
.time()) - random
.randint(86400, 1123200),
146 'timezone_name': 'America/New_York',
148 'app_language': 'en',
149 'timezone_offset': '-14400',
150 'host_abi': 'armeabi-v7a',
154 'carrier_region': 'US',
156 'build_number': self
._APP
_INFO
['app_version'],
158 'ts': int(time
.time()),
159 'iid': self
._APP
_INFO
['iid'],
160 'device_id': random
.randint(7250000000000000000, 7351147085025500000),
161 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
164 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
165 note
='Downloading API JSON', errnote
='Unable to download API page'):
166 if not self
._APP
_INFO
and not self
._get
_next
_app
_info
():
167 message
= 'No working app info is available'
169 raise ExtractorError(message
, expected
=True)
171 self
.report_warning(message
)
174 max_tries
= len(self
._APP
_INFO
_POOL
) + 1 # _APP_INFO_POOL + _APP_INFO
175 for count
in itertools
.count(1):
176 self
.write_debug(str(self
._APP
_INFO
))
177 real_query
= self
._build
_api
_query
(query
)
179 return self
._call
_api
_impl
(ep
, real_query
, video_id
, fatal
, note
, errnote
)
180 except ExtractorError
as e
:
181 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
182 message
= str(e
.cause
or e
.msg
)
183 if not self
._get
_next
_app
_info
():
187 self
.report_warning(message
)
189 self
.report_warning(f
'{message}. Retrying... (attempt {count} of {max_tries})')
193 def _extract_aweme_app(self
, aweme_id
):
194 feed_list
= self
._call
_api
(
195 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
196 errnote
='Unable to download video feed').get('aweme_list') or []
197 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
199 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
200 return self
._parse
_aweme
_video
_app
(aweme_detail
)
202 def _get_subtitles(self
, aweme_detail
, aweme_id
):
203 # TODO: Extract text positioning info
205 # aweme/detail endpoint subs
206 captions_info
= traverse_obj(
207 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
208 for caption
in captions_info
:
209 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
212 caption_json
= self
._download
_json
(
213 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
216 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
219 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
220 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
224 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
225 if not caption
.get('url'):
227 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
228 'ext': remove_start(caption
.get('caption_format'), 'web'),
229 'url': caption
['url'],
233 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', ...), expected_type
=dict):
234 if not caption
.get('Url'):
236 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
237 'ext': remove_start(caption
.get('Format'), 'web'),
238 'url': caption
['Url'],
242 def _parse_aweme_video_app(self
, aweme_detail
):
243 aweme_id
= aweme_detail
['aweme_id']
244 video_info
= aweme_detail
['video']
246 def parse_url_key(url_key
):
247 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
248 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
249 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
253 'format_id': format_id
,
254 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
255 'tbr': int_or_none(bitrate
, scale
=1000) or None,
256 'quality': qualities(self
.QUALITIES
)(res
),
259 known_resolutions
= {}
262 ext
= determine_ext(url
, default_ext
='m4a')
264 'format_note': 'Music track',
266 'acodec': 'aac' if ext
== 'm4a' else ext
,
270 } if ext
== 'mp3' or '-music-' in url
else {}
272 def extract_addr(addr
, add_meta
={}):
273 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
274 is_bytevc2
= parsed_meta
.get('vcodec') == 'bytevc2'
276 known_resolutions
.setdefault(res
, {}).setdefault('height', int_or_none(addr
.get('height')))
277 known_resolutions
[res
].setdefault('width', int_or_none(addr
.get('width')))
278 parsed_meta
.update(known_resolutions
.get(res
, {}))
279 add_meta
.setdefault('height', int_or_none(res
[:-1]))
282 'filesize': int_or_none(addr
.get('data_size')),
285 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
286 **add_meta
, **parsed_meta
,
287 # bytevc2 is bytedance's proprietary (unplayable) video codec
288 'preference': -100 if is_bytevc2
else -1,
289 'format_note': join_nonempty(
290 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None,
291 '(UNPLAYABLE)' if is_bytevc2
else None, delim
=' '),
293 } for url
in addr
.get('url_list') or []]
295 # Hack: Add direct video links first to prioritize them when removing duplicate formats
297 width
= int_or_none(video_info
.get('width'))
298 height
= int_or_none(video_info
.get('height'))
299 if video_info
.get('play_addr'):
300 formats
.extend(extract_addr(video_info
['play_addr'], {
301 'format_id': 'play_addr',
302 'format_note': 'Direct video',
303 'vcodec': 'h265' if traverse_obj(
304 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
308 if video_info
.get('download_addr'):
309 download_addr
= video_info
['download_addr']
310 dl_width
= int_or_none(download_addr
.get('width'))
311 formats
.extend(extract_addr(download_addr
, {
312 'format_id': 'download_addr',
313 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
315 'width': dl_width
or width
,
316 'height': try_call(lambda: int(dl_width
/ 0.5625)) or height
, # download_addr['height'] is wrong
317 'preference': -2 if video_info
.get('has_watermark') else -1,
319 if video_info
.get('play_addr_h264'):
320 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
321 'format_id': 'play_addr_h264',
322 'format_note': 'Direct video',
325 if video_info
.get('play_addr_bytevc1'):
326 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
327 'format_id': 'play_addr_bytevc1',
328 'format_note': 'Direct video',
332 for bitrate
in video_info
.get('bit_rate', []):
333 if bitrate
.get('play_addr'):
334 formats
.extend(extract_addr(bitrate
['play_addr'], {
335 'format_id': bitrate
.get('gear_name'),
336 'format_note': 'Playback video',
337 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
338 'vcodec': 'h265' if traverse_obj(
339 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
340 'fps': bitrate
.get('FPS'),
343 self
._remove
_duplicate
_formats
(formats
)
344 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
347 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
350 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
351 'origin_cover', 'dynamic_cover'):
352 for cover_url
in traverse_obj(video_info
, (cover_id
, 'url_list', ...)):
358 stats_info
= aweme_detail
.get('statistics') or {}
359 author_info
= aweme_detail
.get('author') or {}
360 music_info
= aweme_detail
.get('music') or {}
361 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
362 'sec_uid', 'id', 'uid', 'unique_id',
363 expected_type
=str_or_none
, get_all
=False))
364 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str)
366 contained_music_track
= traverse_obj(
367 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
368 contained_music_author
= traverse_obj(
369 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
371 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
372 if is_generic_og_trackname
:
373 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
375 music_track
, music_author
= music_info
.get('title'), traverse_obj(music_info
, ('author', {str}
))
379 **traverse_obj(aweme_detail
, {
380 'title': ('desc', {str}
),
381 'description': ('desc', {str}
),
382 'timestamp': ('create_time', {int_or_none}
),
384 **traverse_obj(stats_info
, {
385 'view_count': 'play_count',
386 'like_count': 'digg_count',
387 'repost_count': 'share_count',
388 'comment_count': 'comment_count',
389 }, expected_type
=int_or_none
),
390 **traverse_obj(author_info
, {
391 'uploader': ('unique_id', {str}
),
392 'uploader_id': ('uid', {str_or_none}
),
393 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
394 'channel': ('nickname', {str}
),
395 'channel_id': ('sec_uid', {str}
),
397 'uploader_url': user_url
,
398 'track': music_track
,
399 'album': str_or_none(music_info
.get('album')) or None,
400 'artists': re
.split(r
'(?:, | & )', music_author
) if music_author
else None,
402 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
403 'thumbnails': thumbnails
,
404 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
405 'availability': self
._availability
(
406 is_private
='Private' in labels
,
407 needs_subscription
='Friends only' in labels
,
408 is_unlisted
='Followers only' in labels
),
409 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
412 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
, video_id
):
413 video_info
= aweme_detail
['video']
414 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
415 music_info
= aweme_detail
.get('music') or {}
416 stats_info
= aweme_detail
.get('stats') or {}
417 channel_id
= traverse_obj(author_info
or aweme_detail
, (('authorSecId', 'secUid'), {str}
), get_all
=False)
418 user_url
= self
._UPLOADER
_URL
_FORMAT
% channel_id
if channel_id
else None
421 width
= int_or_none(video_info
.get('width'))
422 height
= int_or_none(video_info
.get('height'))
424 for play_url
in traverse_obj(video_info
, ('playAddr', ((..., 'src'), None), {url_or_none}
)):
426 'url': self
._proto
_relative
_url
(play_url
),
432 for download_url
in traverse_obj(video_info
, (('downloadAddr', ('download', 'url')), {url_or_none}
)):
434 'format_id': 'download',
435 'url': self
._proto
_relative
_url
(download_url
),
441 self
._remove
_duplicate
_formats
(formats
)
444 for thumb_url
in traverse_obj(aweme_detail
, (
445 (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none}
)):
447 'url': self
._proto
_relative
_url
(thumb_url
),
454 **traverse_obj(aweme_detail
, {
455 'title': ('desc', {str}
),
456 'description': ('desc', {str}
),
457 'duration': ('video', 'duration', {int_or_none}
),
458 'timestamp': ('createTime', {int_or_none}
),
460 **traverse_obj(author_info
or aweme_detail
, {
461 'creators': ('nickname', {str}
, {lambda x: [x] if x else None}
), # for compat
462 'channel': ('nickname', {str}
),
463 'uploader': (('uniqueId', 'author'), {str}
),
464 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}
),
466 **traverse_obj(stats_info
, {
467 'view_count': 'playCount',
468 'like_count': 'diggCount',
469 'repost_count': 'shareCount',
470 'comment_count': 'commentCount',
471 }, expected_type
=int_or_none
),
472 **traverse_obj(music_info
, {
473 'track': ('title', {str}
),
474 'album': ('album', {str}
, {lambda x: x or None}
),
475 'artists': ('authorName', {str}
, {lambda x: [x] if x else None}
),
477 'channel_id': channel_id
,
478 'uploader_url': user_url
,
480 'thumbnails': thumbnails
,
482 'Referer': webpage_url
,
487 class TikTokIE(TikTokBaseIE
):
488 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
489 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
492 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
493 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
495 'id': '6748451240264420610',
497 'title': '#jassmanak #lehanga #leenabhushan',
498 'description': '#jassmanak #lehanga #leenabhushan',
502 'uploader': 'leenabhushan',
503 'uploader_id': '6691488002098119685',
504 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
505 'creator': 'facestoriesbyleenabh',
506 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
507 'upload_date': '20191016',
508 'timestamp': 1571246252,
512 'comment_count': int,
513 'artist': 'Ysrbeats',
517 'skip': '404 Not Found',
519 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
520 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
522 'id': '6742501081818877190',
524 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
525 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
529 'uploader': 'patrox',
530 'uploader_id': '18702747',
531 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
532 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
534 'creators': ['patroX'],
535 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
536 'upload_date': '20190930',
537 'timestamp': 1569860870,
541 'comment_count': int,
542 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'],
546 # Banned audio, only available on the app
547 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
549 'id': '6984138651336838402',
551 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
552 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
553 'uploader': 'barudakhb_',
554 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
555 'creators': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
556 'uploader_id': '6974687867511718913',
557 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
558 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
559 'track': 'Boka Dance',
560 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'],
561 'timestamp': 1626121503,
563 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
564 'upload_date': '20210712',
568 'comment_count': int,
571 # Sponsored video, only available with feed workaround
572 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
574 'id': '7042692929109986561',
576 'title': 'Slap and Run!',
577 'description': 'Slap and Run!',
578 'uploader': 'user440922249',
579 'channel': 'Slap And Run',
580 'creators': ['Slap And Run'],
581 'uploader_id': '7036055384943690754',
582 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
583 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
584 'track': 'Promoted Music',
585 'timestamp': 1639754738,
587 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
588 'upload_date': '20211217',
592 'comment_count': int,
594 'params': {'skip_download': True}
, # XXX: unable to download video data: HTTP Error 403: Forbidden
596 # Video without title and description
597 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
599 'id': '7059698374567611694',
601 'title': 'TikTok video #7059698374567611694',
603 'uploader': 'pokemonlife22',
604 'channel': 'Pokemon',
605 'creators': ['Pokemon'],
606 'uploader_id': '6820838815978423302',
607 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
608 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
609 'track': 'original sound',
610 'timestamp': 1643714123,
612 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
613 'upload_date': '20220201',
614 'artists': ['Pokemon'],
618 'comment_count': int,
621 # hydration JSON is sent in a <script> element
622 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
624 'id': '7065799023130643713',
626 'title': '#denidil#денидил',
627 'description': '#denidil#денидил',
628 'uploader': 'denidil6',
629 'uploader_id': '7046664115636405250',
630 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
631 'artist': 'Holocron Music',
632 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
633 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
634 'timestamp': 1645134536,
636 'upload_date': '20220217',
640 'comment_count': int,
642 'skip': 'This video is unavailable',
644 # slideshow audio-only mp3 format
645 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283',
647 'id': '7139980461132074283',
649 'title': 'TikTok video #7139980461132074283',
651 'channel': 'Antaura',
652 'creators': ['Antaura'],
653 'uploader': '_le_cannibale_',
654 'uploader_id': '6604511138619654149',
655 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
656 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP',
657 'artists': ['nathan !'],
658 'track': 'grahamscott canon',
659 'upload_date': '20220905',
660 'timestamp': 1662406249,
664 'comment_count': int,
665 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
668 # only available via web
669 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662', # FIXME
670 'md5': '6aba7fad816e8709ff2c149679ace165',
672 'id': '7206382937372134662',
674 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
675 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a',
676 'channel': 'MoxyPatch',
677 'creators': ['MoxyPatch'],
678 'uploader': 'moxypatch',
679 'uploader_id': '7039142049363379205',
680 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
681 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V',
682 'artists': ['your worst nightmare'],
683 'track': 'original sound',
684 'upload_date': '20230303',
685 'timestamp': 1677866781,
690 'comment_count': int,
691 'thumbnail': r
're:^https://.+',
692 'thumbnails': 'count:3',
694 'expected_warnings': ['Unable to find video in feed'],
697 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME
698 'md5': '982512017a8a917124d5a08c8ae79621',
700 'id': '7107337212743830830',
702 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
703 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok',
704 'uploader': 'tatemcrae',
705 'uploader_id': '86328792343818240',
706 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
707 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd',
708 'channel': 'tate mcrae',
709 'creators': ['tate mcrae'],
710 'artists': ['tate mcrae'],
711 'track': 'original sound',
712 'upload_date': '20220609',
713 'timestamp': 1654805899,
718 'comment_count': int,
719 'thumbnail': r
're:^https://.+\.webp',
721 'skip': 'Unavailable via feed API, no formats available via web',
723 # Slideshow, audio-only m4a format
724 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594',
725 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d',
727 'id': '7253412088251534594',
729 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
730 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ',
731 'uploader': 'hara_yoimiya',
732 'uploader_id': '6582536342634676230',
733 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
734 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB',
735 'channel': 'лампочка',
736 'creators': ['лампочка'],
737 'artists': ['Øneheart'],
738 'album': 'watching the stars',
739 'track': 'watching the stars',
740 'upload_date': '20230708',
741 'timestamp': 1688816612,
744 'comment_count': int,
746 'thumbnail': r
're:^https://.+\.(?:webp|jpe?g)',
749 # Auto-captions available
750 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
751 'only_matching': True
754 def _real_extract(self
, url
):
755 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
757 if self
._KNOWN
_APP
_INFO
:
759 return self
._extract
_aweme
_app
(video_id
)
760 except ExtractorError
as e
:
762 self
.report_warning(f
'{e}; trying with webpage')
764 url
= self
._create
_url
(user_id
, video_id
)
765 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'Mozilla/5.0'}
)
767 if universal_data
:= self
._get
_universal
_data
(webpage
, video_id
):
768 self
.write_debug('Found universal data for rehydration')
769 status
= traverse_obj(universal_data
, ('webapp.video-detail', 'statusCode', {int}
)) or 0
770 video_data
= traverse_obj(universal_data
, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict}
))
772 elif sigi_data
:= self
._get
_sigi
_state
(webpage
, video_id
):
773 self
.write_debug('Found sigi state data')
774 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode', {int}
)) or 0
775 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
, {dict}
))
777 elif next_data
:= self
._search
_nextjs
_data
(webpage
, video_id
, default
={}):
778 self
.write_debug('Found next.js data')
779 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode', {int}
)) or 0
780 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict}
))
783 raise ExtractorError('Unable to extract webpage video data')
785 if video_data
and status
== 0:
786 return self
._parse
_aweme
_video
_web
(video_data
, url
, video_id
)
787 elif status
== 10216:
788 raise ExtractorError('This video is private', expected
=True)
789 raise ExtractorError(f
'Video not available, status code {status}', video_id
=video_id
)
792 class TikTokUserIE(TikTokBaseIE
):
793 IE_NAME
= 'tiktok:user'
794 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
797 'url': 'https://tiktok.com/@corgibobaa?lang=en',
798 'playlist_mincount': 45,
800 'id': '6935371178089399301',
801 'title': 'corgibobaa',
802 'thumbnail': r
're:https://.+_1080x1080\.webp'
804 'expected_warnings': ['Retrying']
806 'url': 'https://www.tiktok.com/@6820838815978423302',
807 'playlist_mincount': 5,
809 'id': '6820838815978423302',
810 'title': '6820838815978423302',
811 'thumbnail': r
're:https://.+_1080x1080\.webp'
813 'expected_warnings': ['Retrying']
815 'url': 'https://www.tiktok.com/@meme',
816 'playlist_mincount': 593,
818 'id': '79005827461758976',
820 'thumbnail': r
're:https://.+_1080x1080\.webp'
822 'expected_warnings': ['Retrying']
825 r
''' # TODO: Fix by adding _signature to api_url
826 def _entries(self, webpage, user_id, username):
827 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
828 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
829 if not verifyfp_cookie:
830 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
831 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='
833 for page in itertools.count():
834 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
835 for video in data_json.get('itemList', []):
836 video_id = video['id']
837 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
838 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
839 if not data_json.get('hasMore'):
841 cursor = data_json['cursor']
844 def _video_entries_api(self
, webpage
, user_id
, username
):
850 'retry_type': 'no_retry',
851 '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.
854 for page
in itertools
.count(1):
855 for retry
in self
.RetryManager():
857 post_list
= self
._call
_api
(
858 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
859 errnote
='Unable to download user video list')
860 except ExtractorError
as e
:
861 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
865 yield from post_list
.get('aweme_list', [])
866 if not post_list
.get('has_more'):
868 query
['max_cursor'] = post_list
['max_cursor']
870 def _entries_api(self
, user_id
, videos
):
873 **self
._parse
_aweme
_video
_app
(video
),
874 'extractor_key': TikTokIE
.ie_key(),
875 'extractor': 'TikTok',
876 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
879 def _real_extract(self
, url
):
880 user_name
= self
._match
_id
(url
)
881 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
882 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
884 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
886 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
887 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
889 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
892 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
893 def _entries(self
, list_id
, display_id
):
895 self
._QUERY
_NAME
: list_id
,
899 'device_id': ''.join(random
.choices(string
.digits
, k
=19))
902 for page
in itertools
.count(1):
903 for retry
in self
.RetryManager():
905 post_list
= self
._call
_api
(
906 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
907 errnote
='Unable to download video list')
908 except ExtractorError
as e
:
909 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
913 for video
in post_list
.get('aweme_list', []):
915 **self
._parse
_aweme
_video
_app
(video
),
916 'extractor_key': TikTokIE
.ie_key(),
917 'extractor': 'TikTok',
918 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
920 if not post_list
.get('has_more'):
922 query
['cursor'] = post_list
['cursor']
924 def _real_extract(self
, url
):
925 list_id
= self
._match
_id
(url
)
926 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
929 class TikTokSoundIE(TikTokBaseListIE
):
930 IE_NAME
= 'tiktok:sound'
931 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
933 _QUERY_NAME
= 'music_id'
934 _API_ENDPOINT
= 'music/aweme'
936 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
937 'playlist_mincount': 100,
939 'id': '6956990112127585029'
941 'expected_warnings': ['Retrying']
943 # Actual entries are less than listed video count
944 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
945 'playlist_mincount': 2182,
947 'id': '7036843036118469381'
949 'expected_warnings': ['Retrying']
953 class TikTokEffectIE(TikTokBaseListIE
):
954 IE_NAME
= 'tiktok:effect'
955 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
957 _QUERY_NAME
= 'sticker_id'
958 _API_ENDPOINT
= 'sticker/aweme'
960 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
961 'playlist_mincount': 100,
965 'expected_warnings': ['Retrying']
967 # Different entries between mobile and web, depending on region
968 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
969 'only_matching': True
973 class TikTokTagIE(TikTokBaseListIE
):
974 IE_NAME
= 'tiktok:tag'
975 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
977 _QUERY_NAME
= 'ch_id'
978 _API_ENDPOINT
= 'challenge/aweme'
980 'url': 'https://tiktok.com/tag/hello2018',
981 'playlist_mincount': 39,
984 'title': 'hello2018',
986 'expected_warnings': ['Retrying']
988 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
989 'only_matching': True
992 def _real_extract(self
, url
):
993 display_id
= self
._match
_id
(url
)
994 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
995 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
997 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
998 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
1001 class DouyinIE(TikTokBaseIE
):
1002 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
1004 'url': 'https://www.douyin.com/video/6961737553342991651',
1005 'md5': '9ecce7bc5b302601018ecb2871c63a75',
1007 'id': '6961737553342991651',
1009 'title': '#杨超越 小小水手带你去远航❤️',
1010 'description': '#杨超越 小小水手带你去远航❤️',
1011 'uploader': '6897520xka',
1012 'uploader_id': '110403406559',
1013 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1014 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1016 'creators': ['杨超越'],
1018 'timestamp': 1620905839,
1019 'upload_date': '20210513',
1020 'track': '@杨超越创作的原声',
1024 'repost_count': int,
1025 'comment_count': int,
1026 'thumbnail': r
're:https?://.+\.jpe?g',
1029 'url': 'https://www.douyin.com/video/6982497745948921092',
1030 'md5': '15c5e660b7048af3707304e3cc02bbb5',
1032 'id': '6982497745948921092',
1034 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1035 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
1036 'uploader': '0731chaoyue',
1037 'uploader_id': '408654318141572',
1038 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1039 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
1040 'channel': '杨超越工作室',
1041 'creators': ['杨超越工作室'],
1043 'timestamp': 1625739481,
1044 'upload_date': '20210708',
1045 'track': '@杨超越工作室创作的原声',
1046 'artists': ['杨超越工作室'],
1049 'repost_count': int,
1050 'comment_count': int,
1051 'thumbnail': r
're:https?://.+\.jpe?g',
1054 'url': 'https://www.douyin.com/video/6953975910773099811',
1055 'md5': '0e6443758b8355db9a3c34864a4276be',
1057 'id': '6953975910773099811',
1059 'title': '#一起看海 出现在你的夏日里',
1060 'description': '#一起看海 出现在你的夏日里',
1061 'uploader': '6897520xka',
1062 'uploader_id': '110403406559',
1063 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1064 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1066 'creators': ['杨超越'],
1068 'timestamp': 1619098692,
1069 'upload_date': '20210422',
1070 'track': '@杨超越创作的原声',
1074 'repost_count': int,
1075 'comment_count': int,
1076 'thumbnail': r
're:https?://.+\.jpe?g',
1079 'url': 'https://www.douyin.com/video/6950251282489675042',
1080 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
1082 'id': '6950251282489675042',
1084 'title': '哈哈哈,成功了哈哈哈哈哈哈',
1086 'upload_date': '20210412',
1087 'timestamp': 1618231483,
1088 'uploader_id': '110403406559',
1091 'repost_count': int,
1092 'comment_count': int,
1094 'skip': 'No longer available',
1096 'url': 'https://www.douyin.com/video/6963263655114722595',
1097 'md5': '1440bcf59d8700f8e014da073a4dfea8',
1099 'id': '6963263655114722595',
1101 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1102 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
1103 'uploader': '6897520xka',
1104 'uploader_id': '110403406559',
1105 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1106 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
1108 'creators': ['杨超越'],
1110 'timestamp': 1621261163,
1111 'upload_date': '20210517',
1112 'track': '@杨超越创作的原声',
1116 'repost_count': int,
1117 'comment_count': int,
1118 'thumbnail': r
're:https?://.+\.jpe?g',
1121 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
1122 _WEBPAGE_HOST
= 'https://www.douyin.com/'
1124 def _real_extract(self
, url
):
1125 video_id
= self
._match
_id
(url
)
1127 detail
= traverse_obj(self
._download
_json
(
1128 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id
,
1129 'Downloading web detail JSON', 'Failed to download web detail JSON',
1130 query
={'aweme_id': video_id}
, fatal
=False), ('aweme_detail', {dict}
))
1132 # TODO: Run verification challenge code to generate signature cookies
1133 raise ExtractorError(
1134 'Fresh cookies (not necessarily logged in) are needed',
1135 expected
=not self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('s_v_web_id'))
1137 return self
._parse
_aweme
_video
_app
(detail
)
1140 class TikTokVMIE(InfoExtractor
):
1141 _VALID_URL
= r
'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)'
1142 IE_NAME
= 'vm.tiktok'
1145 'url': 'https://www.tiktok.com/t/ZTRC5xgJp',
1147 'id': '7170520270497680683',
1149 'title': 'md5:c64f6152330c2efe98093ccc8597871c',
1150 'uploader_id': '6687535061741700102',
1151 'upload_date': '20221127',
1154 'comment_count': int,
1155 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
1156 'album': 'Wave of Mutilation: Best of Pixies',
1157 'thumbnail': r
're:https://.+\.webp.*',
1159 'timestamp': 1669516858,
1160 'repost_count': int,
1162 'track': 'Where Is My Mind?',
1163 'description': 'md5:c64f6152330c2efe98093ccc8597871c',
1164 'uploader': 'sigmachaddeus',
1165 'creator': 'SigmaChad',
1168 'url': 'https://vm.tiktok.com/ZTR45GpSF/',
1170 'id': '7106798200794926362',
1172 'title': 'md5:edc3e7ea587847f8537468f2fe51d074',
1173 'uploader_id': '6997695878846268418',
1174 'upload_date': '20220608',
1177 'comment_count': int,
1178 'thumbnail': r
're:https://.+\.webp.*',
1179 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
1181 'timestamp': 1654680400,
1182 'repost_count': int,
1183 'artist': 'Akihitoko',
1184 'track': 'original sound',
1185 'description': 'md5:edc3e7ea587847f8537468f2fe51d074',
1186 'uploader': 'akihitoko1',
1187 'creator': 'Akihitoko',
1190 'url': 'https://vt.tiktok.com/ZSe4FqkKd',
1191 'only_matching': True,
1194 def _real_extract(self
, url
):
1195 new_url
= self
._request
_webpage
(
1196 HEADRequest(url
), self
._match
_id
(url
), headers
={'User-Agent': 'facebookexternalhit/1.1'}
).url
1197 if self
.suitable(new_url
): # Prevent infinite loop in case redirect fails
1198 raise UnsupportedError(new_url
)
1199 return self
.url_result(new_url
)
1202 class TikTokLiveIE(TikTokBaseIE
):
1203 _VALID_URL
= r
'''(?x)https?://(?:
1204 (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live|
1205 m\.tiktok\.com/share/live/(?P<id>\d+)
1207 IE_NAME
= 'tiktok:live'
1210 'url': 'https://www.tiktok.com/@weathernewslive/live',
1212 'id': '7210809319192726273',
1214 'title': r
're:ウェザーニュースLiVE[\d\s:-]*',
1215 'creator': 'ウェザーニュースLiVE',
1216 'uploader': 'weathernewslive',
1217 'uploader_id': '6621496731283095554',
1218 'uploader_url': 'https://www.tiktok.com/@weathernewslive',
1219 'live_status': 'is_live',
1220 'concurrent_view_count': int,
1222 'params': {'skip_download': 'm3u8'}
,
1224 'url': 'https://www.tiktok.com/@pilarmagenta/live',
1226 'id': '7209423610325322522',
1229 'creator': 'Pilarmagenta',
1230 'uploader': 'pilarmagenta',
1231 'uploader_id': '6624846890674683909',
1232 'uploader_url': 'https://www.tiktok.com/@pilarmagenta',
1233 'live_status': 'is_live',
1234 'concurrent_view_count': int,
1236 'skip': 'Livestream',
1238 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en',
1239 'only_matching': True,
1241 'url': 'https://www.tiktok.com/@iris04201/live',
1242 'only_matching': True,
1245 def _call_api(self
, url
, param
, room_id
, uploader
, key
=None):
1246 response
= traverse_obj(self
._download
_json
(
1247 url
, room_id
, fatal
=False, query
={
1250 }), (key
, {dict}
), default
={})
1252 # status == 2 if live else 4
1253 if int_or_none(response
.get('status')) == 2:
1255 # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live
1257 raise ExtractorError('This livestream has ended', expected
=True)
1258 raise UserNotLive(video_id
=uploader
)
1260 def _real_extract(self
, url
):
1261 uploader
, room_id
= self
._match
_valid
_url
(url
).group('uploader', 'id')
1262 webpage
= self
._download
_webpage
(
1263 url
, uploader
or room_id
, headers
={'User-Agent': 'Mozilla/5.0'}
, fatal
=not room_id
)
1266 data
= self
._get
_sigi
_state
(webpage
, uploader
or room_id
)
1267 room_id
= (traverse_obj(data
, ('UserModule', 'users', ..., 'roomId', {str_or_none}
), get_all
=False)
1268 or self
._search
_regex
(r
'snssdk\d*://live\?room_id=(\d+)', webpage
, 'room ID', default
=None)
1270 uploader
= uploader
or traverse_obj(
1271 data
, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'),
1272 ('UserModule', 'users', ..., 'uniqueId'), get_all
=False, expected_type
=str)
1275 raise UserNotLive(video_id
=uploader
)
1278 live_info
= self
._call
_api
(
1279 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id
, uploader
, key
='data')
1281 get_quality
= qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin'))
1282 parse_inner
= lambda x
: self
._parse
_json
(x
, None)
1284 for quality
, stream
in traverse_obj(live_info
, (
1285 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data',
1286 {parse_inner}
, 'data', {dict}
), default
={}).items():
1288 sdk_params
= traverse_obj(stream
, ('main', 'sdk_params', {parse_inner}
, {
1289 'vcodec': ('VCodec', {str}
),
1290 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}
),
1291 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}
),
1294 flv_url
= traverse_obj(stream
, ('main', 'flv', {url_or_none}
))
1299 'format_id': f
'flv-{quality}',
1300 'quality': get_quality(quality
),
1304 hls_url
= traverse_obj(stream
, ('main', 'hls', {url_or_none}
))
1309 'protocol': 'm3u8_native',
1310 'format_id': f
'hls-{quality}',
1311 'quality': get_quality(quality
),
1315 def get_vcodec(*keys
):
1316 return traverse_obj(live_info
, (
1317 'stream_url', *keys
, {parse_inner}
, 'VCodec', {str}
))
1319 for stream
in ('hls', 'rtmp'):
1320 stream_url
= traverse_obj(live_info
, ('stream_url', f
'{stream}_pull_url', {url_or_none}
))
1324 'ext': 'mp4' if stream
== 'hls' else 'flv',
1325 'protocol': 'm3u8_native' if stream
== 'hls' else 'https',
1326 'format_id': f
'{stream}-pull',
1327 'vcodec': get_vcodec(f
'{stream}_pull_url_params'),
1328 'quality': get_quality('ORIGION'),
1331 for f_id
, f_url
in traverse_obj(live_info
, ('stream_url', 'flv_pull_url', {dict}
), default
={}).items():
1332 if not url_or_none(f_url
):
1337 'format_id': f
'flv-{f_id}'.lower(),
1338 'vcodec': get_vcodec('flv_pull_url_params', f_id
),
1339 'quality': get_quality(f_id
),
1342 # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs
1343 if not traverse_obj(formats
, lambda _
, v
: v
['ext'] == 'mp4'):
1344 live_info
= merge_dicts(live_info
, self
._call
_api
(
1345 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id
, uploader
, key
='LiveRoomInfo'))
1346 if url_or_none(live_info
.get('liveUrl')):
1348 'url': live_info
['liveUrl'],
1350 'protocol': 'm3u8_native',
1351 'format_id': 'hls-fallback',
1353 'quality': get_quality('origin'),
1356 uploader
= uploader
or traverse_obj(live_info
, ('ownerInfo', 'uniqueId'), ('owner', 'display_id'))
1360 'uploader': uploader
,
1361 'uploader_url': format_field(uploader
, None, self
._UPLOADER
_URL
_FORMAT
) or None,
1364 '_format_sort_fields': ('quality', 'ext'),
1365 **traverse_obj(live_info
, {
1367 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}
),
1368 'creator': (('ownerInfo', 'owner'), 'nickname'),
1369 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}
),