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
= [('20.9.3', '293'), ('20.4.3', '243'), ('20.2.1', '221'), ('20.1.2', '212'), ('20.0.4', '204')]
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')
36 _session_initialized
= False
39 def _create_url(user_id
, video_id
):
40 return f
'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}'
42 def _get_sigi_state(self
, webpage
, display_id
):
43 return self
._parse
_json
(get_element_by_id(
44 'SIGI_STATE|sigi-persisted-data', webpage
, escape_value
=False), display_id
)
46 def _real_initialize(self
):
47 if self
._session
_initialized
:
49 self
._request
_webpage
(HEADRequest('https://www.tiktok.com'), None, note
='Setting up session', fatal
=False)
50 TikTokBaseIE
._session
_initialized
= True
52 def _call_api_impl(self
, ep
, query
, manifest_app_version
, video_id
, fatal
=True,
53 note
='Downloading API JSON', errnote
='Unable to download API page'):
54 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choice('0123456789abcdef') for _
in range(160)))
55 webpage_cookies
= self
._get
_cookies
(self
._WEBPAGE
_HOST
)
56 if webpage_cookies
.get('sid_tt'):
57 self
._set
_cookie
(self
._API
_HOSTNAME
, 'sid_tt', webpage_cookies
['sid_tt'].value
)
58 return self
._download
_json
(
59 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
60 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
61 '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)',
62 'Accept': 'application/json',
65 def _build_api_query(self
, query
, app_version
, manifest_app_version
):
68 'version_name': app_version
,
69 'version_code': manifest_app_version
,
70 'build_number': app_version
,
71 'manifest_version_code': manifest_app_version
,
72 'update_version_code': manifest_app_version
,
73 'openudid': ''.join(random
.choice('0123456789abcdef') for _
in range(16)),
74 'uuid': ''.join([random
.choice(string
.digits
) for _
in range(16)]),
75 '_rticket': int(time
.time() * 1000),
76 'ts': int(time
.time()),
77 'device_brand': 'Google',
78 'device_type': 'Pixel 4',
79 'device_platform': 'android',
80 'resolution': '1080*1920',
84 'carrier_region': 'US',
87 'app_name': self
._APP
_NAME
,
90 'timezone_name': 'America/New_York',
91 'timezone_offset': '-14400',
92 'channel': 'googleplay',
99 'cp': 'cbfhckdckkde1',
102 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
103 note
='Downloading API JSON', errnote
='Unable to download API page'):
104 if not self
._WORKING
_APP
_VERSION
:
105 app_version
= self
._configuration
_arg
('app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
106 manifest_app_version
= self
._configuration
_arg
('manifest_app_version', [''], ie_key
=TikTokIE
.ie_key())[0]
107 if app_version
and manifest_app_version
:
108 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
109 self
.write_debug('Imported app version combo from extractor arguments')
110 elif app_version
or manifest_app_version
:
111 self
.report_warning('Only one of the two required version params are passed as extractor arguments', only_once
=True)
113 if self
._WORKING
_APP
_VERSION
:
114 app_version
, manifest_app_version
= self
._WORKING
_APP
_VERSION
115 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
116 return self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
118 for count
, (app_version
, manifest_app_version
) in enumerate(self
._APP
_VERSIONS
, start
=1):
119 real_query
= self
._build
_api
_query
(query
, app_version
, manifest_app_version
)
121 res
= self
._call
_api
_impl
(ep
, real_query
, manifest_app_version
, video_id
, fatal
, note
, errnote
)
122 self
._WORKING
_APP
_VERSION
= (app_version
, manifest_app_version
)
124 except ExtractorError
as e
:
125 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
126 if count
== len(self
._APP
_VERSIONS
):
130 self
.report_warning(str(e
.cause
or e
.msg
))
132 self
.report_warning('%s. Retrying... (attempt %s of %s)' % (str(e
.cause
or e
.msg
), count
, len(self
._APP
_VERSIONS
)))
136 def _get_subtitles(self
, aweme_detail
, aweme_id
):
137 # TODO: Extract text positioning info
139 captions_info
= traverse_obj(
140 aweme_detail
, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type
=dict, default
=[])
141 for caption
in captions_info
:
142 caption_url
= traverse_obj(caption
, ('url', 'url_list', ...), expected_type
=url_or_none
, get_all
=False)
145 caption_json
= self
._download
_json
(
146 caption_url
, aweme_id
, note
='Downloading captions', errnote
='Unable to download captions', fatal
=False)
149 subtitles
.setdefault(caption
.get('language', 'en'), []).append({
152 f
'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}'
153 for i
, line
in enumerate(caption_json
['utterances']) if line
.get('text'))
157 def _parse_aweme_video_app(self
, aweme_detail
):
158 aweme_id
= aweme_detail
['aweme_id']
159 video_info
= aweme_detail
['video']
161 def parse_url_key(url_key
):
162 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
163 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
164 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
168 'format_id': format_id
,
169 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
170 'tbr': int_or_none(bitrate
, scale
=1000) or None,
171 'quality': qualities(self
.QUALITIES
)(res
),
174 known_resolutions
= {}
176 def extract_addr(addr
, add_meta
={}):
177 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
179 known_resolutions
.setdefault(res
, {}).setdefault('height', add_meta
.get('height'))
180 known_resolutions
[res
].setdefault('width', add_meta
.get('width'))
181 parsed_meta
.update(known_resolutions
.get(res
, {}))
182 add_meta
.setdefault('height', int_or_none(res
[:-1]))
185 'filesize': int_or_none(addr
.get('data_size')),
188 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
189 **add_meta
, **parsed_meta
,
190 'format_note': join_nonempty(
191 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' ')
192 } for url
in addr
.get('url_list') or []]
194 # Hack: Add direct video links first to prioritize them when removing duplicate formats
196 if video_info
.get('play_addr'):
197 formats
.extend(extract_addr(video_info
['play_addr'], {
198 'format_id': 'play_addr',
199 'format_note': 'Direct video',
200 'vcodec': 'h265' if traverse_obj(
201 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002
202 'width': video_info
.get('width'),
203 'height': video_info
.get('height'),
205 if video_info
.get('download_addr'):
206 formats
.extend(extract_addr(video_info
['download_addr'], {
207 'format_id': 'download_addr',
208 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
210 'width': video_info
.get('width'),
211 'height': video_info
.get('height'),
212 'preference': -2 if video_info
.get('has_watermark') else -1,
214 if video_info
.get('play_addr_h264'):
215 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
216 'format_id': 'play_addr_h264',
217 'format_note': 'Direct video',
220 if video_info
.get('play_addr_bytevc1'):
221 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
222 'format_id': 'play_addr_bytevc1',
223 'format_note': 'Direct video',
227 for bitrate
in video_info
.get('bit_rate', []):
228 if bitrate
.get('play_addr'):
229 formats
.extend(extract_addr(bitrate
['play_addr'], {
230 'format_id': bitrate
.get('gear_name'),
231 'format_note': 'Playback video',
232 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
233 'vcodec': 'h265' if traverse_obj(
234 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
235 'fps': bitrate
.get('FPS'),
238 self
._remove
_duplicate
_formats
(formats
)
239 auth_cookie
= self
._get
_cookies
(self
._WEBPAGE
_HOST
).get('sid_tt')
242 self
._set
_cookie
(compat_urllib_parse_urlparse(f
['url']).hostname
, 'sid_tt', auth_cookie
.value
)
243 self
._sort
_formats
(formats
, ('quality', 'codec', 'size', 'br'))
246 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
247 'origin_cover', 'dynamic_cover'):
248 cover
= video_info
.get(cover_id
)
250 for cover_url
in cover
['url_list']:
256 stats_info
= aweme_detail
.get('statistics', {})
257 author_info
= aweme_detail
.get('author', {})
258 music_info
= aweme_detail
.get('music', {})
259 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
260 'sec_uid', 'id', 'uid', 'unique_id',
261 expected_type
=str_or_none
, get_all
=False))
262 labels
= traverse_obj(aweme_detail
, ('hybrid_label', ..., 'text'), expected_type
=str, default
=[])
264 contained_music_track
= traverse_obj(
265 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
266 contained_music_author
= traverse_obj(
267 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
269 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
270 if is_generic_og_trackname
:
271 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
273 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
277 'extractor_key': TikTokIE
.ie_key(),
278 'extractor': TikTokIE
.IE_NAME
,
279 'webpage_url': self
._create
_url
(author_info
.get('uid'), aweme_id
),
280 'title': aweme_detail
.get('desc'),
281 'description': aweme_detail
.get('desc'),
282 'view_count': int_or_none(stats_info
.get('play_count')),
283 'like_count': int_or_none(stats_info
.get('digg_count')),
284 'repost_count': int_or_none(stats_info
.get('share_count')),
285 'comment_count': int_or_none(stats_info
.get('comment_count')),
286 'uploader': str_or_none(author_info
.get('unique_id')),
287 'creator': str_or_none(author_info
.get('nickname')),
288 'uploader_id': str_or_none(author_info
.get('uid')),
289 'uploader_url': user_url
,
290 'track': music_track
,
291 'album': str_or_none(music_info
.get('album')) or None,
292 'artist': music_author
,
293 'timestamp': int_or_none(aweme_detail
.get('create_time')),
295 'subtitles': self
.extract_subtitles(aweme_detail
, aweme_id
),
296 'thumbnails': thumbnails
,
297 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000),
298 'availability': self
._availability
(
299 is_private
='Private' in labels
,
300 needs_subscription
='Friends only' in labels
,
301 is_unlisted
='Followers only' in labels
)
304 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
):
305 video_info
= aweme_detail
['video']
306 author_info
= traverse_obj(aweme_detail
, 'authorInfo', 'author', expected_type
=dict, default
={})
307 music_info
= aweme_detail
.get('music') or {}
308 stats_info
= aweme_detail
.get('stats') or {}
309 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
310 'secUid', 'id', 'uid', 'uniqueId',
311 expected_type
=str_or_none
, get_all
=False)
312 or aweme_detail
.get('authorSecId'))
315 play_url
= video_info
.get('playAddr')
316 width
= video_info
.get('width')
317 height
= video_info
.get('height')
318 if isinstance(play_url
, str):
320 'url': self
._proto
_relative
_url
(play_url
),
325 elif isinstance(play_url
, list):
327 'url': self
._proto
_relative
_url
(url
),
331 } for url
in traverse_obj(play_url
, (..., 'src'), expected_type
=url_or_none
, default
=[]) if url
]
333 download_url
= url_or_none(video_info
.get('downloadAddr')) or traverse_obj(video_info
, ('download', 'url'), expected_type
=url_or_none
)
336 'format_id': 'download',
337 'url': self
._proto
_relative
_url
(download_url
),
342 self
._remove
_duplicate
_formats
(formats
)
343 self
._sort
_formats
(formats
)
346 for thumbnail_name
in ('thumbnail', 'cover', 'dynamicCover', 'originCover'):
347 if aweme_detail
.get(thumbnail_name
):
349 'url': self
._proto
_relative
_url
(aweme_detail
[thumbnail_name
]),
355 'id': traverse_obj(aweme_detail
, 'id', 'awemeId', expected_type
=str_or_none
),
356 'title': aweme_detail
.get('desc'),
357 'duration': try_get(aweme_detail
, lambda x
: x
['video']['duration'], int),
358 'view_count': int_or_none(stats_info
.get('playCount')),
359 'like_count': int_or_none(stats_info
.get('diggCount')),
360 'repost_count': int_or_none(stats_info
.get('shareCount')),
361 'comment_count': int_or_none(stats_info
.get('commentCount')),
362 'timestamp': int_or_none(aweme_detail
.get('createTime')),
363 'creator': str_or_none(author_info
.get('nickname')),
364 'uploader': str_or_none(author_info
.get('uniqueId') or aweme_detail
.get('author')),
365 'uploader_id': str_or_none(author_info
.get('id') or aweme_detail
.get('authorId')),
366 'uploader_url': user_url
,
367 'track': str_or_none(music_info
.get('title')),
368 'album': str_or_none(music_info
.get('album')) or None,
369 'artist': str_or_none(music_info
.get('authorName')),
371 'thumbnails': thumbnails
,
372 'description': str_or_none(aweme_detail
.get('desc')),
374 'Referer': webpage_url
379 class TikTokIE(TikTokBaseIE
):
380 _VALID_URL
= r
'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)/video)/(?P<id>\d+)'
381 _EMBED_REGEX
= [rf
'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})']
384 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
385 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
387 'id': '6748451240264420610',
389 'title': '#jassmanak #lehanga #leenabhushan',
390 'description': '#jassmanak #lehanga #leenabhushan',
394 'uploader': 'leenabhushan',
395 'uploader_id': '6691488002098119685',
396 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
397 'creator': 'facestoriesbyleenabh',
398 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
399 'upload_date': '20191016',
400 'timestamp': 1571246252,
404 'comment_count': int,
405 'artist': 'Ysrbeats',
410 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
411 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
413 'id': '6742501081818877190',
415 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
416 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
420 'uploader': 'patrox',
421 'uploader_id': '18702747',
422 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
424 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
425 'upload_date': '20190930',
426 'timestamp': 1569860870,
430 'comment_count': int,
431 'artist': 'Evan Todd, Jessica Keenan Wynn, Alice Lee, Barrett Wilbert Weed & Jon Eidson',
435 # Banned audio, only available on the app
436 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402',
438 'id': '6984138651336838402',
440 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
441 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥',
442 'uploader': 'barudakhb_',
443 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
444 'uploader_id': '6974687867511718913',
445 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d',
446 'track': 'Boka Dance',
447 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6',
448 'timestamp': 1626121503,
450 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
451 'upload_date': '20210712',
455 'comment_count': int,
458 # Sponsored video, only available with feed workaround
459 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561',
461 'id': '7042692929109986561',
463 'title': 'Slap and Run!',
464 'description': 'Slap and Run!',
465 'uploader': 'user440922249',
466 'creator': 'Slap And Run',
467 'uploader_id': '7036055384943690754',
468 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_',
469 'track': 'Promoted Music',
470 'timestamp': 1639754738,
472 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
473 'upload_date': '20211217',
477 'comment_count': int,
479 'expected_warnings': ['trying with webpage', 'Unable to find video in feed']
481 # Video without title and description
482 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694',
484 'id': '7059698374567611694',
486 'title': 'TikTok video #7059698374567611694',
488 'uploader': 'pokemonlife22',
489 'creator': 'Pokemon',
490 'uploader_id': '6820838815978423302',
491 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W',
492 'track': 'original sound',
493 'timestamp': 1643714123,
495 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
496 'upload_date': '20220201',
501 'comment_count': int,
504 # hydration JSON is sent in a <script> element
505 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713',
507 'id': '7065799023130643713',
509 'title': '#denidil#денидил',
510 'description': '#denidil#денидил',
511 'uploader': 'denidil6',
512 'uploader_id': '7046664115636405250',
513 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ',
514 'artist': 'Holocron Music',
515 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
516 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night',
517 'timestamp': 1645134536,
519 'upload_date': '20220217',
523 'comment_count': int,
525 'expected_warnings': ['trying feed workaround', 'Unable to find video in feed']
527 # Auto-captions available
528 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758',
529 'only_matching': True
532 def _extract_aweme_app(self
, aweme_id
):
534 aweme_detail
= self
._call
_api
('aweme/detail', {'aweme_id': aweme_id}
, aweme_id
,
535 note
='Downloading video details', errnote
='Unable to download video details').get('aweme_detail')
537 raise ExtractorError('Video not available', video_id
=aweme_id
)
538 except ExtractorError
as e
:
539 self
.report_warning(f
'{e.orig_msg}; trying feed workaround')
540 feed_list
= self
._call
_api
('feed', {'aweme_id': aweme_id}
, aweme_id
,
541 note
='Downloading video feed', errnote
='Unable to download video feed').get('aweme_list') or []
542 aweme_detail
= next((aweme
for aweme
in feed_list
if str(aweme
.get('aweme_id')) == aweme_id
), None)
544 raise ExtractorError('Unable to find video in feed', video_id
=aweme_id
)
545 return self
._parse
_aweme
_video
_app
(aweme_detail
)
547 def _real_extract(self
, url
):
548 video_id
, user_id
= self
._match
_valid
_url
(url
).group('id', 'user_id')
550 return self
._extract
_aweme
_app
(video_id
)
551 except ExtractorError
as e
:
552 self
.report_warning(f
'{e}; trying with webpage')
554 url
= self
._create
_url
(user_id
, video_id
)
555 webpage
= self
._download
_webpage
(url
, video_id
, headers
={'User-Agent': 'User-Agent:Mozilla/5.0'}
)
556 next_data
= self
._search
_nextjs
_data
(webpage
, video_id
, default
='{}')
558 status
= traverse_obj(next_data
, ('props', 'pageProps', 'statusCode'), expected_type
=int) or 0
559 video_data
= traverse_obj(next_data
, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type
=dict)
561 sigi_data
= self
._get
_sigi
_state
(webpage
, video_id
)
562 status
= traverse_obj(sigi_data
, ('VideoPage', 'statusCode'), expected_type
=int) or 0
563 video_data
= traverse_obj(sigi_data
, ('ItemModule', video_id
), expected_type
=dict)
566 return self
._parse
_aweme
_video
_web
(video_data
, url
)
567 elif status
== 10216:
568 raise ExtractorError('This video is private', expected
=True)
569 raise ExtractorError('Video not available', video_id
=video_id
)
572 class TikTokUserIE(TikTokBaseIE
):
573 IE_NAME
= 'tiktok:user'
574 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
576 'url': 'https://tiktok.com/@corgibobaa?lang=en',
577 'playlist_mincount': 45,
579 'id': '6935371178089399301',
580 'title': 'corgibobaa',
581 'thumbnail': r
're:https://.+_1080x1080\.webp'
583 'expected_warnings': ['Retrying']
585 'url': 'https://www.tiktok.com/@6820838815978423302',
586 'playlist_mincount': 5,
588 'id': '6820838815978423302',
589 'title': '6820838815978423302',
590 'thumbnail': r
're:https://.+_1080x1080\.webp'
592 'expected_warnings': ['Retrying']
594 'url': 'https://www.tiktok.com/@meme',
595 'playlist_mincount': 593,
597 'id': '79005827461758976',
599 'thumbnail': r
're:https://.+_1080x1080\.webp'
601 'expected_warnings': ['Retrying']
604 r
''' # TODO: Fix by adding _signature to api_url
605 def _entries(self, webpage, user_id, username):
606 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
607 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
608 if not verifyfp_cookie:
609 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
610 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='
612 for page in itertools.count():
613 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
614 for video in data_json.get('itemList', []):
615 video_id = video['id']
616 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
617 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
618 if not data_json.get('hasMore'):
620 cursor = data_json['cursor']
623 def _video_entries_api(self
, webpage
, user_id
, username
):
629 'retry_type': 'no_retry',
630 '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.
633 for page
in itertools
.count(1):
634 for retry
in self
.RetryManager():
636 post_list
= self
._call
_api
(
637 'aweme/post', query
, username
, note
=f
'Downloading user video list page {page}',
638 errnote
='Unable to download user video list')
639 except ExtractorError
as e
:
640 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
644 yield from post_list
.get('aweme_list', [])
645 if not post_list
.get('has_more'):
647 query
['max_cursor'] = post_list
['max_cursor']
649 def _entries_api(self
, user_id
, videos
):
652 **self
._parse
_aweme
_video
_app
(video
),
653 'extractor_key': TikTokIE
.ie_key(),
654 'extractor': 'TikTok',
655 'webpage_url': f
'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}',
658 def _real_extract(self
, url
):
659 user_name
= self
._match
_id
(url
)
660 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
661 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
663 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID', default
=None) or user_name
665 videos
= LazyList(self
._video
_entries
_api
(webpage
, user_id
, user_name
))
666 thumbnail
= traverse_obj(videos
, (0, 'author', 'avatar_larger', 'url_list', 0))
668 return self
.playlist_result(self
._entries
_api
(user_id
, videos
), user_id
, user_name
, thumbnail
=thumbnail
)
671 class TikTokBaseListIE(TikTokBaseIE
):
672 def _entries(self
, list_id
, display_id
):
674 self
._QUERY
_NAME
: list_id
,
678 'device_id': ''.join(random
.choice(string
.digits
) for i
in range(19))
681 for page
in itertools
.count(1):
682 for retry
in self
.RetryManager():
684 post_list
= self
._call
_api
(
685 self
._API
_ENDPOINT
, query
, display_id
, note
=f
'Downloading video list page {page}',
686 errnote
='Unable to download video list')
687 except ExtractorError
as e
:
688 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0:
692 for video
in post_list
.get('aweme_list', []):
694 **self
._parse
_aweme
_video
_app
(video
),
695 'extractor_key': TikTokIE
.ie_key(),
696 'extractor': 'TikTok',
697 'webpage_url': f
'https://tiktok.com/@_/video/{video["aweme_id"]}',
699 if not post_list
.get('has_more'):
701 query
['cursor'] = post_list
['cursor']
703 def _real_extract(self
, url
):
704 list_id
= self
._match
_id
(url
)
705 return self
.playlist_result(self
._entries
(list_id
, list_id
), list_id
)
708 class TikTokSoundIE(TikTokBaseListIE
):
709 IE_NAME
= 'tiktok:sound'
710 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
711 _QUERY_NAME
= 'music_id'
712 _API_ENDPOINT
= 'music/aweme'
714 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en',
715 'playlist_mincount': 100,
717 'id': '6956990112127585029'
719 'expected_warnings': ['Retrying']
721 # Actual entries are less than listed video count
722 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381',
723 'playlist_mincount': 2182,
725 'id': '7036843036118469381'
727 'expected_warnings': ['Retrying']
731 class TikTokEffectIE(TikTokBaseListIE
):
732 IE_NAME
= 'tiktok:effect'
733 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?'
734 _QUERY_NAME
= 'sticker_id'
735 _API_ENDPOINT
= 'sticker/aweme'
737 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156',
738 'playlist_mincount': 100,
742 'expected_warnings': ['Retrying']
744 # Different entries between mobile and web, depending on region
745 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565',
746 'only_matching': True
750 class TikTokTagIE(TikTokBaseListIE
):
751 IE_NAME
= 'tiktok:tag'
752 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)'
753 _QUERY_NAME
= 'ch_id'
754 _API_ENDPOINT
= 'challenge/aweme'
756 'url': 'https://tiktok.com/tag/hello2018',
757 'playlist_mincount': 39,
760 'title': 'hello2018',
762 'expected_warnings': ['Retrying']
764 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1',
765 'only_matching': True
768 def _real_extract(self
, url
):
769 display_id
= self
._match
_id
(url
)
770 webpage
= self
._download
_webpage
(url
, display_id
, headers
={
771 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
773 tag_id
= self
._html
_search
_regex
(r
'snssdk\d*://challenge/detail/(\d+)', webpage
, 'tag ID')
774 return self
.playlist_result(self
._entries
(tag_id
, display_id
), tag_id
, display_id
)
777 class DouyinIE(TikTokIE
):
778 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
780 'url': 'https://www.douyin.com/video/6961737553342991651',
781 'md5': '10523312c8b8100f353620ac9dc8f067',
783 'id': '6961737553342991651',
785 'title': '#杨超越 小小水手带你去远航❤️',
787 'upload_date': '20210513',
788 'timestamp': 1620905839,
789 'uploader_id': '110403406559',
793 'comment_count': int,
796 'url': 'https://www.douyin.com/video/6982497745948921092',
797 'md5': 'd78408c984b9b5102904cf6b6bc2d712',
799 'id': '6982497745948921092',
801 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
802 'uploader': '杨超越工作室',
803 'upload_date': '20210708',
804 'timestamp': 1625739481,
805 'uploader_id': '408654318141572',
809 'comment_count': int,
812 'url': 'https://www.douyin.com/video/6953975910773099811',
813 'md5': '72e882e24f75064c218b76c8b713c185',
815 'id': '6953975910773099811',
817 'title': '#一起看海 出现在你的夏日里',
819 'upload_date': '20210422',
820 'timestamp': 1619098692,
821 'uploader_id': '110403406559',
825 'comment_count': int,
828 'url': 'https://www.douyin.com/video/6950251282489675042',
829 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
831 'id': '6950251282489675042',
833 'title': '哈哈哈,成功了哈哈哈哈哈哈',
835 'upload_date': '20210412',
836 'timestamp': 1618231483,
837 'uploader_id': '110403406559',
841 'comment_count': int,
844 'url': 'https://www.douyin.com/video/6963263655114722595',
845 'md5': '1abe1c477d05ee62efb40bf2329957cf',
847 'id': '6963263655114722595',
849 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
851 'upload_date': '20210517',
852 'timestamp': 1621261163,
853 'uploader_id': '110403406559',
857 'comment_count': int,
860 _APP_VERSIONS
= [('9.6.0', '960')]
863 _API_HOSTNAME
= 'aweme.snssdk.com'
864 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
865 _WEBPAGE_HOST
= 'https://www.douyin.com/'
867 def _real_extract(self
, url
):
868 video_id
= self
._match
_id
(url
)
871 return self
._extract
_aweme
_app
(video_id
)
872 except ExtractorError
as e
:
873 self
.report_warning(f
'{e}; trying with webpage')
875 webpage
= self
._download
_webpage
(url
, video_id
)
876 render_data_json
= self
._search
_regex
(
877 r
'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^
>]*>(%7B
.+%7D
)</script
>',
878 webpage, 'render data
', default=None)
879 if not render_data_json:
880 # TODO: Run verification challenge code to generate signature cookies
881 raise ExtractorError('Fresh
cookies (not necessarily logged
in) are needed
')
883 render_data = self._parse_json(
884 render_data_json, video_id, transform_source=compat_urllib_parse_unquote)
885 return self._parse_aweme_video_web(get_first(render_data, ('aweme
', 'detail
')), url)
888 class TikTokVMIE(InfoExtractor):
889 _VALID_URL = r'https?
://(?
:vm|vt
)\
.tiktok\
.com
/(?P
<id>\w
+)'
890 IE_NAME = 'vm
.tiktok
'
893 'url
': 'https
://vm
.tiktok
.com
/ZSe4FqkKd
',
895 'id': '7023491746608712966',
897 'title
': 'md5
:5607564db90271abbbf8294cca77eddd
',
898 'description
': 'md5
:5607564db90271abbbf8294cca77eddd
',
900 'upload_date
': '20211026',
901 'uploader_id
': '7007385080558846981',
904 'track
': 'original sound
',
905 'uploader
': 'susmandem
',
906 'timestamp
': 1635284105,
907 'thumbnail
': r're
:https
://.+\
.webp
.*',
910 'comment_count
': int,
912 'uploader_url
': 'https
://www
.tiktok
.com
/@MS4wLjABAAAAXcNoOEOxVyBzuII_E--T0MeCrLP0ay1Sm6x_n3dluiWEoWZD0VlQOytwad4W0i0n
',
915 'url
': 'https
://vt
.tiktok
.com
/ZSe4FqkKd
',
916 'only_matching
': True,
919 def _real_extract(self, url):
920 new_url = self._request_webpage(
921 HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).geturl()
922 if self.suitable(new_url): # Prevent infinite loop in case redirect fails
923 raise UnsupportedError(new_url)
924 return self.url_result(new_url)