7 from .common
import InfoExtractor
8 from ..compat
import compat_urllib_parse_unquote
, compat_urllib_parse_urlparse
20 srt_subtitles_timecode
,
28 class TikTokBaseIE(InfoExtractor
):
29 _APP_VERSIONS
= [('26.1.3', '260103'), ('26.1.2', '260102'), ('26.1.1', '260101'), ('25.6.2', '250602')]
30 _WORKING_APP_VERSION
= None
33 _API_HOSTNAME
= 'api16-normal-c-useast1a.tiktokv.com'
34 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
35 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
36 QUALITIES
= ('360p', '540p', '720p', '1080p')
39 def _create_url(user_id
, video_id
):
40 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
42 def _get_sigi_state(self
, webpage
, display_id
):
43 return self
._parse
_json
(get_element_by_id(
44 'SIGI_STATE|sigi-persisted-data', webpage
, escape_value
=False), display_id
)
46 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
47 note
='Downloading API JSON', errnote
='Unable to download API page'):
48 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choice('0123456789abcdef') for _
in range(160)))
49 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
50 if webpage_cookies
.get('sid_tt'):
51 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
52 return self
._download
_json
(
53 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
54 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
55 'User-Agent': f
'com.ss.android.ugc.{self._APP_NAME}/{manifest_app_version} (Linux; U; Android 10; en_US; Pixel 4; Build/QQ3A.200805.001; Cronet/58.0.2991.0)',
56 'Accept': 'application/json',
59 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
62 'version_name': app_version
,
63 'version_code': manifest_app_version
,
64 'build_number': app_version
,
65 'manifest_version_code': manifest_app_version
,
66 'update_version_code': manifest_app_version
,
67 'openudid': ''.join(random
.choice('0123456789abcdef') for _
in range(16)),
68 'uuid': ''.join([random
.choice(string
.digits
) for _
in range(16)]),
69 '_rticket': int(time
.time() * 1000),
70 'ts': int(time
.time()),
71 'device_brand': 'Google',
72 'device_type': 'Pixel 4',
73 'device_platform': 'android',
74 'resolution': '1080*1920',
78 'carrier_region': 'US',
81 'app_name': self
._APP
_NAME
,
84 'timezone_name': 'America/New_York',
85 'timezone_offset': '-14400',
86 'channel': 'googleplay',
93 'cp': 'cbfhckdckkde1',
96 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
97 note
='Downloading API JSON', errnote
='Unable to download API page'):
98 if not self
._WORKING
_APP
_VERSION
:
99 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
100 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
101 if app_version
and manifest_app_version
:
102 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
103 self
.write_debug('Imported app version combo from extractor arguments')
104 elif app_version
or manifest_app_version
:
105 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
107 if self
._WORKING
_APP
_VERSION
:
108 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
109 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
110 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
112 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
113 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
115 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
116 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
118 except ExtractorError
as e
:
119 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
120 if count
== len(self
._APP
_VERSIONS
):
124 self
.report_warning(str(e
.cause
or e
.msg
))
126 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
130 def _extract_aweme_app(self
, aweme_id
):
131 feed_list
= self
._call
_api
(
132 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
133 errnote
='Unable to download video feed').get('aweme_list') or []
134 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
136 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
137 return self
._parse
_aweme
_video
_app
(aweme_detail
)
139 def _get_subtitles(self
, aweme_detail
, aweme_id
):
140 # TODO: Extract text positioning info
142 # aweme/detail endpoint subs
143 captions_info
= traverse_obj(
144 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
145 for caption
in captions_info
:
146 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
149 caption_json
= self
._download
_json
(
150 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
153 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
156 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
157 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
161 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
162 if not caption
.get('url'):
164 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
165 'ext': remove_start(caption
.get('caption_format'), 'web'),
166 'url': caption
['url'],
170 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', ...), expected_type
=dict):
171 if not caption
.get('Url'):
173 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
174 'ext': remove_start(caption
.get('Format'), 'web'),
175 'url': caption
['Url'],
179 def _parse_aweme_video_app(self
, aweme_detail
):
180 aweme_id
= aweme_detail
['aweme_id']
181 video_info
= aweme_detail
['video']
183 def parse_url_key(url_key
):
184 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
185 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
186 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
190 'format_id': format_id
,
191 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
192 'tbr': int_or_none(bitrate
, scale
=1000) or None,
193 'quality': qualities(self
.QUALITIES
)(res
),
196 known_resolutions
= {}
198 def extract_addr(addr
, add_meta
={}):
199 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
201 known_resolutions
.setdefault(res
, {}).setdefault('height', add_meta
.get('height'))
202 known_resolutions
[res
].setdefault('width', add_meta
.get('width'))
203 parsed_meta
.update(known_resolutions
.get(res
, {}))
204 add_meta
.setdefault('height', int_or_none(res
[:-1]))
207 'filesize': int_or_none(addr
.get('data_size')),
210 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
211 **add_meta
, **parsed_meta
,
212 'format_note': join_nonempty(
213 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' ')
214 } for url
in addr
.get('url_list') or []]
216 # Hack: Add direct video links first to prioritize them when removing duplicate formats
218 if video_info
.get('play_addr'):
219 formats
.extend(extract_addr(video_info
['play_addr'], {
220 'format_id': 'play_addr',
221 'format_note': 'Direct video',
222 'vcodec': 'h265' if traverse_obj(
223 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
224 'width': video_info
.get('width'),
225 'height': video_info
.get('height'),
227 if video_info
.get('download_addr'):
228 formats
.extend(extract_addr(video_info
['download_addr'], {
229 'format_id': 'download_addr',
230 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
232 'width': video_info
.get('width'),
233 'height': video_info
.get('height'),
234 'preference': -2 if video_info
.get('has_watermark') else -1,
236 if video_info
.get('play_addr_h264'):
237 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
238 'format_id': 'play_addr_h264',
239 'format_note': 'Direct video',
242 if video_info
.get('play_addr_bytevc1'):
243 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
244 'format_id': 'play_addr_bytevc1',
245 'format_note': 'Direct video',
249 for bitrate
in video_info
.get('bit_rate', []):
250 if bitrate
.get('play_addr'):
251 formats
.extend(extract_addr(bitrate
['play_addr'], {
252 'format_id': bitrate
.get('gear_name'),
253 'format_note': 'Playback video',
254 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
255 'vcodec': 'h265' if traverse_obj(
256 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
257 'fps': bitrate
.get('FPS'),
260 self
._remove
_duplicate
_formats
(formats
)
261 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
264 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
267 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
268 'origin_cover', 'dynamic_cover'):
269 cover
= video_info
.get(cover_id
)
271 for cover_url
in cover
['url_list']:
277 stats_info
= aweme_detail
.get('statistics', {})
278 author_info
= aweme_detail
.get('author', {})
279 music_info
= aweme_detail
.get('music', {})
280 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
281 'sec_uid', 'id', 'uid', 'unique_id',
282 expected_type
=str_or_none
, get_all
=False))
283 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str, default
=[])
285 contained_music_track
= traverse_obj(
286 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
287 contained_music_author
= traverse_obj(
288 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
290 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
291 if is_generic_og_trackname
:
292 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
294 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
298 'extractor_key': TikTokIE
.ie_key(),
299 'extractor': TikTokIE
.IE_NAME
,
300 'webpage_url': self
._create
_url
(author_info
.get('uid'), aweme_id
),
301 'title': aweme_detail
.get('desc'),
302 'description': aweme_detail
.get('desc'),
303 'view_count': int_or_none(stats_info
.get('play_count')),
304 'like_count': int_or_none(stats_info
.get('digg_count')),
305 'repost_count': int_or_none(stats_info
.get('share_count')),
306 'comment_count': int_or_none(stats_info
.get('comment_count')),
307 'uploader': str_or_none(author_info
.get('unique_id')),
308 'creator': str_or_none(author_info
.get('nickname')),
309 'uploader_id': str_or_none(author_info
.get('uid')),
310 'uploader_url': user_url
,
311 'track': music_track
,
312 'album': str_or_none(music_info
.get('album')) or None,
313 'artist': music_author
or None,
314 'timestamp': int_or_none(aweme_detail
.get('create_time')),
316 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
317 'thumbnails': thumbnails
,
318 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
319 'availability': self
._availability
(
320 is_private
='Private' in labels
,
321 needs_subscription
='Friends only' in labels
,
322 is_unlisted
='Followers only' in labels
),
323 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
326 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
):
327 video_info
= aweme_detail
['video']
328 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
329 music_info
= aweme_detail
.get('music') or {}
330 stats_info
= aweme_detail
.get('stats') or {}
331 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
332 'secUid', 'id', 'uid', 'uniqueId',
333 expected_type
=str_or_none
, get_all
=False)
334 or aweme_detail
.get('authorSecId'))
337 play_url
= video_info
.get('playAddr')
338 width
= video_info
.get('width')
339 height
= video_info
.get('height')
340 if isinstance(play_url
, str):
342 'url': self
._proto
_relative
_url
(play_url
),
347 elif isinstance(play_url
, list):
349 'url': self
._proto
_relative
_url
(url
),
353 } for url
in traverse_obj(play_url
, (..., 'src'), expected_type
=url_or_none
, default
=[]) if url
]
355 download_url
= url_or_none(video_info
.get('downloadAddr')) or traverse_obj(video_info
, ('download', 'url'), expected_type
=url_or_none
)
358 'format_id': 'download',
359 'url': self
._proto
_relative
_url
(download_url
),
364 self
._remove
_duplicate
_formats
(formats
)
367 for thumbnail_name
in ('thumbnail', 'cover', 'dynamicCover', 'originCover'):
368 if aweme_detail
.get(thumbnail_name
):
370 'url': self
._proto
_relative
_url
(aweme_detail
[thumbnail_name
]),
376 'id': traverse_obj(aweme_detail
, 'id', 'awemeId', expected_type
=str_or_none
),
377 'title': aweme_detail
.get('desc'),
378 'duration': try_get(aweme_detail
, lambda x
: x
['video']['duration'], int),
379 'view_count': int_or_none(stats_info
.get('playCount')),
380 'like_count': int_or_none(stats_info
.get('diggCount')),
381 'repost_count': int_or_none(stats_info
.get('shareCount')),
382 'comment_count': int_or_none(stats_info
.get('commentCount')),
383 'timestamp': int_or_none(aweme_detail
.get('createTime')),
384 'creator': str_or_none(author_info
.get('nickname')),
385 'uploader': str_or_none(author_info
.get('uniqueId') or aweme_detail
.get('author')),
386 'uploader_id': str_or_none(traverse_obj(author_info
, 'id', 'uid', 'authorId')),
387 'uploader_url': user_url
,
388 'track': str_or_none(music_info
.get('title')),
389 'album': str_or_none(music_info
.get('album')) or None,
390 'artist': str_or_none(music_info
.get('authorName')),
392 'thumbnails': thumbnails
,
393 'description': str_or_none(aweme_detail
.get('desc')),
395 'Referer': webpage_url
400 class TikTokIE(TikTokBaseIE
):
401 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)/video)/(?P<id>\d+)'
402 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
405 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
406 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
408 'id': '6748451240264420610',
410 'title': '#jassmanak #lehanga #leenabhushan',
411 'description': '#jassmanak #lehanga #leenabhushan',
415 'uploader': 'leenabhushan',
416 'uploader_id': '6691488002098119685',
417 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
418 'creator': 'facestoriesbyleenabh',
419 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
420 'upload_date': '20191016',
421 'timestamp': 1571246252,
425 'comment_count': int,
426 'artist': 'Ysrbeats',
431 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
432 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
434 'id': '6742501081818877190',
436 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
437 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
441 'uploader': 'patrox',
442 'uploader_id': '18702747',
443 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
445 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
446 'upload_date': '20190930',
447 'timestamp': 1569860870,
451 'comment_count': int,
452 'artist': 'Evan Todd, Jessica Keenan Wynn, Alice Lee, Barrett Wilbert Weed & Jon Eidson',
456 # Banned audio, only available on the app
457 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
459 'id': '6984138651336838402',
461 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
462 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
463 'uploader': 'barudakhb_',
464 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
465 'uploader_id': '6974687867511718913',
466 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
467 'track': 'Boka Dance',
468 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
469 'timestamp': 1626121503,
471 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
472 'upload_date': '20210712',
476 'comment_count': int,
479 # Sponsored video, only available with feed workaround
480 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
482 'id': '7042692929109986561',
484 'title': 'Slap and Run!',
485 'description': 'Slap and Run!',
486 'uploader': 'user440922249',
487 'creator': 'Slap And Run',
488 'uploader_id': '7036055384943690754',
489 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
490 'track': 'Promoted Music',
491 'timestamp': 1639754738,
493 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
494 'upload_date': '20211217',
498 'comment_count': int,
500 'expected_warnings': ['trying with webpage', 'Unable to find video in feed']
502 # Video without title and description
503 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
505 'id': '7059698374567611694',
507 'title': 'TikTok video #7059698374567611694',
509 'uploader': 'pokemonlife22',
510 'creator': 'Pokemon',
511 'uploader_id': '6820838815978423302',
512 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
513 'track': 'original sound',
514 'timestamp': 1643714123,
516 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
517 'upload_date': '20220201',
522 'comment_count': int,
525 # hydration JSON is sent in a <script> element
526 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
528 'id': '7065799023130643713',
530 'title': '#denidil#денидил',
531 'description': '#denidil#денидил',
532 'uploader': 'denidil6',
533 'uploader_id': '7046664115636405250',
534 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
535 'artist': 'Holocron Music',
536 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
537 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
538 'timestamp': 1645134536,
540 'upload_date': '20220217',
544 'comment_count': int,
546 'skip': 'This video is unavailable',
548 # Auto-captions available
549 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
550 'only_matching': True
553 def _real_extract(self
, url
):
554 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
556 return self
._extract
_aweme
_app
(video_id
)
557 except ExtractorError
as e
:
558 self
.report_warning(f
'{e}; trying with webpage')
560 url
= self
._create
_url
(user_id
, video_id
)
561 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'User-Agent:Mozilla/5.0'}
)
562 next_data
= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}')
564 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode'), expected_type
=int) or 0
565 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type
=dict)
567 sigi_data
= self
._get
_sigi
_state
(webpage
, video_id
)
568 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode'), expected_type
=int) or 0
569 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
), expected_type
=dict)
572 return self
._parse
_aweme
_video
_web
(video_data
, url
)
573 elif status
== 10216:
574 raise ExtractorError('This video is private', expected
=True)
575 raise ExtractorError('Video not available', video_id
=video_id
)
578 class TikTokUserIE(TikTokBaseIE
):
579 IE_NAME
= 'tiktok:user'
580 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
583 'url': 'https://tiktok.com/@corgibobaa?lang=en',
584 'playlist_mincount': 45,
586 'id': '6935371178089399301',
587 'title': 'corgibobaa',
588 'thumbnail': r
're:https://.+_1080x1080\.webp'
590 'expected_warnings': ['Retrying']
592 'url': 'https://www.tiktok.com/@6820838815978423302',
593 'playlist_mincount': 5,
595 'id': '6820838815978423302',
596 'title': '6820838815978423302',
597 'thumbnail': r
're:https://.+_1080x1080\.webp'
599 'expected_warnings': ['Retrying']
601 'url': 'https://www.tiktok.com/@meme',
602 'playlist_mincount': 593,
604 'id': '79005827461758976',
606 'thumbnail': r
're:https://.+_1080x1080\.webp'
608 'expected_warnings': ['Retrying']
611 r
''' # TODO: Fix by adding _signature to api_url
612 def _entries(self, webpage, user_id, username):
613 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
614 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
615 if not verifyfp_cookie:
616 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
617 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='
619 for page in itertools.count():
620 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
621 for video in data_json.get('itemList', []):
622 video_id = video['id']
623 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
624 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
625 if not data_json.get('hasMore'):
627 cursor = data_json['cursor']
630 def _video_entries_api(self
, webpage
, user_id
, username
):
636 'retry_type': 'no_retry',
637 'device_id': ''.join(random
.choice(string
.digits
) for _
in range(19)), # Some endpoints don't like randomized device_id, so it isn't directly set in _call_api.
640 for page
in itertools
.count(1):
641 for retry
in self
.RetryManager():
643 post_list
= self
._call
_api
(
644 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
645 errnote
='Unable to download user video list')
646 except ExtractorError
as e
:
647 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
651 yield from post_list
.get('aweme_list', [])
652 if not post_list
.get('has_more'):
654 query
['max_cursor'] = post_list
['max_cursor']
656 def _entries_api(self
, user_id
, videos
):
659 **self
._parse
_aweme
_video
_app
(video
),
660 'extractor_key': TikTokIE
.ie_key(),
661 'extractor': 'TikTok',
662 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
665 def _real_extract(self
, url
):
666 user_name
= self
._match
_id
(url
)
667 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
668 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
670 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
672 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
673 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
675 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
678 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
679 def _entries(self
, list_id
, display_id
):
681 self
._QUERY
_NAME
: list_id
,
685 'device_id': ''.join(random
.choice(string
.digits
) for i
in range(19))
688 for page
in itertools
.count(1):
689 for retry
in self
.RetryManager():
691 post_list
= self
._call
_api
(
692 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
693 errnote
='Unable to download video list')
694 except ExtractorError
as e
:
695 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
699 for video
in post_list
.get('aweme_list', []):
701 **self
._parse
_aweme
_video
_app
(video
),
702 'extractor_key': TikTokIE
.ie_key(),
703 'extractor': 'TikTok',
704 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
706 if not post_list
.get('has_more'):
708 query
['cursor'] = post_list
['cursor']
710 def _real_extract(self
, url
):
711 list_id
= self
._match
_id
(url
)
712 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
715 class TikTokSoundIE(TikTokBaseListIE
):
716 IE_NAME
= 'tiktok:sound'
717 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
719 _QUERY_NAME
= 'music_id'
720 _API_ENDPOINT
= 'music/aweme'
722 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
723 'playlist_mincount': 100,
725 'id': '6956990112127585029'
727 'expected_warnings': ['Retrying']
729 # Actual entries are less than listed video count
730 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
731 'playlist_mincount': 2182,
733 'id': '7036843036118469381'
735 'expected_warnings': ['Retrying']
739 class TikTokEffectIE(TikTokBaseListIE
):
740 IE_NAME
= 'tiktok:effect'
741 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
743 _QUERY_NAME
= 'sticker_id'
744 _API_ENDPOINT
= 'sticker/aweme'
746 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
747 'playlist_mincount': 100,
751 'expected_warnings': ['Retrying']
753 # Different entries between mobile and web, depending on region
754 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
755 'only_matching': True
759 class TikTokTagIE(TikTokBaseListIE
):
760 IE_NAME
= 'tiktok:tag'
761 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
763 _QUERY_NAME
= 'ch_id'
764 _API_ENDPOINT
= 'challenge/aweme'
766 'url': 'https://tiktok.com/tag/hello2018',
767 'playlist_mincount': 39,
770 'title': 'hello2018',
772 'expected_warnings': ['Retrying']
774 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
775 'only_matching': True
778 def _real_extract(self
, url
):
779 display_id
= self
._match
_id
(url
)
780 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
781 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
783 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
784 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
787 class DouyinIE(TikTokBaseIE
):
788 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
790 'url': 'https://www.douyin.com/video/6961737553342991651',
791 'md5': 'a97db7e3e67eb57bf40735c022ffa228',
793 'id': '6961737553342991651',
795 'title': '#杨超越 小小水手带你去远航❤️',
796 'description': '#杨超越 小小水手带你去远航❤️',
797 'uploader_id': '110403406559',
798 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
801 'timestamp': 1620905839,
802 'upload_date': '20210513',
803 'track': '@杨超越创作的原声',
807 'comment_count': int,
810 'url': 'https://www.douyin.com/video/6982497745948921092',
811 'md5': '34a87ebff3833357733da3fe17e37c0e',
813 'id': '6982497745948921092',
815 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
816 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
817 'uploader_id': '408654318141572',
818 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
821 'timestamp': 1625739481,
822 'upload_date': '20210708',
823 'track': '@杨超越工作室创作的原声',
827 'comment_count': int,
830 'url': 'https://www.douyin.com/video/6953975910773099811',
831 'md5': 'dde3302460f19db59c47060ff013b902',
833 'id': '6953975910773099811',
835 'title': '#一起看海 出现在你的夏日里',
836 'description': '#一起看海 出现在你的夏日里',
837 'uploader_id': '110403406559',
838 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
841 'timestamp': 1619098692,
842 'upload_date': '20210422',
843 'track': '@杨超越创作的原声',
847 'comment_count': int,
850 'url': 'https://www.douyin.com/video/6950251282489675042',
851 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
853 'id': '6950251282489675042',
855 'title': '哈哈哈,成功了哈哈哈哈哈哈',
857 'upload_date': '20210412',
858 'timestamp': 1618231483,
859 'uploader_id': '110403406559',
863 'comment_count': int,
865 'skip': 'No longer available',
867 'url': 'https://www.douyin.com/video/6963263655114722595',
868 'md5': 'cf9f11f0ec45d131445ec2f06766e122',
870 'id': '6963263655114722595',
872 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
873 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
874 'uploader_id': '110403406559',
875 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
878 'timestamp': 1621261163,
879 'upload_date': '20210517',
880 'track': '@杨超越创作的原声',
884 'comment_count': int,
887 _APP_VERSIONS
= [('23.3.0', '230300')]
890 _API_HOSTNAME
= 'aweme.snssdk.com'
891 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
892 _WEBPAGE_HOST
= 'https://www.douyin.com/'
894 def _real_extract(self
, url
):
895 video_id
= self
._match
_id
(url
)
898 return self
._extract
_aweme
_app
(video_id
)
899 except ExtractorError
as e
:
901 self
.to_screen(f
'{e}; trying with webpage')
903 webpage
= self
._download
_webpage
(url
, video_id
)
904 render_data_json
= self
._search
_regex
(
905 r
'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^
>]*>(%7B
.+%7D
)</script
>',
906 webpage, 'render data
', default=None)
907 if not render_data_json:
908 # TODO: Run verification challenge code to generate signature cookies
909 cookies = self._get_cookies(self._WEBPAGE_HOST)
910 expected = not cookies.get('s_v_web_id
') or not cookies.get('ttwid
')
911 raise ExtractorError(
912 'Fresh
cookies (not necessarily logged
in) are needed
', expected=expected)
914 render_data = self._parse_json(
915 render_data_json, video_id, transform_source=compat_urllib_parse_unquote)
916 return self._parse_aweme_video_web(get_first(render_data, ('aweme
', 'detail
')), url)
919 class TikTokVMIE(InfoExtractor):
920 _VALID_URL = r'https?
://(?
:(?
:vm|vt
)\
.tiktok\
.com|
(?
:www\
.)tiktok\
.com
/t
)/(?P
<id>\w
+)'
921 IE_NAME = 'vm
.tiktok
'
924 'url
': 'https
://www
.tiktok
.com
/t
/ZTRC5xgJp
',
926 'id': '7170520270497680683',
928 'title
': 'md5
:c64f6152330c2efe98093ccc8597871c
',
929 'uploader_id
': '6687535061741700102',
930 'upload_date
': '20221127',
933 'comment_count
': int,
934 'uploader_url
': 'https
://www
.tiktok
.com
/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
935 'album
': 'Wave of Mutilation
: Best of Pixies
',
936 'thumbnail
': r're
:https
://.+\
.webp
.*',
938 'timestamp
': 1669516858,
941 'track
': 'Where Is My Mind?
',
942 'description
': 'md5
:c64f6152330c2efe98093ccc8597871c
',
943 'uploader
': 'sigmachaddeus
',
944 'creator
': 'SigmaChad
',
947 'url
': 'https
://vm
.tiktok
.com
/ZSe4FqkKd
',
948 'only_matching
': True,
950 'url
': 'https
://vt
.tiktok
.com
/ZSe4FqkKd
',
951 'only_matching
': True,
954 def _real_extract(self, url):
955 new_url = self._request_webpage(
956 HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).geturl()
957 if self.suitable(new_url): # Prevent infinite loop in case redirect fails
958 raise UnsupportedError(new_url)
959 return self.url_result(new_url)