7 from .common
import InfoExtractor
8 from ..compat
import compat_urllib_parse_unquote
, compat_urllib_parse_urlparse
19 srt_subtitles_timecode
,
27 class TikTokBaseIE(InfoExtractor
):
28 _APP_VERSIONS
= [('26.1.3', '260103'), ('26.1.2', '260102'), ('26.1.1', '260101'), ('25.6.2', '250602')]
29 _WORKING_APP_VERSION
= None
32 _API_HOSTNAME
= 'api-h2.tiktokv.com'
33 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
34 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
35 QUALITIES
= ('360p', '540p', '720p', '1080p')
38 def _create_url(user_id
, video_id
):
39 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
41 def _get_sigi_state(self
, webpage
, display_id
):
42 return self
._parse
_json
(get_element_by_id(
43 'SIGI_STATE|sigi-persisted-data', webpage
, escape_value
=False), display_id
)
45 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
46 note
='Downloading API JSON', errnote
='Unable to download API page'):
47 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choice('0123456789abcdef') for _
in range(160)))
48 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
49 if webpage_cookies
.get('sid_tt'):
50 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
51 return self
._download
_json
(
52 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
53 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
54 'User-Agent': f
'com.ss.android.ugc.trill/{manifest_app_version} (Linux; U; Android 10; en_US; Pixel 4; Build/QQ3A.200805.001; Cronet/58.0.2991.0)',
55 'Accept': 'application/json',
58 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
61 'version_name': app_version
,
62 'version_code': manifest_app_version
,
63 'build_number': app_version
,
64 'manifest_version_code': manifest_app_version
,
65 'update_version_code': manifest_app_version
,
66 'openudid': ''.join(random
.choice('0123456789abcdef') for _
in range(16)),
67 'uuid': ''.join([random
.choice(string
.digits
) for _
in range(16)]),
68 '_rticket': int(time
.time() * 1000),
69 'ts': int(time
.time()),
70 'device_brand': 'Google',
71 'device_type': 'Pixel 4',
72 'device_platform': 'android',
73 'resolution': '1080*1920',
77 'carrier_region': 'US',
80 'app_name': self
._APP
_NAME
,
83 'timezone_name': 'America/New_York',
84 'timezone_offset': '-14400',
85 'channel': 'googleplay',
92 'cp': 'cbfhckdckkde1',
95 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
96 note
='Downloading API JSON', errnote
='Unable to download API page'):
97 if not self
._WORKING
_APP
_VERSION
:
98 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
99 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
100 if app_version
and manifest_app_version
:
101 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
102 self
.write_debug('Imported app version combo from extractor arguments')
103 elif app_version
or manifest_app_version
:
104 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
106 if self
._WORKING
_APP
_VERSION
:
107 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
108 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
109 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
111 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
112 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
114 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
115 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
117 except ExtractorError
as e
:
118 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
119 if count
== len(self
._APP
_VERSIONS
):
123 self
.report_warning(str(e
.cause
or e
.msg
))
125 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
129 def _get_subtitles(self
, aweme_detail
, aweme_id
):
130 # TODO: Extract text positioning info
132 captions_info
= traverse_obj(
133 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict, default
=[])
134 for caption
in captions_info
:
135 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
138 caption_json
= self
._download
_json
(
139 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
142 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
145 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
146 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
150 def _parse_aweme_video_app(self
, aweme_detail
):
151 aweme_id
= aweme_detail
['aweme_id']
152 video_info
= aweme_detail
['video']
154 def parse_url_key(url_key
):
155 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
156 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
157 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
161 'format_id': format_id
,
162 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
163 'tbr': int_or_none(bitrate
, scale
=1000) or None,
164 'quality': qualities(self
.QUALITIES
)(res
),
167 known_resolutions
= {}
169 def extract_addr(addr
, add_meta
={}):
170 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
172 known_resolutions
.setdefault(res
, {}).setdefault('height', add_meta
.get('height'))
173 known_resolutions
[res
].setdefault('width', add_meta
.get('width'))
174 parsed_meta
.update(known_resolutions
.get(res
, {}))
175 add_meta
.setdefault('height', int_or_none(res
[:-1]))
178 'filesize': int_or_none(addr
.get('data_size')),
181 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
182 **add_meta
, **parsed_meta
,
183 'format_note': join_nonempty(
184 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' ')
185 } for url
in addr
.get('url_list') or []]
187 # Hack: Add direct video links first to prioritize them when removing duplicate formats
189 if video_info
.get('play_addr'):
190 formats
.extend(extract_addr(video_info
['play_addr'], {
191 'format_id': 'play_addr',
192 'format_note': 'Direct video',
193 'vcodec': 'h265' if traverse_obj(
194 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
195 'width': video_info
.get('width'),
196 'height': video_info
.get('height'),
198 if video_info
.get('download_addr'):
199 formats
.extend(extract_addr(video_info
['download_addr'], {
200 'format_id': 'download_addr',
201 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
203 'width': video_info
.get('width'),
204 'height': video_info
.get('height'),
205 'preference': -2 if video_info
.get('has_watermark') else -1,
207 if video_info
.get('play_addr_h264'):
208 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
209 'format_id': 'play_addr_h264',
210 'format_note': 'Direct video',
213 if video_info
.get('play_addr_bytevc1'):
214 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
215 'format_id': 'play_addr_bytevc1',
216 'format_note': 'Direct video',
220 for bitrate
in video_info
.get('bit_rate', []):
221 if bitrate
.get('play_addr'):
222 formats
.extend(extract_addr(bitrate
['play_addr'], {
223 'format_id': bitrate
.get('gear_name'),
224 'format_note': 'Playback video',
225 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
226 'vcodec': 'h265' if traverse_obj(
227 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
228 'fps': bitrate
.get('FPS'),
231 self
._remove
_duplicate
_formats
(formats
)
232 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
235 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
236 self
._sort
_formats
(formats
, ('quality', 'codec', 'size', 'br'))
239 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
240 'origin_cover', 'dynamic_cover'):
241 cover
= video_info
.get(cover_id
)
243 for cover_url
in cover
['url_list']:
249 stats_info
= aweme_detail
.get('statistics', {})
250 author_info
= aweme_detail
.get('author', {})
251 music_info
= aweme_detail
.get('music', {})
252 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
253 'sec_uid', 'id', 'uid', 'unique_id',
254 expected_type
=str_or_none
, get_all
=False))
255 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str, default
=[])
257 contained_music_track
= traverse_obj(
258 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
259 contained_music_author
= traverse_obj(
260 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
262 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
263 if is_generic_og_trackname
:
264 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
266 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
270 'extractor_key': TikTokIE
.ie_key(),
271 'extractor': TikTokIE
.IE_NAME
,
272 'webpage_url': self
._create
_url
(author_info
.get('uid'), aweme_id
),
273 'title': aweme_detail
.get('desc'),
274 'description': aweme_detail
.get('desc'),
275 'view_count': int_or_none(stats_info
.get('play_count')),
276 'like_count': int_or_none(stats_info
.get('digg_count')),
277 'repost_count': int_or_none(stats_info
.get('share_count')),
278 'comment_count': int_or_none(stats_info
.get('comment_count')),
279 'uploader': str_or_none(author_info
.get('unique_id')),
280 'creator': str_or_none(author_info
.get('nickname')),
281 'uploader_id': str_or_none(author_info
.get('uid')),
282 'uploader_url': user_url
,
283 'track': music_track
,
284 'album': str_or_none(music_info
.get('album')) or None,
285 'artist': music_author
or None,
286 'timestamp': int_or_none(aweme_detail
.get('create_time')),
288 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
289 'thumbnails': thumbnails
,
290 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
291 'availability': self
._availability
(
292 is_private
='Private' in labels
,
293 needs_subscription
='Friends only' in labels
,
294 is_unlisted
='Followers only' in labels
)
297 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
):
298 video_info
= aweme_detail
['video']
299 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
300 music_info
= aweme_detail
.get('music') or {}
301 stats_info
= aweme_detail
.get('stats') or {}
302 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
303 'secUid', 'id', 'uid', 'uniqueId',
304 expected_type
=str_or_none
, get_all
=False)
305 or aweme_detail
.get('authorSecId'))
308 play_url
= video_info
.get('playAddr')
309 width
= video_info
.get('width')
310 height
= video_info
.get('height')
311 if isinstance(play_url
, str):
313 'url': self
._proto
_relative
_url
(play_url
),
318 elif isinstance(play_url
, list):
320 'url': self
._proto
_relative
_url
(url
),
324 } for url
in traverse_obj(play_url
, (..., 'src'), expected_type
=url_or_none
, default
=[]) if url
]
326 download_url
= url_or_none(video_info
.get('downloadAddr')) or traverse_obj(video_info
, ('download', 'url'), expected_type
=url_or_none
)
329 'format_id': 'download',
330 'url': self
._proto
_relative
_url
(download_url
),
335 self
._remove
_duplicate
_formats
(formats
)
336 self
._sort
_formats
(formats
)
339 for thumbnail_name
in ('thumbnail', 'cover', 'dynamicCover', 'originCover'):
340 if aweme_detail
.get(thumbnail_name
):
342 'url': self
._proto
_relative
_url
(aweme_detail
[thumbnail_name
]),
348 'id': traverse_obj(aweme_detail
, 'id', 'awemeId', expected_type
=str_or_none
),
349 'title': aweme_detail
.get('desc'),
350 'duration': try_get(aweme_detail
, lambda x
: x
['video']['duration'], int),
351 'view_count': int_or_none(stats_info
.get('playCount')),
352 'like_count': int_or_none(stats_info
.get('diggCount')),
353 'repost_count': int_or_none(stats_info
.get('shareCount')),
354 'comment_count': int_or_none(stats_info
.get('commentCount')),
355 'timestamp': int_or_none(aweme_detail
.get('createTime')),
356 'creator': str_or_none(author_info
.get('nickname')),
357 'uploader': str_or_none(author_info
.get('uniqueId') or aweme_detail
.get('author')),
358 'uploader_id': str_or_none(author_info
.get('id') or aweme_detail
.get('authorId')),
359 'uploader_url': user_url
,
360 'track': str_or_none(music_info
.get('title')),
361 'album': str_or_none(music_info
.get('album')) or None,
362 'artist': str_or_none(music_info
.get('authorName')),
364 'thumbnails': thumbnails
,
365 'description': str_or_none(aweme_detail
.get('desc')),
367 'Referer': webpage_url
372 class TikTokIE(TikTokBaseIE
):
373 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)/video)/(?P<id>\d+)'
374 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
377 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
378 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
380 'id': '6748451240264420610',
382 'title': '#jassmanak #lehanga #leenabhushan',
383 'description': '#jassmanak #lehanga #leenabhushan',
387 'uploader': 'leenabhushan',
388 'uploader_id': '6691488002098119685',
389 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
390 'creator': 'facestoriesbyleenabh',
391 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
392 'upload_date': '20191016',
393 'timestamp': 1571246252,
397 'comment_count': int,
398 'artist': 'Ysrbeats',
403 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
404 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
406 'id': '6742501081818877190',
408 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
409 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
413 'uploader': 'patrox',
414 'uploader_id': '18702747',
415 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
417 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
418 'upload_date': '20190930',
419 'timestamp': 1569860870,
423 'comment_count': int,
424 'artist': 'Evan Todd, Jessica Keenan Wynn, Alice Lee, Barrett Wilbert Weed & Jon Eidson',
428 # Banned audio, only available on the app
429 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
431 'id': '6984138651336838402',
433 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
434 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
435 'uploader': 'barudakhb_',
436 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
437 'uploader_id': '6974687867511718913',
438 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
439 'track': 'Boka Dance',
440 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
441 'timestamp': 1626121503,
443 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
444 'upload_date': '20210712',
448 'comment_count': int,
451 # Sponsored video, only available with feed workaround
452 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
454 'id': '7042692929109986561',
456 'title': 'Slap and Run!',
457 'description': 'Slap and Run!',
458 'uploader': 'user440922249',
459 'creator': 'Slap And Run',
460 'uploader_id': '7036055384943690754',
461 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
462 'track': 'Promoted Music',
463 'timestamp': 1639754738,
465 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
466 'upload_date': '20211217',
470 'comment_count': int,
472 'expected_warnings': ['trying with webpage', 'Unable to find video in feed']
474 # Video without title and description
475 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
477 'id': '7059698374567611694',
479 'title': 'TikTok video #7059698374567611694',
481 'uploader': 'pokemonlife22',
482 'creator': 'Pokemon',
483 'uploader_id': '6820838815978423302',
484 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
485 'track': 'original sound',
486 'timestamp': 1643714123,
488 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
489 'upload_date': '20220201',
494 'comment_count': int,
497 # hydration JSON is sent in a <script> element
498 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
500 'id': '7065799023130643713',
502 'title': '#denidil#денидил',
503 'description': '#denidil#денидил',
504 'uploader': 'denidil6',
505 'uploader_id': '7046664115636405250',
506 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
507 'artist': 'Holocron Music',
508 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
509 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
510 'timestamp': 1645134536,
512 'upload_date': '20220217',
516 'comment_count': int,
518 'skip': 'This video is unavailable',
520 # Auto-captions available
521 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
522 'only_matching': True
525 def _extract_aweme_app(self
, aweme_id
):
526 feed_list
= self
._call
_api
('feed', {'aweme_id': aweme_id}
, aweme_id
,
527 note
='Downloading video feed', errnote
='Unable to download video feed').get('aweme_list') or []
528 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
530 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
531 return self
._parse
_aweme
_video
_app
(aweme_detail
)
533 def _real_extract(self
, url
):
534 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
536 return self
._extract
_aweme
_app
(video_id
)
537 except ExtractorError
as e
:
538 self
.report_warning(f
'{e}; trying with webpage')
540 url
= self
._create
_url
(user_id
, video_id
)
541 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'User-Agent:Mozilla/5.0'}
)
542 next_data
= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}')
544 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode'), expected_type
=int) or 0
545 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type
=dict)
547 sigi_data
= self
._get
_sigi
_state
(webpage
, video_id
)
548 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode'), expected_type
=int) or 0
549 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
), expected_type
=dict)
552 return self
._parse
_aweme
_video
_web
(video_data
, url
)
553 elif status
== 10216:
554 raise ExtractorError('This video is private', expected
=True)
555 raise ExtractorError('Video not available', video_id
=video_id
)
558 class TikTokUserIE(TikTokBaseIE
):
559 IE_NAME
= 'tiktok:user'
560 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
563 'url': 'https://tiktok.com/@corgibobaa?lang=en',
564 'playlist_mincount': 45,
566 'id': '6935371178089399301',
567 'title': 'corgibobaa',
568 'thumbnail': r
're:https://.+_1080x1080\.webp'
570 'expected_warnings': ['Retrying']
572 'url': 'https://www.tiktok.com/@6820838815978423302',
573 'playlist_mincount': 5,
575 'id': '6820838815978423302',
576 'title': '6820838815978423302',
577 'thumbnail': r
're:https://.+_1080x1080\.webp'
579 'expected_warnings': ['Retrying']
581 'url': 'https://www.tiktok.com/@meme',
582 'playlist_mincount': 593,
584 'id': '79005827461758976',
586 'thumbnail': r
're:https://.+_1080x1080\.webp'
588 'expected_warnings': ['Retrying']
591 r
''' # TODO: Fix by adding _signature to api_url
592 def _entries(self, webpage, user_id, username):
593 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
594 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
595 if not verifyfp_cookie:
596 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
597 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='
599 for page in itertools.count():
600 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
601 for video in data_json.get('itemList', []):
602 video_id = video['id']
603 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
604 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
605 if not data_json.get('hasMore'):
607 cursor = data_json['cursor']
610 def _video_entries_api(self
, webpage
, user_id
, username
):
616 'retry_type': 'no_retry',
617 '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.
620 for page
in itertools
.count(1):
621 for retry
in self
.RetryManager():
623 post_list
= self
._call
_api
(
624 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
625 errnote
='Unable to download user video list')
626 except ExtractorError
as e
:
627 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
631 yield from post_list
.get('aweme_list', [])
632 if not post_list
.get('has_more'):
634 query
['max_cursor'] = post_list
['max_cursor']
636 def _entries_api(self
, user_id
, videos
):
639 **self
._parse
_aweme
_video
_app
(video
),
640 'extractor_key': TikTokIE
.ie_key(),
641 'extractor': 'TikTok',
642 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
645 def _real_extract(self
, url
):
646 user_name
= self
._match
_id
(url
)
647 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
648 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
650 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
652 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
653 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
655 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
658 class TikTokBaseListIE(TikTokBaseIE
):
659 def _entries(self
, list_id
, display_id
):
661 self
._QUERY
_NAME
: list_id
,
665 'device_id': ''.join(random
.choice(string
.digits
) for i
in range(19))
668 for page
in itertools
.count(1):
669 for retry
in self
.RetryManager():
671 post_list
= self
._call
_api
(
672 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
673 errnote
='Unable to download video list')
674 except ExtractorError
as e
:
675 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
679 for video
in post_list
.get('aweme_list', []):
681 **self
._parse
_aweme
_video
_app
(video
),
682 'extractor_key': TikTokIE
.ie_key(),
683 'extractor': 'TikTok',
684 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
686 if not post_list
.get('has_more'):
688 query
['cursor'] = post_list
['cursor']
690 def _real_extract(self
, url
):
691 list_id
= self
._match
_id
(url
)
692 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
695 class TikTokSoundIE(TikTokBaseListIE
):
696 IE_NAME
= 'tiktok:sound'
697 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
699 _QUERY_NAME
= 'music_id'
700 _API_ENDPOINT
= 'music/aweme'
702 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
703 'playlist_mincount': 100,
705 'id': '6956990112127585029'
707 'expected_warnings': ['Retrying']
709 # Actual entries are less than listed video count
710 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
711 'playlist_mincount': 2182,
713 'id': '7036843036118469381'
715 'expected_warnings': ['Retrying']
719 class TikTokEffectIE(TikTokBaseListIE
):
720 IE_NAME
= 'tiktok:effect'
721 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
723 _QUERY_NAME
= 'sticker_id'
724 _API_ENDPOINT
= 'sticker/aweme'
726 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
727 'playlist_mincount': 100,
731 'expected_warnings': ['Retrying']
733 # Different entries between mobile and web, depending on region
734 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
735 'only_matching': True
739 class TikTokTagIE(TikTokBaseListIE
):
740 IE_NAME
= 'tiktok:tag'
741 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
743 _QUERY_NAME
= 'ch_id'
744 _API_ENDPOINT
= 'challenge/aweme'
746 'url': 'https://tiktok.com/tag/hello2018',
747 'playlist_mincount': 39,
750 'title': 'hello2018',
752 'expected_warnings': ['Retrying']
754 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
755 'only_matching': True
758 def _real_extract(self
, url
):
759 display_id
= self
._match
_id
(url
)
760 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
761 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
763 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
764 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
767 class DouyinIE(TikTokIE
):
768 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
770 'url': 'https://www.douyin.com/video/6961737553342991651',
771 'md5': '10523312c8b8100f353620ac9dc8f067',
773 'id': '6961737553342991651',
775 'title': '#杨超越 小小水手带你去远航❤️',
777 'upload_date': '20210513',
778 'timestamp': 1620905839,
779 'uploader_id': '110403406559',
783 'comment_count': int,
786 'url': 'https://www.douyin.com/video/6982497745948921092',
787 'md5': 'd78408c984b9b5102904cf6b6bc2d712',
789 'id': '6982497745948921092',
791 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
792 'uploader': '杨超越工作室',
793 'upload_date': '20210708',
794 'timestamp': 1625739481,
795 'uploader_id': '408654318141572',
799 'comment_count': int,
802 'url': 'https://www.douyin.com/video/6953975910773099811',
803 'md5': '72e882e24f75064c218b76c8b713c185',
805 'id': '6953975910773099811',
807 'title': '#一起看海 出现在你的夏日里',
809 'upload_date': '20210422',
810 'timestamp': 1619098692,
811 'uploader_id': '110403406559',
815 'comment_count': int,
818 'url': 'https://www.douyin.com/video/6950251282489675042',
819 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
821 'id': '6950251282489675042',
823 'title': '哈哈哈,成功了哈哈哈哈哈哈',
825 'upload_date': '20210412',
826 'timestamp': 1618231483,
827 'uploader_id': '110403406559',
831 'comment_count': int,
834 'url': 'https://www.douyin.com/video/6963263655114722595',
835 'md5': '1abe1c477d05ee62efb40bf2329957cf',
837 'id': '6963263655114722595',
839 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
841 'upload_date': '20210517',
842 'timestamp': 1621261163,
843 'uploader_id': '110403406559',
847 'comment_count': int,
850 _APP_VERSIONS
= [('9.6.0', '960')]
853 _API_HOSTNAME
= 'aweme.snssdk.com'
854 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
855 _WEBPAGE_HOST
= 'https://www.douyin.com/'
857 def _real_extract(self
, url
):
858 video_id
= self
._match
_id
(url
)
861 return self
._extract
_aweme
_app
(video_id
)
862 except ExtractorError
as e
:
863 self
.report_warning(f
'{e}; trying with webpage')
865 webpage
= self
._download
_webpage
(url
, video_id
)
866 render_data_json
= self
._search
_regex
(
867 r
'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^
>]*>(%7B
.+%7D
)</script
>',
868 webpage, 'render data
', default=None)
869 if not render_data_json:
870 # TODO: Run verification challenge code to generate signature cookies
871 raise ExtractorError('Fresh
cookies (not necessarily logged
in) are needed
')
873 render_data = self._parse_json(
874 render_data_json, video_id, transform_source=compat_urllib_parse_unquote)
875 return self._parse_aweme_video_web(get_first(render_data, ('aweme
', 'detail
')), url)
878 class TikTokVMIE(InfoExtractor):
879 _VALID_URL = r'https?
://(?
:vm|vt
)\
.tiktok\
.com
/(?P
<id>\w
+)'
880 IE_NAME = 'vm
.tiktok
'
883 'url
': 'https
://vm
.tiktok
.com
/ZSe4FqkKd
',
885 'id': '7023491746608712966',
887 'title
': 'md5
:5607564db90271abbbf8294cca77eddd
',
888 'description
': 'md5
:5607564db90271abbbf8294cca77eddd
',
890 'upload_date
': '20211026',
891 'uploader_id
': '7007385080558846981',
894 'track
': 'original sound
',
895 'uploader
': 'susmandem
',
896 'timestamp
': 1635284105,
897 'thumbnail
': r're
:https
://.+\
.webp
.*',
900 'comment_count
': int,
902 'uploader_url
': 'https
://www
.tiktok
.com
/@MS4wLjABAAAAXcNoOEOxVyBzuII_E--T0MeCrLP0ay1Sm6x_n3dluiWEoWZD0VlQOytwad4W0i0n
',
905 'url
': 'https
://vt
.tiktok
.com
/ZSe4FqkKd
',
906 'only_matching
': True,
909 def _real_extract(self, url):
910 new_url = self._request_webpage(
911 HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).geturl()
912 if self.suitable(new_url): # Prevent infinite loop in case redirect fails
913 raise UnsupportedError(new_url)
914 return self.url_result(new_url)