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 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
34 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
35 QUALITIES
= ('360p', '540p', '720p', '1080p')
38 def _API_HOSTNAME(self
):
39 return self
._configuration
_arg
(
40 'api_hostname', ['api16-normal-c-useast1a.tiktokv.com'], ie_key
=TikTokIE
)[0]
43 def _create_url(user_id
, video_id
):
44 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
46 def _get_sigi_state(self
, webpage
, display_id
):
47 return self
._parse
_json
(get_element_by_id(
48 'SIGI_STATE|sigi-persisted-data', webpage
, escape_value
=False), display_id
)
50 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
51 note
='Downloading API JSON', errnote
='Unable to download API page'):
52 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choices('0123456789abcdef', k
=160)))
53 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
54 if webpage_cookies
.get('sid_tt'):
55 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
56 return self
._download
_json
(
57 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
58 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
59 '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)',
60 'Accept': 'application/json',
63 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
66 'version_name': app_version
,
67 'version_code': manifest_app_version
,
68 'build_number': app_version
,
69 'manifest_version_code': manifest_app_version
,
70 'update_version_code': manifest_app_version
,
71 'openudid': ''.join(random
.choices('0123456789abcdef', k
=16)),
72 'uuid': ''.join(random
.choices(string
.digits
, k
=16)),
73 '_rticket': int(time
.time() * 1000),
74 'ts': int(time
.time()),
75 'device_brand': 'Google',
76 'device_type': 'Pixel 4',
77 'device_platform': 'android',
78 'resolution': '1080*1920',
82 'carrier_region': 'US',
85 'app_name': self
._APP
_NAME
,
88 'timezone_name': 'America/New_York',
89 'timezone_offset': '-14400',
90 'channel': 'googleplay',
97 'cp': 'cbfhckdckkde1',
100 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
101 note
='Downloading API JSON', errnote
='Unable to download API page'):
102 if not self
._WORKING
_APP
_VERSION
:
103 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
104 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
105 if app_version
and manifest_app_version
:
106 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
107 self
.write_debug('Imported app version combo from extractor arguments')
108 elif app_version
or manifest_app_version
:
109 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
111 if self
._WORKING
_APP
_VERSION
:
112 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
113 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
114 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
116 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
117 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
119 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
120 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
122 except ExtractorError
as e
:
123 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
124 if count
== len(self
._APP
_VERSIONS
):
128 self
.report_warning(str(e
.cause
or e
.msg
))
130 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
134 def _extract_aweme_app(self
, aweme_id
):
135 feed_list
= self
._call
_api
(
136 'feed', {'aweme_id': aweme_id}
, aweme_id
, note
='Downloading video feed',
137 errnote
='Unable to download video feed').get('aweme_list') or []
138 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
140 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
141 return self
._parse
_aweme
_video
_app
(aweme_detail
)
143 def _get_subtitles(self
, aweme_detail
, aweme_id
):
144 # TODO: Extract text positioning info
146 # aweme/detail endpoint subs
147 captions_info
= traverse_obj(
148 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict)
149 for caption
in captions_info
:
150 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
153 caption_json
= self
._download
_json
(
154 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
157 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
160 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
161 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
165 for caption
in traverse_obj(aweme_detail
, ('video', 'cla_info', 'caption_infos', ...), expected_type
=dict):
166 if not caption
.get('url'):
168 subtitles
.setdefault(caption
.get('lang') or 'en', []).append({
169 'ext': remove_start(caption
.get('caption_format'), 'web'),
170 'url': caption
['url'],
174 for caption
in traverse_obj(aweme_detail
, ('video', 'subtitleInfos', ...), expected_type
=dict):
175 if not caption
.get('Url'):
177 subtitles
.setdefault(caption
.get('LanguageCodeName') or 'en', []).append({
178 'ext': remove_start(caption
.get('Format'), 'web'),
179 'url': caption
['Url'],
183 def _parse_aweme_video_app(self
, aweme_detail
):
184 aweme_id
= aweme_detail
['aweme_id']
185 video_info
= aweme_detail
['video']
187 def parse_url_key(url_key
):
188 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
189 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
190 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
194 'format_id': format_id
,
195 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
196 'tbr': int_or_none(bitrate
, scale
=1000) or None,
197 'quality': qualities(self
.QUALITIES
)(res
),
200 known_resolutions
= {}
202 def extract_addr(addr
, add_meta
={}):
203 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
205 known_resolutions
.setdefault(res
, {}).setdefault('height', add_meta
.get('height'))
206 known_resolutions
[res
].setdefault('width', add_meta
.get('width'))
207 parsed_meta
.update(known_resolutions
.get(res
, {}))
208 add_meta
.setdefault('height', int_or_none(res
[:-1]))
211 'filesize': int_or_none(addr
.get('data_size')),
214 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
215 **add_meta
, **parsed_meta
,
216 'format_note': join_nonempty(
217 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' ')
218 } for url
in addr
.get('url_list') or []]
220 # Hack: Add direct video links first to prioritize them when removing duplicate formats
222 if video_info
.get('play_addr'):
223 formats
.extend(extract_addr(video_info
['play_addr'], {
224 'format_id': 'play_addr',
225 'format_note': 'Direct video',
226 'vcodec': 'h265' if traverse_obj(
227 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
228 'width': video_info
.get('width'),
229 'height': video_info
.get('height'),
231 if video_info
.get('download_addr'):
232 formats
.extend(extract_addr(video_info
['download_addr'], {
233 'format_id': 'download_addr',
234 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
236 'width': video_info
.get('width'),
237 'height': video_info
.get('height'),
238 'preference': -2 if video_info
.get('has_watermark') else -1,
240 if video_info
.get('play_addr_h264'):
241 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
242 'format_id': 'play_addr_h264',
243 'format_note': 'Direct video',
246 if video_info
.get('play_addr_bytevc1'):
247 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
248 'format_id': 'play_addr_bytevc1',
249 'format_note': 'Direct video',
253 for bitrate
in video_info
.get('bit_rate', []):
254 if bitrate
.get('play_addr'):
255 formats
.extend(extract_addr(bitrate
['play_addr'], {
256 'format_id': bitrate
.get('gear_name'),
257 'format_note': 'Playback video',
258 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
259 'vcodec': 'h265' if traverse_obj(
260 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
261 'fps': bitrate
.get('FPS'),
264 self
._remove
_duplicate
_formats
(formats
)
265 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
268 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
271 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
272 'origin_cover', 'dynamic_cover'):
273 cover
= video_info
.get(cover_id
)
275 for cover_url
in cover
['url_list']:
281 stats_info
= aweme_detail
.get('statistics', {})
282 author_info
= aweme_detail
.get('author', {})
283 music_info
= aweme_detail
.get('music', {})
284 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
285 'sec_uid', 'id', 'uid', 'unique_id',
286 expected_type
=str_or_none
, get_all
=False))
287 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str, default
=[])
289 contained_music_track
= traverse_obj(
290 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
291 contained_music_author
= traverse_obj(
292 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
294 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
295 if is_generic_og_trackname
:
296 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
298 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
302 'extractor_key': TikTokIE
.ie_key(),
303 'extractor': TikTokIE
.IE_NAME
,
304 'webpage_url': self
._create
_url
(author_info
.get('uid'), aweme_id
),
305 'title': aweme_detail
.get('desc'),
306 'description': aweme_detail
.get('desc'),
307 'view_count': int_or_none(stats_info
.get('play_count')),
308 'like_count': int_or_none(stats_info
.get('digg_count')),
309 'repost_count': int_or_none(stats_info
.get('share_count')),
310 'comment_count': int_or_none(stats_info
.get('comment_count')),
311 'uploader': str_or_none(author_info
.get('unique_id')),
312 'creator': str_or_none(author_info
.get('nickname')),
313 'uploader_id': str_or_none(author_info
.get('uid')),
314 'uploader_url': user_url
,
315 'track': music_track
,
316 'album': str_or_none(music_info
.get('album')) or None,
317 'artist': music_author
or None,
318 'timestamp': int_or_none(aweme_detail
.get('create_time')),
320 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
321 'thumbnails': thumbnails
,
322 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
323 'availability': self
._availability
(
324 is_private
='Private' in labels
,
325 needs_subscription
='Friends only' in labels
,
326 is_unlisted
='Followers only' in labels
),
327 '_format_sort_fields': ('quality', 'codec', 'size', 'br'),
330 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
):
331 video_info
= aweme_detail
['video']
332 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
333 music_info
= aweme_detail
.get('music') or {}
334 stats_info
= aweme_detail
.get('stats') or {}
335 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
336 'secUid', 'id', 'uid', 'uniqueId',
337 expected_type
=str_or_none
, get_all
=False)
338 or aweme_detail
.get('authorSecId'))
341 play_url
= video_info
.get('playAddr')
342 width
= video_info
.get('width')
343 height
= video_info
.get('height')
344 if isinstance(play_url
, str):
346 'url': self
._proto
_relative
_url
(play_url
),
351 elif isinstance(play_url
, list):
353 'url': self
._proto
_relative
_url
(url
),
357 } for url
in traverse_obj(play_url
, (..., 'src'), expected_type
=url_or_none
, default
=[]) if url
]
359 download_url
= url_or_none(video_info
.get('downloadAddr')) or traverse_obj(video_info
, ('download', 'url'), expected_type
=url_or_none
)
362 'format_id': 'download',
363 'url': self
._proto
_relative
_url
(download_url
),
368 self
._remove
_duplicate
_formats
(formats
)
371 for thumbnail_name
in ('thumbnail', 'cover', 'dynamicCover', 'originCover'):
372 if aweme_detail
.get(thumbnail_name
):
374 'url': self
._proto
_relative
_url
(aweme_detail
[thumbnail_name
]),
380 'id': traverse_obj(aweme_detail
, 'id', 'awemeId', expected_type
=str_or_none
),
381 'title': aweme_detail
.get('desc'),
382 'duration': try_get(aweme_detail
, lambda x
: x
['video']['duration'], int),
383 'view_count': int_or_none(stats_info
.get('playCount')),
384 'like_count': int_or_none(stats_info
.get('diggCount')),
385 'repost_count': int_or_none(stats_info
.get('shareCount')),
386 'comment_count': int_or_none(stats_info
.get('commentCount')),
387 'timestamp': int_or_none(aweme_detail
.get('createTime')),
388 'creator': str_or_none(author_info
.get('nickname')),
389 'uploader': str_or_none(author_info
.get('uniqueId') or aweme_detail
.get('author')),
390 'uploader_id': str_or_none(traverse_obj(author_info
, 'id', 'uid', 'authorId')),
391 'uploader_url': user_url
,
392 'track': str_or_none(music_info
.get('title')),
393 'album': str_or_none(music_info
.get('album')) or None,
394 'artist': str_or_none(music_info
.get('authorName')),
396 'thumbnails': thumbnails
,
397 'description': str_or_none(aweme_detail
.get('desc')),
399 'Referer': webpage_url
404 class TikTokIE(TikTokBaseIE
):
405 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)'
406 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
409 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
410 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
412 'id': '6748451240264420610',
414 'title': '#jassmanak #lehanga #leenabhushan',
415 'description': '#jassmanak #lehanga #leenabhushan',
419 'uploader': 'leenabhushan',
420 'uploader_id': '6691488002098119685',
421 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
422 'creator': 'facestoriesbyleenabh',
423 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
424 'upload_date': '20191016',
425 'timestamp': 1571246252,
429 'comment_count': int,
430 'artist': 'Ysrbeats',
435 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
436 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
438 'id': '6742501081818877190',
440 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
441 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
445 'uploader': 'patrox',
446 'uploader_id': '18702747',
447 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
449 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
450 'upload_date': '20190930',
451 'timestamp': 1569860870,
455 'comment_count': int,
456 'artist': 'Evan Todd, Jessica Keenan Wynn, Alice Lee, Barrett Wilbert Weed & Jon Eidson',
460 # Banned audio, only available on the app
461 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
463 'id': '6984138651336838402',
465 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
466 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
467 'uploader': 'barudakhb_',
468 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
469 'uploader_id': '6974687867511718913',
470 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
471 'track': 'Boka Dance',
472 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
473 'timestamp': 1626121503,
475 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
476 'upload_date': '20210712',
480 'comment_count': int,
483 # Sponsored video, only available with feed workaround
484 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
486 'id': '7042692929109986561',
488 'title': 'Slap and Run!',
489 'description': 'Slap and Run!',
490 'uploader': 'user440922249',
491 'creator': 'Slap And Run',
492 'uploader_id': '7036055384943690754',
493 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
494 'track': 'Promoted Music',
495 'timestamp': 1639754738,
497 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
498 'upload_date': '20211217',
502 'comment_count': int,
504 'expected_warnings': ['trying with webpage', 'Unable to find video in feed']
506 # Video without title and description
507 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
509 'id': '7059698374567611694',
511 'title': 'TikTok video #7059698374567611694',
513 'uploader': 'pokemonlife22',
514 'creator': 'Pokemon',
515 'uploader_id': '6820838815978423302',
516 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
517 'track': 'original sound',
518 'timestamp': 1643714123,
520 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
521 'upload_date': '20220201',
526 'comment_count': int,
529 # hydration JSON is sent in a <script> element
530 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
532 'id': '7065799023130643713',
534 'title': '#denidil#денидил',
535 'description': '#denidil#денидил',
536 'uploader': 'denidil6',
537 'uploader_id': '7046664115636405250',
538 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
539 'artist': 'Holocron Music',
540 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
541 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
542 'timestamp': 1645134536,
544 'upload_date': '20220217',
548 'comment_count': int,
550 'skip': 'This video is unavailable',
552 # Auto-captions available
553 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
554 'only_matching': True
557 def _real_extract(self
, url
):
558 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
560 return self
._extract
_aweme
_app
(video_id
)
561 except ExtractorError
as e
:
562 self
.report_warning(f
'{e}; trying with webpage')
564 url
= self
._create
_url
(user_id
, video_id
)
565 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'User-Agent:Mozilla/5.0'}
)
566 next_data
= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}')
568 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode'), expected_type
=int) or 0
569 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type
=dict)
571 sigi_data
= self
._get
_sigi
_state
(webpage
, video_id
)
572 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode'), expected_type
=int) or 0
573 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
), expected_type
=dict)
576 return self
._parse
_aweme
_video
_web
(video_data
, url
)
577 elif status
== 10216:
578 raise ExtractorError('This video is private', expected
=True)
579 raise ExtractorError('Video not available', video_id
=video_id
)
582 class TikTokUserIE(TikTokBaseIE
):
583 IE_NAME
= 'tiktok:user'
584 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
587 'url': 'https://tiktok.com/@corgibobaa?lang=en',
588 'playlist_mincount': 45,
590 'id': '6935371178089399301',
591 'title': 'corgibobaa',
592 'thumbnail': r
're:https://.+_1080x1080\.webp'
594 'expected_warnings': ['Retrying']
596 'url': 'https://www.tiktok.com/@6820838815978423302',
597 'playlist_mincount': 5,
599 'id': '6820838815978423302',
600 'title': '6820838815978423302',
601 'thumbnail': r
're:https://.+_1080x1080\.webp'
603 'expected_warnings': ['Retrying']
605 'url': 'https://www.tiktok.com/@meme',
606 'playlist_mincount': 593,
608 'id': '79005827461758976',
610 'thumbnail': r
're:https://.+_1080x1080\.webp'
612 'expected_warnings': ['Retrying']
615 r
''' # TODO: Fix by adding _signature to api_url
616 def _entries(self, webpage, user_id, username):
617 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
618 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
619 if not verifyfp_cookie:
620 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
621 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='
623 for page in itertools.count():
624 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
625 for video in data_json.get('itemList', []):
626 video_id = video['id']
627 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
628 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
629 if not data_json.get('hasMore'):
631 cursor = data_json['cursor']
634 def _video_entries_api(self
, webpage
, user_id
, username
):
640 'retry_type': 'no_retry',
641 '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.
644 for page
in itertools
.count(1):
645 for retry
in self
.RetryManager():
647 post_list
= self
._call
_api
(
648 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
649 errnote
='Unable to download user video list')
650 except ExtractorError
as e
:
651 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
655 yield from post_list
.get('aweme_list', [])
656 if not post_list
.get('has_more'):
658 query
['max_cursor'] = post_list
['max_cursor']
660 def _entries_api(self
, user_id
, videos
):
663 **self
._parse
_aweme
_video
_app
(video
),
664 'extractor_key': TikTokIE
.ie_key(),
665 'extractor': 'TikTok',
666 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
669 def _real_extract(self
, url
):
670 user_name
= self
._match
_id
(url
)
671 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
672 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
674 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
676 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
677 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
679 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
682 class TikTokBaseListIE(TikTokBaseIE
): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor
683 def _entries(self
, list_id
, display_id
):
685 self
._QUERY
_NAME
: list_id
,
689 'device_id': ''.join(random
.choices(string
.digits
, k
=19))
692 for page
in itertools
.count(1):
693 for retry
in self
.RetryManager():
695 post_list
= self
._call
_api
(
696 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
697 errnote
='Unable to download video list')
698 except ExtractorError
as e
:
699 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
703 for video
in post_list
.get('aweme_list', []):
705 **self
._parse
_aweme
_video
_app
(video
),
706 'extractor_key': TikTokIE
.ie_key(),
707 'extractor': 'TikTok',
708 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
710 if not post_list
.get('has_more'):
712 query
['cursor'] = post_list
['cursor']
714 def _real_extract(self
, url
):
715 list_id
= self
._match
_id
(url
)
716 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
719 class TikTokSoundIE(TikTokBaseListIE
):
720 IE_NAME
= 'tiktok:sound'
721 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
723 _QUERY_NAME
= 'music_id'
724 _API_ENDPOINT
= 'music/aweme'
726 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
727 'playlist_mincount': 100,
729 'id': '6956990112127585029'
731 'expected_warnings': ['Retrying']
733 # Actual entries are less than listed video count
734 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
735 'playlist_mincount': 2182,
737 'id': '7036843036118469381'
739 'expected_warnings': ['Retrying']
743 class TikTokEffectIE(TikTokBaseListIE
):
744 IE_NAME
= 'tiktok:effect'
745 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
747 _QUERY_NAME
= 'sticker_id'
748 _API_ENDPOINT
= 'sticker/aweme'
750 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
751 'playlist_mincount': 100,
755 'expected_warnings': ['Retrying']
757 # Different entries between mobile and web, depending on region
758 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
759 'only_matching': True
763 class TikTokTagIE(TikTokBaseListIE
):
764 IE_NAME
= 'tiktok:tag'
765 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
767 _QUERY_NAME
= 'ch_id'
768 _API_ENDPOINT
= 'challenge/aweme'
770 'url': 'https://tiktok.com/tag/hello2018',
771 'playlist_mincount': 39,
774 'title': 'hello2018',
776 'expected_warnings': ['Retrying']
778 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
779 'only_matching': True
782 def _real_extract(self
, url
):
783 display_id
= self
._match
_id
(url
)
784 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
785 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
787 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
788 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
791 class DouyinIE(TikTokBaseIE
):
792 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
794 'url': 'https://www.douyin.com/video/6961737553342991651',
795 'md5': 'a97db7e3e67eb57bf40735c022ffa228',
797 'id': '6961737553342991651',
799 'title': '#杨超越 小小水手带你去远航❤️',
800 'description': '#杨超越 小小水手带你去远航❤️',
801 'uploader_id': '110403406559',
802 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
805 'timestamp': 1620905839,
806 'upload_date': '20210513',
807 'track': '@杨超越创作的原声',
811 'comment_count': int,
814 'url': 'https://www.douyin.com/video/6982497745948921092',
815 'md5': '34a87ebff3833357733da3fe17e37c0e',
817 'id': '6982497745948921092',
819 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
820 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想',
821 'uploader_id': '408654318141572',
822 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA',
825 'timestamp': 1625739481,
826 'upload_date': '20210708',
827 'track': '@杨超越工作室创作的原声',
831 'comment_count': int,
834 'url': 'https://www.douyin.com/video/6953975910773099811',
835 'md5': 'dde3302460f19db59c47060ff013b902',
837 'id': '6953975910773099811',
839 'title': '#一起看海 出现在你的夏日里',
840 'description': '#一起看海 出现在你的夏日里',
841 'uploader_id': '110403406559',
842 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
845 'timestamp': 1619098692,
846 'upload_date': '20210422',
847 'track': '@杨超越创作的原声',
851 'comment_count': int,
854 'url': 'https://www.douyin.com/video/6950251282489675042',
855 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
857 'id': '6950251282489675042',
859 'title': '哈哈哈,成功了哈哈哈哈哈哈',
861 'upload_date': '20210412',
862 'timestamp': 1618231483,
863 'uploader_id': '110403406559',
867 'comment_count': int,
869 'skip': 'No longer available',
871 'url': 'https://www.douyin.com/video/6963263655114722595',
872 'md5': 'cf9f11f0ec45d131445ec2f06766e122',
874 'id': '6963263655114722595',
876 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
877 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
878 'uploader_id': '110403406559',
879 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98',
882 'timestamp': 1621261163,
883 'upload_date': '20210517',
884 'track': '@杨超越创作的原声',
888 'comment_count': int,
891 _APP_VERSIONS
= [('23.3.0', '230300')]
894 _API_HOSTNAME
= 'aweme.snssdk.com'
895 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
896 _WEBPAGE_HOST
= 'https://www.douyin.com/'
898 def _real_extract(self
, url
):
899 video_id
= self
._match
_id
(url
)
902 return self
._extract
_aweme
_app
(video_id
)
903 except ExtractorError
as e
:
905 self
.to_screen(f
'{e}; trying with webpage')
907 webpage
= self
._download
_webpage
(url
, video_id
)
908 render_data_json
= self
._search
_regex
(
909 r
'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^
>]*>(%7B
.+%7D
)</script
>',
910 webpage, 'render data
', default=None)
911 if not render_data_json:
912 # TODO: Run verification challenge code to generate signature cookies
913 cookies = self._get_cookies(self._WEBPAGE_HOST)
914 expected = not cookies.get('s_v_web_id
') or not cookies.get('ttwid
')
915 raise ExtractorError(
916 'Fresh
cookies (not necessarily logged
in) are needed
', expected=expected)
918 render_data = self._parse_json(
919 render_data_json, video_id, transform_source=compat_urllib_parse_unquote)
920 return self._parse_aweme_video_web(get_first(render_data, ('aweme
', 'detail
')), url)
923 class TikTokVMIE(InfoExtractor):
924 _VALID_URL = r'https?
://(?
:(?
:vm|vt
)\
.tiktok\
.com|
(?
:www\
.)tiktok\
.com
/t
)/(?P
<id>\w
+)'
925 IE_NAME = 'vm
.tiktok
'
928 'url
': 'https
://www
.tiktok
.com
/t
/ZTRC5xgJp
',
930 'id': '7170520270497680683',
932 'title
': 'md5
:c64f6152330c2efe98093ccc8597871c
',
933 'uploader_id
': '6687535061741700102',
934 'upload_date
': '20221127',
937 'comment_count
': int,
938 'uploader_url
': 'https
://www
.tiktok
.com
/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX',
939 'album
': 'Wave of Mutilation
: Best of Pixies
',
940 'thumbnail
': r're
:https
://.+\
.webp
.*',
942 'timestamp
': 1669516858,
945 'track
': 'Where Is My Mind?
',
946 'description
': 'md5
:c64f6152330c2efe98093ccc8597871c
',
947 'uploader
': 'sigmachaddeus
',
948 'creator
': 'SigmaChad
',
951 'url
': 'https
://vm
.tiktok
.com
/ZTR45GpSF
/',
953 'id': '7106798200794926362',
955 'title
': 'md5
:edc3e7ea587847f8537468f2fe51d074
',
956 'uploader_id
': '6997695878846268418',
957 'upload_date
': '20220608',
960 'comment_count
': int,
961 'thumbnail
': r're
:https
://.+\
.webp
.*',
962 'uploader_url
': 'https
://www
.tiktok
.com
/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO',
964 'timestamp
': 1654680400,
966 'artist
': 'Akihitoko
',
967 'track
': 'original sound
',
968 'description
': 'md5
:edc3e7ea587847f8537468f2fe51d074
',
969 'uploader
': 'akihitoko1
',
970 'creator
': 'Akihitoko
',
973 'url
': 'https
://vt
.tiktok
.com
/ZSe4FqkKd
',
974 'only_matching
': True,
977 def _real_extract(self, url):
978 new_url = self._request_webpage(
979 HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).geturl()
980 if self.suitable(new_url): # Prevent infinite loop in case redirect fails
981 raise UnsupportedError(new_url)
982 return self.url_result(new_url)