7 from .common
import InfoExtractor
9 compat_urllib_parse_unquote
,
10 compat_urllib_parse_urlparse
20 srt_subtitles_timecode
,
29 class TikTokBaseIE(InfoExtractor
):
30 _APP_VERSIONS
= [('20.9.3', '293'), ('20.4.3', '243'), ('20.2.1', '221'), ('20.1.2', '212'), ('20.0.4', '204')]
31 _WORKING_APP_VERSION
= None
34 _API_HOSTNAME
= 'api-h2.tiktokv.com'
35 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
36 _WEBPAGE_HOST
= 'https://www.tiktok.com/'
37 QUALITIES
= ('360p', '540p', '720p', '1080p')
39 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
40 note
='Downloading API JSON', errnote
='Unable to download API page'):
41 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choice('0123456789abcdef') for _
in range(160)))
42 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
43 if webpage_cookies
.get('sid_tt'):
44 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
45 return self
._download
_json
(
46 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
47 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
48 '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)',
49 'Accept': 'application/json',
52 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
55 'version_name': app_version
,
56 'version_code': manifest_app_version
,
57 'build_number': app_version
,
58 'manifest_version_code': manifest_app_version
,
59 'update_version_code': manifest_app_version
,
60 'openudid': ''.join(random
.choice('0123456789abcdef') for _
in range(16)),
61 'uuid': ''.join([random
.choice(string
.digits
) for _
in range(16)]),
62 '_rticket': int(time
.time() * 1000),
63 'ts': int(time
.time()),
64 'device_brand': 'Google',
65 'device_type': 'Pixel 4',
66 'device_platform': 'android',
67 'resolution': '1080*1920',
71 'carrier_region': 'US',
74 'app_name': self
._APP
_NAME
,
77 'timezone_name': 'America/New_York',
78 'timezone_offset': '-14400',
79 'channel': 'googleplay',
86 'cp': 'cbfhckdckkde1',
89 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
90 note
='Downloading API JSON', errnote
='Unable to download API page'):
91 if not self
._WORKING
_APP
_VERSION
:
92 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
93 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
94 if app_version
and manifest_app_version
:
95 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
96 self
.write_debug('Imported app version combo from extractor arguments')
97 elif app_version
or manifest_app_version
:
98 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
100 if self
._WORKING
_APP
_VERSION
:
101 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
102 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
103 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
105 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
106 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
108 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
109 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
111 except ExtractorError
as e
:
112 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
113 if count
== len(self
._APP
_VERSIONS
):
117 self
.report_warning(str(e
.cause
or e
.msg
))
119 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
123 def _get_subtitles(self
, aweme_detail
, aweme_id
):
124 # TODO: Extract text positioning info
126 captions_info
= traverse_obj(
127 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict, default
=[])
128 for caption
in captions_info
:
129 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
132 caption_json
= self
._download
_json
(
133 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
136 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
139 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
140 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
144 def _parse_aweme_video_app(self
, aweme_detail
):
145 aweme_id
= aweme_detail
['aweme_id']
146 video_info
= aweme_detail
['video']
148 def parse_url_key(url_key
):
149 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
150 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
151 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
155 'format_id': format_id
,
156 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
157 'tbr': int_or_none(bitrate
, scale
=1000) or None,
158 'quality': qualities(self
.QUALITIES
)(res
),
161 known_resolutions
= {}
163 def extract_addr(addr
, add_meta
={}):
164 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
166 known_resolutions
.setdefault(res
, {}).setdefault('height', add_meta
.get('height'))
167 known_resolutions
[res
].setdefault('width', add_meta
.get('width'))
168 parsed_meta
.update(known_resolutions
.get(res
, {}))
169 add_meta
.setdefault('height', int_or_none(res
[:-1]))
172 'filesize': int_or_none(addr
.get('data_size')),
175 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
176 **add_meta
, **parsed_meta
,
177 'format_note': join_nonempty(
178 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' ')
179 } for url
in addr
.get('url_list') or []]
181 # Hack: Add direct video links first to prioritize them when removing duplicate formats
183 if video_info
.get('play_addr'):
184 formats
.extend(extract_addr(video_info
['play_addr'], {
185 'format_id': 'play_addr',
186 'format_note': 'Direct video',
187 'vcodec': 'h265' if traverse_obj(
188 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
189 'width': video_info
.get('width'),
190 'height': video_info
.get('height'),
192 if video_info
.get('download_addr'):
193 formats
.extend(extract_addr(video_info
['download_addr'], {
194 'format_id': 'download_addr',
195 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
197 'width': video_info
.get('width'),
198 'height': video_info
.get('height'),
199 'preference': -2 if video_info
.get('has_watermark') else -1,
201 if video_info
.get('play_addr_h264'):
202 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
203 'format_id': 'play_addr_h264',
204 'format_note': 'Direct video',
207 if video_info
.get('play_addr_bytevc1'):
208 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
209 'format_id': 'play_addr_bytevc1',
210 'format_note': 'Direct video',
214 for bitrate
in video_info
.get('bit_rate', []):
215 if bitrate
.get('play_addr'):
216 formats
.extend(extract_addr(bitrate
['play_addr'], {
217 'format_id': bitrate
.get('gear_name'),
218 'format_note': 'Playback video',
219 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
220 'vcodec': 'h265' if traverse_obj(
221 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
222 'fps': bitrate
.get('FPS'),
225 self
._remove
_duplicate
_formats
(formats
)
226 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
229 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
230 self
._sort
_formats
(formats
, ('quality', 'codec', 'size', 'br'))
233 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
234 'origin_cover', 'dynamic_cover'):
235 cover
= video_info
.get(cover_id
)
237 for cover_url
in cover
['url_list']:
243 stats_info
= aweme_detail
.get('statistics', {})
244 author_info
= aweme_detail
.get('author', {})
245 music_info
= aweme_detail
.get('music', {})
246 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
247 'sec_uid', 'id', 'uid', 'unique_id',
248 expected_type
=str_or_none
, get_all
=False))
249 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str, default
=[])
251 contained_music_track
= traverse_obj(
252 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
253 contained_music_author
= traverse_obj(
254 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
256 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
257 if is_generic_og_trackname
:
258 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
260 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
264 'title': aweme_detail
.get('desc'),
265 'description': aweme_detail
.get('desc'),
266 'view_count': int_or_none(stats_info
.get('play_count')),
267 'like_count': int_or_none(stats_info
.get('digg_count')),
268 'repost_count': int_or_none(stats_info
.get('share_count')),
269 'comment_count': int_or_none(stats_info
.get('comment_count')),
270 'uploader': str_or_none(author_info
.get('unique_id')),
271 'creator': str_or_none(author_info
.get('nickname')),
272 'uploader_id': str_or_none(author_info
.get('uid')),
273 'uploader_url': user_url
,
274 'track': music_track
,
275 'album': str_or_none(music_info
.get('album')) or None,
276 'artist': music_author
,
277 'timestamp': int_or_none(aweme_detail
.get('create_time')),
279 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
280 'thumbnails': thumbnails
,
281 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
282 'availability': self
._availability
(
283 is_private
='Private' in labels
,
284 needs_subscription
='Friends only' in labels
,
285 is_unlisted
='Followers only' in labels
)
288 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
):
289 video_info
= aweme_detail
['video']
290 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
291 music_info
= aweme_detail
.get('music') or {}
292 stats_info
= aweme_detail
.get('stats') or {}
293 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
294 'secUid', 'id', 'uid', 'uniqueId',
295 expected_type
=str_or_none
, get_all
=False)
296 or aweme_detail
.get('authorSecId'))
299 play_url
= video_info
.get('playAddr')
300 width
= video_info
.get('width')
301 height
= video_info
.get('height')
302 if isinstance(play_url
, str):
304 'url': self
._proto
_relative
_url
(play_url
),
309 elif isinstance(play_url
, list):
311 'url': self
._proto
_relative
_url
(url
),
315 } for url
in traverse_obj(play_url
, (..., 'src'), expected_type
=url_or_none
, default
=[]) if url
]
317 download_url
= url_or_none(video_info
.get('downloadAddr')) or traverse_obj(video_info
, ('download', 'url'), expected_type
=url_or_none
)
320 'format_id': 'download',
321 'url': self
._proto
_relative
_url
(download_url
),
326 self
._remove
_duplicate
_formats
(formats
)
327 self
._sort
_formats
(formats
)
330 for thumbnail_name
in ('thumbnail', 'cover', 'dynamicCover', 'originCover'):
331 if aweme_detail
.get(thumbnail_name
):
333 'url': self
._proto
_relative
_url
(aweme_detail
[thumbnail_name
]),
339 'id': traverse_obj(aweme_detail
, 'id', 'awemeId', expected_type
=str_or_none
),
340 'title': aweme_detail
.get('desc'),
341 'duration': try_get(aweme_detail
, lambda x
: x
['video']['duration'], int),
342 'view_count': int_or_none(stats_info
.get('playCount')),
343 'like_count': int_or_none(stats_info
.get('diggCount')),
344 'repost_count': int_or_none(stats_info
.get('shareCount')),
345 'comment_count': int_or_none(stats_info
.get('commentCount')),
346 'timestamp': int_or_none(aweme_detail
.get('createTime')),
347 'creator': str_or_none(author_info
.get('nickname')),
348 'uploader': str_or_none(author_info
.get('uniqueId') or aweme_detail
.get('author')),
349 'uploader_id': str_or_none(author_info
.get('id') or aweme_detail
.get('authorId')),
350 'uploader_url': user_url
,
351 'track': str_or_none(music_info
.get('title')),
352 'album': str_or_none(music_info
.get('album')) or None,
353 'artist': str_or_none(music_info
.get('authorName')),
355 'thumbnails': thumbnails
,
356 'description': str_or_none(aweme_detail
.get('desc')),
358 'Referer': webpage_url
363 class TikTokIE(TikTokBaseIE
):
364 _VALID_URL
= r
'https?://www\.tiktok\.com/@[\w\.-]+/video/(?P<id>\d+)'
367 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
368 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
370 'id': '6748451240264420610',
372 'title': '#jassmanak #lehanga #leenabhushan',
373 'description': '#jassmanak #lehanga #leenabhushan',
377 'uploader': 'leenabhushan',
378 'uploader_id': '6691488002098119685',
379 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
380 'creator': 'facestoriesbyleenabh',
381 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
382 'upload_date': '20191016',
383 'timestamp': 1571246252,
387 'comment_count': int,
388 'artist': 'Ysrbeats',
393 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
394 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
396 'id': '6742501081818877190',
398 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
399 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
403 'uploader': 'patrox',
404 'uploader_id': '18702747',
405 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
407 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
408 'upload_date': '20190930',
409 'timestamp': 1569860870,
413 'comment_count': int,
414 'artist': 'Evan Todd, Jessica Keenan Wynn, Alice Lee, Barrett Wilbert Weed & Jon Eidson',
418 # Banned audio, only available on the app
419 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
421 'id': '6984138651336838402',
423 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
424 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
425 'uploader': 'barudakhb_',
426 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
427 'uploader_id': '6974687867511718913',
428 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
429 'track': 'Boka Dance',
430 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
431 'timestamp': 1626121503,
433 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
434 'upload_date': '20210712',
438 'comment_count': int,
441 # Sponsored video, only available with feed workaround
442 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
444 'id': '7042692929109986561',
446 'title': 'Slap and Run!',
447 'description': 'Slap and Run!',
448 'uploader': 'user440922249',
449 'creator': 'Slap And Run',
450 'uploader_id': '7036055384943690754',
451 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
452 'track': 'Promoted Music',
453 'timestamp': 1639754738,
455 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
456 'upload_date': '20211217',
460 'comment_count': int,
462 'expected_warnings': ['Video not available']
464 # Video without title and description
465 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
467 'id': '7059698374567611694',
469 'title': 'tiktok video #7059698374567611694',
471 'uploader': 'pokemonlife22',
472 'creator': 'Pokemon',
473 'uploader_id': '6820838815978423302',
474 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
475 'track': 'original sound',
476 'timestamp': 1643714123,
478 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
479 'upload_date': '20220201',
484 'comment_count': int,
486 'expected_warnings': ['Video not available', 'Creating a generic title']
488 # Auto-captions available
489 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
490 'only_matching': True
493 def _extract_aweme_app(self
, aweme_id
):
495 aweme_detail
= self
._call
_api
('aweme/detail', {'aweme_id': aweme_id}
, aweme_id
,
496 note
='Downloading video details', errnote
='Unable to download video details').get('aweme_detail')
498 raise ExtractorError('Video not available', video_id
=aweme_id
)
499 except ExtractorError
as e
:
500 self
.report_warning(f
'{e}; Retrying with feed workaround')
501 feed_list
= self
._call
_api
('feed', {'aweme_id': aweme_id}
, aweme_id
,
502 note
='Downloading video feed', errnote
='Unable to download video feed').get('aweme_list') or []
503 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
505 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
506 return self
._parse
_aweme
_video
_app
(aweme_detail
)
508 def _real_extract(self
, url
):
509 video_id
= self
._match
_id
(url
)
512 return self
._extract
_aweme
_app
(video_id
)
513 except ExtractorError
as e
:
514 self
.report_warning(f
'{e}; Retrying with webpage')
516 # If we only call once, we get a 403 when downlaoding the video.
517 self
._download
_webpage
(url
, video_id
)
518 webpage
= self
._download
_webpage
(url
, video_id
, note
='Downloading video webpage')
519 next_data
= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}')
522 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode'), expected_type
=int) or 0
523 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type
=dict)
525 sigi_json
= self
._search
_regex
(
526 r
'>\s*window\[[\'"]SIGI_STATE[\'"]\
]\s
*=\s
*(?P
<sigi_state
>{.+}
);',
527 webpage, 'sigi data
', group='sigi_state
')
528 sigi_data = self._parse_json(sigi_json, video_id)
529 status = traverse_obj(sigi_data, ('VideoPage
', 'statusCode
'), expected_type=int) or 0
530 video_data = traverse_obj(sigi_data, ('ItemModule
', video_id), expected_type=dict)
533 return self._parse_aweme_video_web(video_data, url)
534 elif status == 10216:
535 raise ExtractorError('This video
is private
', expected=True)
536 raise ExtractorError('Video
not available
', video_id=video_id)
539 class TikTokUserIE(TikTokBaseIE):
540 IE_NAME = 'tiktok
:user
'
541 _VALID_URL = r'https?
://(?
:www\
.)?tiktok\
.com
/@(?P
<id>[\w\
.-]+)/?
(?
:$|
[#?])'
543 'url': 'https://tiktok.com/@corgibobaa?lang=en',
544 'playlist_mincount': 45,
546 'id': '6935371178089399301',
547 'title': 'corgibobaa',
548 'thumbnail': r
're:https://.+_1080x1080\.webp'
550 'expected_warnings': ['Retrying']
552 'url': 'https://www.tiktok.com/@6820838815978423302',
553 'playlist_mincount': 5,
555 'id': '6820838815978423302',
556 'title': '6820838815978423302',
557 'thumbnail': r
're:https://.+_1080x1080\.webp'
559 'expected_warnings': ['Retrying']
561 'url': 'https://www.tiktok.com/@meme',
562 'playlist_mincount': 593,
564 'id': '79005827461758976',
566 'thumbnail': r
're:https://.+_1080x1080\.webp'
568 'expected_warnings': ['Retrying']
571 r
''' # TODO: Fix by adding _signature to api_url
572 def _entries(self, webpage, user_id, username):
573 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
574 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
575 if not verifyfp_cookie:
576 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
577 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='
579 for page in itertools.count():
580 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
581 for video in data_json.get('itemList', []):
582 video_id = video['id']
583 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
584 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
585 if not data_json.get('hasMore'):
587 cursor = data_json['cursor']
590 def _video_entries_api(self
, webpage
, user_id
, username
):
596 'retry_type': 'no_retry',
597 '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.
600 max_retries
= self
.get_param('extractor_retries', 3)
601 for page
in itertools
.count(1):
602 for retries
in itertools
.count():
604 post_list
= self
._call
_api
('aweme/post', query
, username
,
605 note
='Downloading user video list page %d%s' % (page
, f
' (attempt {retries})' if retries
!= 0 else ''),
606 errnote
='Unable to download user video list')
607 except ExtractorError
as e
:
608 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0 and retries
!= max_retries
:
609 self
.report_warning('%s. Retrying...' % str(e
.cause
or e
.msg
))
613 yield from post_list
.get('aweme_list', [])
614 if not post_list
.get('has_more'):
616 query
['max_cursor'] = post_list
['max_cursor']
618 def _entries_api(self
, user_id
, videos
):
621 **self
._parse
_aweme
_video
_app
(video
),
622 'extractor_key': TikTokIE
.ie_key(),
623 'extractor': 'TikTok',
624 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
627 def _real_extract(self
, url
):
628 user_name
= self
._match
_id
(url
)
629 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
630 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
632 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
634 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
635 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
637 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
640 class TikTokBaseListIE(TikTokBaseIE
):
641 def _entries(self
, list_id
, display_id
):
643 self
._QUERY
_NAME
: list_id
,
647 'device_id': ''.join(random
.choice(string
.digits
) for i
in range(19))
650 max_retries
= self
.get_param('extractor_retries', 3)
651 for page
in itertools
.count(1):
652 for retries
in itertools
.count():
654 post_list
= self
._call
_api
(self
._API
_ENDPOINT
, query
, display_id
,
655 note
='Downloading video list page %d%s' % (page
, f
' (attempt {retries})' if retries
!= 0 else ''),
656 errnote
='Unable to download video list')
657 except ExtractorError
as e
:
658 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0 and retries
!= max_retries
:
659 self
.report_warning('%s. Retrying...' % str(e
.cause
or e
.msg
))
663 for video
in post_list
.get('aweme_list', []):
665 **self
._parse
_aweme
_video
_app
(video
),
666 'extractor_key': TikTokIE
.ie_key(),
667 'extractor': 'TikTok',
668 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
670 if not post_list
.get('has_more'):
672 query
['cursor'] = post_list
['cursor']
674 def _real_extract(self
, url
):
675 list_id
= self
._match
_id
(url
)
676 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
679 class TikTokSoundIE(TikTokBaseListIE
):
680 IE_NAME
= 'tiktok:sound'
681 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
682 _QUERY_NAME
= 'music_id'
683 _API_ENDPOINT
= 'music/aweme'
685 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
686 'playlist_mincount': 100,
688 'id': '6956990112127585029'
690 'expected_warnings': ['Retrying']
692 # Actual entries are less than listed video count
693 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
694 'playlist_mincount': 2182,
696 'id': '7036843036118469381'
698 'expected_warnings': ['Retrying']
702 class TikTokEffectIE(TikTokBaseListIE
):
703 IE_NAME
= 'tiktok:effect'
704 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
705 _QUERY_NAME
= 'sticker_id'
706 _API_ENDPOINT
= 'sticker/aweme'
708 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
709 'playlist_mincount': 100,
713 'expected_warnings': ['Retrying']
715 # Different entries between mobile and web, depending on region
716 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
717 'only_matching': True
721 class TikTokTagIE(TikTokBaseListIE
):
722 IE_NAME
= 'tiktok:tag'
723 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
724 _QUERY_NAME
= 'ch_id'
725 _API_ENDPOINT
= 'challenge/aweme'
727 'url': 'https://tiktok.com/tag/hello2018',
728 'playlist_mincount': 39,
731 'title': 'hello2018',
733 'expected_warnings': ['Retrying']
735 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
736 'only_matching': True
739 def _real_extract(self
, url
):
740 display_id
= self
._match
_id
(url
)
741 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
742 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
744 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
745 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
748 class DouyinIE(TikTokIE
):
749 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
751 'url': 'https://www.douyin.com/video/6961737553342991651',
752 'md5': '10523312c8b8100f353620ac9dc8f067',
754 'id': '6961737553342991651',
756 'title': '#杨超越 小小水手带你去远航❤️',
758 'upload_date': '20210513',
759 'timestamp': 1620905839,
760 'uploader_id': '110403406559',
764 'comment_count': int,
767 'url': 'https://www.douyin.com/video/6982497745948921092',
768 'md5': 'd78408c984b9b5102904cf6b6bc2d712',
770 'id': '6982497745948921092',
772 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
773 'uploader': '杨超越工作室',
774 'upload_date': '20210708',
775 'timestamp': 1625739481,
776 'uploader_id': '408654318141572',
780 'comment_count': int,
783 'url': 'https://www.douyin.com/video/6953975910773099811',
784 'md5': '72e882e24f75064c218b76c8b713c185',
786 'id': '6953975910773099811',
788 'title': '#一起看海 出现在你的夏日里',
790 'upload_date': '20210422',
791 'timestamp': 1619098692,
792 'uploader_id': '110403406559',
796 'comment_count': int,
799 'url': 'https://www.douyin.com/video/6950251282489675042',
800 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
802 'id': '6950251282489675042',
804 'title': '哈哈哈,成功了哈哈哈哈哈哈',
806 'upload_date': '20210412',
807 'timestamp': 1618231483,
808 'uploader_id': '110403406559',
812 'comment_count': int,
815 'url': 'https://www.douyin.com/video/6963263655114722595',
816 'md5': '1abe1c477d05ee62efb40bf2329957cf',
818 'id': '6963263655114722595',
820 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
822 'upload_date': '20210517',
823 'timestamp': 1621261163,
824 'uploader_id': '110403406559',
828 'comment_count': int,
831 _APP_VERSIONS
= [('9.6.0', '960')]
834 _API_HOSTNAME
= 'aweme.snssdk.com'
835 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
836 _WEBPAGE_HOST
= 'https://www.douyin.com/'
838 def _real_extract(self
, url
):
839 video_id
= self
._match
_id
(url
)
842 return self
._extract
_aweme
_app
(video_id
)
843 except ExtractorError
as e
:
844 self
.report_warning(f
'{e}; Retrying with webpage')
846 webpage
= self
._download
_webpage
(url
, video_id
)
847 render_data_json
= self
._search
_regex
(
848 r
'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^
>]*>(%7B
.+%7D
)</script
>',
849 webpage, 'render data
', default=None)
850 if not render_data_json:
851 # TODO: Run verification challenge code to generate signature cookies
852 raise ExtractorError('Fresh
cookies (not necessarily logged
in) are needed
')
854 render_data = self._parse_json(
855 render_data_json, video_id, transform_source=compat_urllib_parse_unquote)
856 return self._parse_aweme_video_web(get_first(render_data, ('aweme
', 'detail
')), url)
859 class TikTokVMIE(InfoExtractor):
860 _VALID_URL = r'https?
://(?
:vm|vt
)\
.tiktok\
.com
/(?P
<id>\w
+)'
861 IE_NAME = 'vm
.tiktok
'
864 'url
': 'https
://vm
.tiktok
.com
/ZSe4FqkKd
',
866 'id': '7023491746608712966',
868 'title
': 'md5
:5607564db90271abbbf8294cca77eddd
',
869 'description
': 'md5
:5607564db90271abbbf8294cca77eddd
',
871 'upload_date
': '20211026',
872 'uploader_id
': '7007385080558846981',
875 'track
': 'original sound
',
876 'uploader
': 'susmandem
',
877 'timestamp
': 1635284105,
878 'thumbnail
': r're
:https
://.+\
.webp
.*',
881 'comment_count
': int,
883 'uploader_url
': 'https
://www
.tiktok
.com
/@MS4wLjABAAAAXcNoOEOxVyBzuII_E--T0MeCrLP0ay1Sm6x_n3dluiWEoWZD0VlQOytwad4W0i0n
',
886 'url
': 'https
://vt
.tiktok
.com
/ZSe4FqkKd
',
887 'only_matching
': True,
890 def _real_extract(self, url):
891 new_url = self._request_webpage(
892 HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).geturl()
893 if self.suitable(new_url): # Prevent infinite loop in case redirect fails
894 raise UnsupportedError(new_url)
895 return self.url_result(new_url)