]>
Commit | Line | Data |
---|---|---|
f7f18f90 | 1 | import itertools |
b801cd71 | 2 | import json |
bd9ff55b | 3 | import random |
216bcb66 | 4 | import re |
bd9ff55b M |
5 | import string |
6 | import time | |
cb61e20c | 7 | import uuid |
1ead840d KS |
8 | |
9 | from .common import InfoExtractor | |
9ff94664 | 10 | from ..compat import compat_urllib_parse_urlparse |
3d2623a8 | 11 | from ..networking import HEADRequest |
1ead840d | 12 | from ..utils import ( |
ce18a19b | 13 | ExtractorError, |
b801cd71 | 14 | LazyList, |
11e1c2e3 | 15 | UnsupportedError, |
933ed882 | 16 | UserNotLive, |
8ceb07e8 | 17 | determine_ext, |
216bcb66 | 18 | format_field, |
1ead840d | 19 | int_or_none, |
34921b43 | 20 | join_nonempty, |
216bcb66 | 21 | merge_dicts, |
b801cd71 | 22 | qualities, |
ba723997 | 23 | remove_start, |
e0585e65 | 24 | srt_subtitles_timecode, |
1ead840d | 25 | str_or_none, |
bd9ff55b | 26 | traverse_obj, |
216bcb66 | 27 | try_call, |
bd9ff55b | 28 | try_get, |
943d5ab1 | 29 | url_or_none, |
1ead840d KS |
30 | ) |
31 | ||
32 | ||
0fd6661e | 33 | class TikTokBaseIE(InfoExtractor): |
943d5ab1 | 34 | _UPLOADER_URL_FORMAT = 'https://www.tiktok.com/@%s' |
53dad39e | 35 | _WEBPAGE_HOST = 'https://www.tiktok.com/' |
be1f331f | 36 | QUALITIES = ('360p', '540p', '720p', '1080p') |
ce18a19b | 37 | |
cb61e20c | 38 | _APP_INFO_DEFAULTS = { |
39 | # unique "install id" | |
40 | 'iid': None, | |
41 | # TikTok (KR/PH/TW/TH/VN) = trill, TikTok (rest of world) = musical_ly, Douyin = aweme | |
42 | 'app_name': 'musical_ly', | |
43 | 'app_version': '34.1.2', | |
44 | 'manifest_app_version': '2023401020', | |
45 | # "app id": aweme = 1128, trill = 1180, musical_ly = 1233, universal = 0 | |
46 | 'aid': '0', | |
47 | } | |
48 | _KNOWN_APP_INFO = [ | |
49 | '7351144126450059040', | |
50 | '7351149742343391009', | |
51 | '7351153174894626592', | |
52 | ] | |
53 | _APP_INFO_POOL = None | |
54 | _APP_INFO = None | |
55 | _APP_USER_AGENT = None | |
56 | ||
c4cbd3be | 57 | @property |
58 | def _API_HOSTNAME(self): | |
59 | return self._configuration_arg( | |
8c05b3eb | 60 | 'api_hostname', ['api22-normal-c-useast2a.tiktokv.com'], ie_key=TikTokIE)[0] |
c4cbd3be | 61 | |
cb61e20c | 62 | def _get_next_app_info(self): |
63 | if self._APP_INFO_POOL is None: | |
64 | defaults = { | |
65 | key: self._configuration_arg(key, [default], ie_key=TikTokIE)[0] | |
66 | for key, default in self._APP_INFO_DEFAULTS.items() | |
67 | if key != 'iid' | |
68 | } | |
69 | app_info_list = ( | |
70 | self._configuration_arg('app_info', ie_key=TikTokIE) | |
71 | or random.sample(self._KNOWN_APP_INFO, len(self._KNOWN_APP_INFO))) | |
72 | self._APP_INFO_POOL = [ | |
73 | {**defaults, **dict( | |
74 | (k, v) for k, v in zip(self._APP_INFO_DEFAULTS, app_info.split('/')) if v | |
75 | )} for app_info in app_info_list | |
76 | ] | |
77 | ||
78 | if not self._APP_INFO_POOL: | |
79 | return False | |
80 | ||
81 | self._APP_INFO = self._APP_INFO_POOL.pop(0) | |
82 | ||
83 | app_name = self._APP_INFO['app_name'] | |
84 | version = self._APP_INFO['manifest_app_version'] | |
85 | if app_name == 'musical_ly': | |
86 | package = f'com.zhiliaoapp.musically/{version}' | |
87 | else: # trill, aweme | |
88 | package = f'com.ss.android.ugc.{app_name}/{version}' | |
89 | self._APP_USER_AGENT = f'{package} (Linux; U; Android 13; en_US; Pixel 7; Build/TD1A.220804.031; Cronet/58.0.2991.0)' | |
90 | ||
91 | return True | |
92 | ||
b801cd71 | 93 | @staticmethod |
94 | def _create_url(user_id, video_id): | |
95 | return f'https://www.tiktok.com/@{user_id or "_"}/video/{video_id}' | |
96 | ||
a39a7ba8 | 97 | def _get_sigi_state(self, webpage, display_id): |
069cbece | 98 | return self._search_json( |
99 | r'<script[^>]+\bid="(?:SIGI_STATE|sigi-persisted-data)"[^>]*>', webpage, | |
d9b4154c | 100 | 'sigi state', display_id, end_pattern=r'</script>', default={}) |
101 | ||
102 | def _get_universal_data(self, webpage, display_id): | |
103 | return traverse_obj(self._search_json( | |
104 | r'<script[^>]+\bid="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>', webpage, | |
105 | 'universal data', display_id, end_pattern=r'</script>', default={}), | |
106 | ('__DEFAULT_SCOPE__', {dict})) or {} | |
a39a7ba8 | 107 | |
cb61e20c | 108 | def _call_api_impl(self, ep, query, video_id, fatal=True, |
046cab39 | 109 | note='Downloading API JSON', errnote='Unable to download API page'): |
efa944f4 | 110 | self._set_cookie(self._API_HOSTNAME, 'odin_tt', ''.join(random.choices('0123456789abcdef', k=160))) |
046cab39 M |
111 | webpage_cookies = self._get_cookies(self._WEBPAGE_HOST) |
112 | if webpage_cookies.get('sid_tt'): | |
113 | self._set_cookie(self._API_HOSTNAME, 'sid_tt', webpage_cookies['sid_tt'].value) | |
114 | return self._download_json( | |
115 | 'https://%s/aweme/v1/%s/' % (self._API_HOSTNAME, ep), video_id=video_id, | |
116 | fatal=fatal, note=note, errnote=errnote, headers={ | |
cb61e20c | 117 | 'User-Agent': self._APP_USER_AGENT, |
046cab39 M |
118 | 'Accept': 'application/json', |
119 | }, query=query) | |
120 | ||
cb61e20c | 121 | def _build_api_query(self, query): |
046cab39 | 122 | return { |
0fd6661e | 123 | **query, |
bd9ff55b | 124 | 'device_platform': 'android', |
cb61e20c | 125 | 'os': 'android', |
126 | 'ssmix': 'a', | |
127 | '_rticket': int(time.time() * 1000), | |
128 | 'cdid': str(uuid.uuid4()), | |
129 | 'channel': 'googleplay', | |
130 | 'aid': self._APP_INFO['aid'], | |
131 | 'app_name': self._APP_INFO['app_name'], | |
132 | 'version_code': ''.join((f'{int(v):02d}' for v in self._APP_INFO['app_version'].split('.'))), | |
133 | 'version_name': self._APP_INFO['app_version'], | |
134 | 'manifest_version_code': self._APP_INFO['manifest_app_version'], | |
135 | 'update_version_code': self._APP_INFO['manifest_app_version'], | |
136 | 'ab_version': self._APP_INFO['app_version'], | |
c2a1bdb0 | 137 | 'resolution': '1080*2400', |
bd9ff55b | 138 | 'dpi': 420, |
cb61e20c | 139 | 'device_type': 'Pixel 7', |
140 | 'device_brand': 'Google', | |
141 | 'language': 'en', | |
bd9ff55b | 142 | 'os_api': '29', |
cb61e20c | 143 | 'os_version': '13', |
144 | 'ac': 'wifi', | |
145 | 'is_pad': '0', | |
146 | 'current_region': 'US', | |
147 | 'app_type': 'normal', | |
bd9ff55b | 148 | 'sys_region': 'US', |
cb61e20c | 149 | 'last_install_time': int(time.time()) - random.randint(86400, 1123200), |
bd9ff55b | 150 | 'timezone_name': 'America/New_York', |
cb61e20c | 151 | 'residence': 'US', |
152 | 'app_language': 'en', | |
bd9ff55b | 153 | 'timezone_offset': '-14400', |
cb61e20c | 154 | 'host_abi': 'armeabi-v7a', |
155 | 'locale': 'en', | |
156 | 'ac2': 'wifi5g', | |
157 | 'uoo': '1', | |
fc53ec13 | 158 | 'carrier_region': 'US', |
cb61e20c | 159 | 'op_region': 'US', |
160 | 'build_number': self._APP_INFO['app_version'], | |
161 | 'region': 'US', | |
162 | 'ts': int(time.time()), | |
163 | 'iid': self._APP_INFO['iid'], | |
164 | 'device_id': random.randint(7250000000000000000, 7351147085025500000), | |
165 | 'openudid': ''.join(random.choices('0123456789abcdef', k=16)), | |
bd9ff55b | 166 | } |
046cab39 M |
167 | |
168 | def _call_api(self, ep, query, video_id, fatal=True, | |
169 | note='Downloading API JSON', errnote='Unable to download API page'): | |
cb61e20c | 170 | if not self._APP_INFO and not self._get_next_app_info(): |
171 | message = 'No working app info is available' | |
172 | if fatal: | |
173 | raise ExtractorError(message, expected=True) | |
174 | else: | |
175 | self.report_warning(message) | |
176 | return | |
177 | ||
178 | max_tries = len(self._APP_INFO_POOL) + 1 # _APP_INFO_POOL + _APP_INFO | |
179 | for count in itertools.count(1): | |
180 | self.write_debug(str(self._APP_INFO)) | |
181 | real_query = self._build_api_query(query) | |
046cab39 | 182 | try: |
cb61e20c | 183 | return self._call_api_impl(ep, real_query, video_id, fatal, note, errnote) |
046cab39 M |
184 | except ExtractorError as e: |
185 | if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0: | |
cb61e20c | 186 | message = str(e.cause or e.msg) |
187 | if not self._get_next_app_info(): | |
046cab39 | 188 | if fatal: |
cb61e20c | 189 | raise |
046cab39 | 190 | else: |
cb61e20c | 191 | self.report_warning(message) |
046cab39 | 192 | return |
cb61e20c | 193 | self.report_warning(f'{message}. Retrying... (attempt {count} of {max_tries})') |
046cab39 | 194 | continue |
cb61e20c | 195 | raise |
0fd6661e | 196 | |
ba723997 | 197 | def _extract_aweme_app(self, aweme_id): |
198 | feed_list = self._call_api( | |
199 | 'feed', {'aweme_id': aweme_id}, aweme_id, note='Downloading video feed', | |
200 | errnote='Unable to download video feed').get('aweme_list') or [] | |
201 | aweme_detail = next((aweme for aweme in feed_list if str(aweme.get('aweme_id')) == aweme_id), None) | |
202 | if not aweme_detail: | |
203 | raise ExtractorError('Unable to find video in feed', video_id=aweme_id) | |
204 | return self._parse_aweme_video_app(aweme_detail) | |
205 | ||
e0585e65 M |
206 | def _get_subtitles(self, aweme_detail, aweme_id): |
207 | # TODO: Extract text positioning info | |
208 | subtitles = {} | |
ba723997 | 209 | # aweme/detail endpoint subs |
e0585e65 | 210 | captions_info = traverse_obj( |
ba723997 | 211 | aweme_detail, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type=dict) |
e0585e65 M |
212 | for caption in captions_info: |
213 | caption_url = traverse_obj(caption, ('url', 'url_list', ...), expected_type=url_or_none, get_all=False) | |
214 | if not caption_url: | |
215 | continue | |
216 | caption_json = self._download_json( | |
217 | caption_url, aweme_id, note='Downloading captions', errnote='Unable to download captions', fatal=False) | |
218 | if not caption_json: | |
219 | continue | |
220 | subtitles.setdefault(caption.get('language', 'en'), []).append({ | |
221 | 'ext': 'srt', | |
222 | 'data': '\n\n'.join( | |
223 | f'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}' | |
224 | for i, line in enumerate(caption_json['utterances']) if line.get('text')) | |
225 | }) | |
ba723997 | 226 | # feed endpoint subs |
227 | if not subtitles: | |
228 | for caption in traverse_obj(aweme_detail, ('video', 'cla_info', 'caption_infos', ...), expected_type=dict): | |
229 | if not caption.get('url'): | |
230 | continue | |
231 | subtitles.setdefault(caption.get('lang') or 'en', []).append({ | |
232 | 'ext': remove_start(caption.get('caption_format'), 'web'), | |
233 | 'url': caption['url'], | |
234 | }) | |
235 | # webpage subs | |
236 | if not subtitles: | |
237 | for caption in traverse_obj(aweme_detail, ('video', 'subtitleInfos', ...), expected_type=dict): | |
238 | if not caption.get('Url'): | |
239 | continue | |
240 | subtitles.setdefault(caption.get('LanguageCodeName') or 'en', []).append({ | |
241 | 'ext': remove_start(caption.get('Format'), 'web'), | |
242 | 'url': caption['Url'], | |
243 | }) | |
e0585e65 M |
244 | return subtitles |
245 | ||
943d5ab1 | 246 | def _parse_aweme_video_app(self, aweme_detail): |
0fd6661e | 247 | aweme_id = aweme_detail['aweme_id'] |
bd9ff55b M |
248 | video_info = aweme_detail['video'] |
249 | ||
250 | def parse_url_key(url_key): | |
251 | format_id, codec, res, bitrate = self._search_regex( | |
252 | r'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key, | |
253 | 'url key', default=(None, None, None, None), group=('id', 'codec', 'res', 'bitrate')) | |
254 | if not format_id: | |
255 | return {}, None | |
256 | return { | |
257 | 'format_id': format_id, | |
258 | 'vcodec': 'h265' if codec == 'bytevc1' else codec, | |
259 | 'tbr': int_or_none(bitrate, scale=1000) or None, | |
260 | 'quality': qualities(self.QUALITIES)(res), | |
261 | }, res | |
262 | ||
263 | known_resolutions = {} | |
264 | ||
b09bd0c1 | 265 | def audio_meta(url): |
266 | ext = determine_ext(url, default_ext='m4a') | |
8ceb07e8 | 267 | return { |
268 | 'format_note': 'Music track', | |
b09bd0c1 | 269 | 'ext': ext, |
270 | 'acodec': 'aac' if ext == 'm4a' else ext, | |
8ceb07e8 | 271 | 'vcodec': 'none', |
272 | 'width': None, | |
273 | 'height': None, | |
b09bd0c1 | 274 | } if ext == 'mp3' or '-music-' in url else {} |
8ceb07e8 | 275 | |
bd9ff55b M |
276 | def extract_addr(addr, add_meta={}): |
277 | parsed_meta, res = parse_url_key(addr.get('url_key', '')) | |
63f685f3 | 278 | is_bytevc2 = parsed_meta.get('vcodec') == 'bytevc2' |
bd9ff55b | 279 | if res: |
9ff94664 | 280 | known_resolutions.setdefault(res, {}).setdefault('height', int_or_none(addr.get('height'))) |
281 | known_resolutions[res].setdefault('width', int_or_none(addr.get('width'))) | |
bd9ff55b M |
282 | parsed_meta.update(known_resolutions.get(res, {})) |
283 | add_meta.setdefault('height', int_or_none(res[:-1])) | |
284 | return [{ | |
285 | 'url': url, | |
286 | 'filesize': int_or_none(addr.get('data_size')), | |
287 | 'ext': 'mp4', | |
288 | 'acodec': 'aac', | |
0fd6661e M |
289 | 'source_preference': -2 if 'aweme/v1' in url else -1, # Downloads from API might get blocked |
290 | **add_meta, **parsed_meta, | |
63f685f3 | 291 | # bytevc2 is bytedance's proprietary (unplayable) video codec |
292 | 'preference': -100 if is_bytevc2 else -1, | |
34921b43 | 293 | 'format_note': join_nonempty( |
63f685f3 | 294 | add_meta.get('format_note'), '(API)' if 'aweme/v1' in url else None, |
295 | '(UNPLAYABLE)' if is_bytevc2 else None, delim=' '), | |
b09bd0c1 | 296 | **audio_meta(url), |
bd9ff55b M |
297 | } for url in addr.get('url_list') or []] |
298 | ||
299 | # Hack: Add direct video links first to prioritize them when removing duplicate formats | |
300 | formats = [] | |
9ff94664 | 301 | width = int_or_none(video_info.get('width')) |
302 | height = int_or_none(video_info.get('height')) | |
bd9ff55b M |
303 | if video_info.get('play_addr'): |
304 | formats.extend(extract_addr(video_info['play_addr'], { | |
305 | 'format_id': 'play_addr', | |
306 | 'format_note': 'Direct video', | |
307 | 'vcodec': 'h265' if traverse_obj( | |
be1f331f | 308 | video_info, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002 |
9ff94664 | 309 | 'width': width, |
310 | 'height': height, | |
bd9ff55b M |
311 | })) |
312 | if video_info.get('download_addr'): | |
9ff94664 | 313 | download_addr = video_info['download_addr'] |
314 | dl_width = int_or_none(download_addr.get('width')) | |
315 | formats.extend(extract_addr(download_addr, { | |
bd9ff55b M |
316 | 'format_id': 'download_addr', |
317 | 'format_note': 'Download video%s' % (', watermarked' if video_info.get('has_watermark') else ''), | |
318 | 'vcodec': 'h264', | |
9ff94664 | 319 | 'width': dl_width or width, |
320 | 'height': try_call(lambda: int(dl_width / 0.5625)) or height, # download_addr['height'] is wrong | |
0fd6661e | 321 | 'preference': -2 if video_info.get('has_watermark') else -1, |
bd9ff55b M |
322 | })) |
323 | if video_info.get('play_addr_h264'): | |
324 | formats.extend(extract_addr(video_info['play_addr_h264'], { | |
325 | 'format_id': 'play_addr_h264', | |
326 | 'format_note': 'Direct video', | |
327 | 'vcodec': 'h264', | |
328 | })) | |
329 | if video_info.get('play_addr_bytevc1'): | |
330 | formats.extend(extract_addr(video_info['play_addr_bytevc1'], { | |
331 | 'format_id': 'play_addr_bytevc1', | |
332 | 'format_note': 'Direct video', | |
333 | 'vcodec': 'h265', | |
334 | })) | |
335 | ||
336 | for bitrate in video_info.get('bit_rate', []): | |
337 | if bitrate.get('play_addr'): | |
338 | formats.extend(extract_addr(bitrate['play_addr'], { | |
339 | 'format_id': bitrate.get('gear_name'), | |
340 | 'format_note': 'Playback video', | |
341 | 'tbr': try_get(bitrate, lambda x: x['bit_rate'] / 1000), | |
342 | 'vcodec': 'h265' if traverse_obj( | |
343 | bitrate, 'is_bytevc1', 'is_h265') else 'h264', | |
943d5ab1 | 344 | 'fps': bitrate.get('FPS'), |
bd9ff55b M |
345 | })) |
346 | ||
347 | self._remove_duplicate_formats(formats) | |
6134fbeb M |
348 | auth_cookie = self._get_cookies(self._WEBPAGE_HOST).get('sid_tt') |
349 | if auth_cookie: | |
350 | for f in formats: | |
be1f331f | 351 | self._set_cookie(compat_urllib_parse_urlparse(f['url']).hostname, 'sid_tt', auth_cookie.value) |
bd9ff55b M |
352 | |
353 | thumbnails = [] | |
354 | for cover_id in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak', | |
355 | 'origin_cover', 'dynamic_cover'): | |
92593690 | 356 | for cover_url in traverse_obj(video_info, (cover_id, 'url_list', ...)): |
357 | thumbnails.append({ | |
358 | 'id': cover_id, | |
359 | 'url': cover_url, | |
360 | }) | |
361 | ||
362 | stats_info = aweme_detail.get('statistics') or {} | |
363 | author_info = aweme_detail.get('author') or {} | |
364 | music_info = aweme_detail.get('music') or {} | |
943d5ab1 M |
365 | user_url = self._UPLOADER_URL_FORMAT % (traverse_obj(author_info, |
366 | 'sec_uid', 'id', 'uid', 'unique_id', | |
367 | expected_type=str_or_none, get_all=False)) | |
6839ae1f | 368 | labels = traverse_obj(aweme_detail, ('hybrid_label', ..., 'text'), expected_type=str) |
bd9ff55b M |
369 | |
370 | contained_music_track = traverse_obj( | |
371 | music_info, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type=str) | |
372 | contained_music_author = traverse_obj( | |
373 | music_info, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type=str) | |
374 | ||
375 | is_generic_og_trackname = music_info.get('is_original_sound') and music_info.get('title') == 'original sound - %s' % music_info.get('owner_handle') | |
376 | if is_generic_og_trackname: | |
377 | music_track, music_author = contained_music_track or 'original sound', contained_music_author | |
378 | else: | |
f4f9f6d0 | 379 | music_track, music_author = music_info.get('title'), traverse_obj(music_info, ('author', {str})) |
bd9ff55b M |
380 | |
381 | return { | |
382 | 'id': aweme_id, | |
92593690 | 383 | **traverse_obj(aweme_detail, { |
384 | 'title': ('desc', {str}), | |
385 | 'description': ('desc', {str}), | |
386 | 'timestamp': ('create_time', {int_or_none}), | |
387 | }), | |
388 | **traverse_obj(stats_info, { | |
389 | 'view_count': 'play_count', | |
390 | 'like_count': 'digg_count', | |
391 | 'repost_count': 'share_count', | |
392 | 'comment_count': 'comment_count', | |
393 | }, expected_type=int_or_none), | |
394 | **traverse_obj(author_info, { | |
f4f9f6d0 | 395 | 'uploader': ('unique_id', {str}), |
396 | 'uploader_id': ('uid', {str_or_none}), | |
397 | 'creators': ('nickname', {str}, {lambda x: [x] if x else None}), # for compat | |
398 | 'channel': ('nickname', {str}), | |
399 | 'channel_id': ('sec_uid', {str}), | |
400 | }), | |
943d5ab1 | 401 | 'uploader_url': user_url, |
bd9ff55b M |
402 | 'track': music_track, |
403 | 'album': str_or_none(music_info.get('album')) or None, | |
f4f9f6d0 | 404 | 'artists': re.split(r'(?:, | & )', music_author) if music_author else None, |
bd9ff55b | 405 | 'formats': formats, |
e0585e65 | 406 | 'subtitles': self.extract_subtitles(aweme_detail, aweme_id), |
bd9ff55b | 407 | 'thumbnails': thumbnails, |
53dad39e M |
408 | 'duration': int_or_none(traverse_obj(video_info, 'duration', ('download_addr', 'duration')), scale=1000), |
409 | 'availability': self._availability( | |
410 | is_private='Private' in labels, | |
411 | needs_subscription='Friends only' in labels, | |
9f14daf2 | 412 | is_unlisted='Followers only' in labels), |
413 | '_format_sort_fields': ('quality', 'codec', 'size', 'br'), | |
bd9ff55b M |
414 | } |
415 | ||
92593690 | 416 | def _parse_aweme_video_web(self, aweme_detail, webpage_url, video_id): |
943d5ab1 | 417 | video_info = aweme_detail['video'] |
11aa91a1 | 418 | author_info = traverse_obj(aweme_detail, 'authorInfo', 'author', expected_type=dict, default={}) |
943d5ab1 M |
419 | music_info = aweme_detail.get('music') or {} |
420 | stats_info = aweme_detail.get('stats') or {} | |
92593690 | 421 | channel_id = traverse_obj(author_info or aweme_detail, (('authorSecId', 'secUid'), {str}), get_all=False) |
422 | user_url = self._UPLOADER_URL_FORMAT % channel_id if channel_id else None | |
943d5ab1 M |
423 | |
424 | formats = [] | |
92593690 | 425 | width = int_or_none(video_info.get('width')) |
426 | height = int_or_none(video_info.get('height')) | |
427 | ||
428 | for play_url in traverse_obj(video_info, ('playAddr', ((..., 'src'), None), {url_or_none})): | |
429 | formats.append({ | |
943d5ab1 M |
430 | 'url': self._proto_relative_url(play_url), |
431 | 'ext': 'mp4', | |
432 | 'width': width, | |
433 | 'height': height, | |
92593690 | 434 | }) |
943d5ab1 | 435 | |
92593690 | 436 | for download_url in traverse_obj(video_info, (('downloadAddr', ('download', 'url')), {url_or_none})): |
943d5ab1 M |
437 | formats.append({ |
438 | 'format_id': 'download', | |
439 | 'url': self._proto_relative_url(download_url), | |
440 | 'ext': 'mp4', | |
441 | 'width': width, | |
442 | 'height': height, | |
443 | }) | |
92593690 | 444 | |
943d5ab1 | 445 | self._remove_duplicate_formats(formats) |
943d5ab1 M |
446 | |
447 | thumbnails = [] | |
92593690 | 448 | for thumb_url in traverse_obj(aweme_detail, ( |
449 | (None, 'video'), ('thumbnail', 'cover', 'dynamicCover', 'originCover'), {url_or_none})): | |
450 | thumbnails.append({ | |
451 | 'url': self._proto_relative_url(thumb_url), | |
452 | 'width': width, | |
453 | 'height': height, | |
454 | }) | |
943d5ab1 M |
455 | |
456 | return { | |
92593690 | 457 | 'id': video_id, |
458 | **traverse_obj(aweme_detail, { | |
459 | 'title': ('desc', {str}), | |
460 | 'description': ('desc', {str}), | |
461 | 'duration': ('video', 'duration', {int_or_none}), | |
462 | 'timestamp': ('createTime', {int_or_none}), | |
463 | }), | |
464 | **traverse_obj(author_info or aweme_detail, { | |
f4f9f6d0 | 465 | 'creators': ('nickname', {str}, {lambda x: [x] if x else None}), # for compat |
466 | 'channel': ('nickname', {str}), | |
92593690 | 467 | 'uploader': (('uniqueId', 'author'), {str}), |
468 | 'uploader_id': (('authorId', 'uid', 'id'), {str_or_none}), | |
469 | }, get_all=False), | |
470 | **traverse_obj(stats_info, { | |
471 | 'view_count': 'playCount', | |
472 | 'like_count': 'diggCount', | |
473 | 'repost_count': 'shareCount', | |
474 | 'comment_count': 'commentCount', | |
475 | }, expected_type=int_or_none), | |
476 | **traverse_obj(music_info, { | |
f4f9f6d0 | 477 | 'track': ('title', {str}), |
478 | 'album': ('album', {str}, {lambda x: x or None}), | |
479 | 'artists': ('authorName', {str}, {lambda x: [x] if x else None}), | |
480 | }), | |
92593690 | 481 | 'channel_id': channel_id, |
943d5ab1 | 482 | 'uploader_url': user_url, |
943d5ab1 M |
483 | 'formats': formats, |
484 | 'thumbnails': thumbnails, | |
943d5ab1 | 485 | 'http_headers': { |
92593690 | 486 | 'Referer': webpage_url, |
943d5ab1 M |
487 | } |
488 | } | |
489 | ||
0fd6661e M |
490 | |
491 | class TikTokIE(TikTokBaseIE): | |
c4cbd3be | 492 | _VALID_URL = r'https?://www\.tiktok\.com/(?:embed|@(?P<user_id>[\w\.-]+)?/video)/(?P<id>\d+)' |
bfd973ec | 493 | _EMBED_REGEX = [rf'<(?:script|iframe)[^>]+\bsrc=(["\'])(?P<url>{_VALID_URL})'] |
0fd6661e M |
494 | |
495 | _TESTS = [{ | |
496 | 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610', | |
0481e266 | 497 | 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7', |
0fd6661e M |
498 | 'info_dict': { |
499 | 'id': '6748451240264420610', | |
500 | 'ext': 'mp4', | |
501 | 'title': '#jassmanak #lehanga #leenabhushan', | |
502 | 'description': '#jassmanak #lehanga #leenabhushan', | |
503 | 'duration': 13, | |
0481e266 | 504 | 'height': 1024, |
505 | 'width': 576, | |
0fd6661e M |
506 | 'uploader': 'leenabhushan', |
507 | 'uploader_id': '6691488002098119685', | |
0481e266 | 508 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy', |
0fd6661e M |
509 | 'creator': 'facestoriesbyleenabh', |
510 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
511 | 'upload_date': '20191016', | |
512 | 'timestamp': 1571246252, | |
513 | 'view_count': int, | |
514 | 'like_count': int, | |
515 | 'repost_count': int, | |
516 | 'comment_count': int, | |
a44ca5a4 | 517 | 'artist': 'Ysrbeats', |
518 | 'album': 'Lehanga', | |
519 | 'track': 'Lehanga', | |
92593690 | 520 | }, |
521 | 'skip': '404 Not Found', | |
0fd6661e M |
522 | }, { |
523 | 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en', | |
0481e266 | 524 | 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b', |
0fd6661e M |
525 | 'info_dict': { |
526 | 'id': '6742501081818877190', | |
527 | 'ext': 'mp4', | |
528 | 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94', | |
529 | 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94', | |
530 | 'duration': 27, | |
531 | 'height': 960, | |
532 | 'width': 540, | |
533 | 'uploader': 'patrox', | |
534 | 'uploader_id': '18702747', | |
0481e266 | 535 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws', |
92593690 | 536 | 'channel_id': 'MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws', |
f4f9f6d0 | 537 | 'channel': 'patroX', |
538 | 'creators': ['patroX'], | |
0fd6661e M |
539 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', |
540 | 'upload_date': '20190930', | |
541 | 'timestamp': 1569860870, | |
542 | 'view_count': int, | |
543 | 'like_count': int, | |
544 | 'repost_count': int, | |
545 | 'comment_count': int, | |
f4f9f6d0 | 546 | 'artists': ['Evan Todd', 'Jessica Keenan Wynn', 'Alice Lee', 'Barrett Wilbert Weed', 'Jon Eidson'], |
a44ca5a4 | 547 | 'track': 'Big Fun', |
92593690 | 548 | }, |
0fd6661e | 549 | }, { |
96f13f01 M |
550 | # Banned audio, only available on the app |
551 | 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402', | |
552 | 'info_dict': { | |
553 | 'id': '6984138651336838402', | |
554 | 'ext': 'mp4', | |
555 | 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥', | |
556 | 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥', | |
557 | 'uploader': 'barudakhb_', | |
f4f9f6d0 | 558 | 'channel': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6', |
559 | 'creators': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'], | |
96f13f01 M |
560 | 'uploader_id': '6974687867511718913', |
561 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d', | |
92593690 | 562 | 'channel_id': 'MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d', |
96f13f01 | 563 | 'track': 'Boka Dance', |
f4f9f6d0 | 564 | 'artists': ['md5:29f238c49bc0c176cb3cef1a9cea9fa6'], |
96f13f01 M |
565 | 'timestamp': 1626121503, |
566 | 'duration': 18, | |
567 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
568 | 'upload_date': '20210712', | |
569 | 'view_count': int, | |
570 | 'like_count': int, | |
571 | 'repost_count': int, | |
572 | 'comment_count': int, | |
92593690 | 573 | }, |
96f13f01 M |
574 | }, { |
575 | # Sponsored video, only available with feed workaround | |
576 | 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561', | |
577 | 'info_dict': { | |
578 | 'id': '7042692929109986561', | |
579 | 'ext': 'mp4', | |
580 | 'title': 'Slap and Run!', | |
581 | 'description': 'Slap and Run!', | |
582 | 'uploader': 'user440922249', | |
f4f9f6d0 | 583 | 'channel': 'Slap And Run', |
584 | 'creators': ['Slap And Run'], | |
96f13f01 M |
585 | 'uploader_id': '7036055384943690754', |
586 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_', | |
92593690 | 587 | 'channel_id': 'MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_', |
96f13f01 M |
588 | 'track': 'Promoted Music', |
589 | 'timestamp': 1639754738, | |
590 | 'duration': 30, | |
591 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
592 | 'upload_date': '20211217', | |
593 | 'view_count': int, | |
594 | 'like_count': int, | |
595 | 'repost_count': int, | |
596 | 'comment_count': int, | |
597 | }, | |
b09bd0c1 | 598 | 'params': {'skip_download': True}, # XXX: unable to download video data: HTTP Error 403: Forbidden |
5fa3c9a8 HTL |
599 | }, { |
600 | # Video without title and description | |
601 | 'url': 'https://www.tiktok.com/@pokemonlife22/video/7059698374567611694', | |
602 | 'info_dict': { | |
603 | 'id': '7059698374567611694', | |
604 | 'ext': 'mp4', | |
b801cd71 | 605 | 'title': 'TikTok video #7059698374567611694', |
5fa3c9a8 HTL |
606 | 'description': '', |
607 | 'uploader': 'pokemonlife22', | |
f4f9f6d0 | 608 | 'channel': 'Pokemon', |
609 | 'creators': ['Pokemon'], | |
5fa3c9a8 HTL |
610 | 'uploader_id': '6820838815978423302', |
611 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W', | |
92593690 | 612 | 'channel_id': 'MS4wLjABAAAA0tF1nBwQVVMyrGu3CqttkNgM68Do1OXUFuCY0CRQk8fEtSVDj89HqoqvbSTmUP2W', |
5fa3c9a8 HTL |
613 | 'track': 'original sound', |
614 | 'timestamp': 1643714123, | |
615 | 'duration': 6, | |
616 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
617 | 'upload_date': '20220201', | |
f4f9f6d0 | 618 | 'artists': ['Pokemon'], |
5fa3c9a8 HTL |
619 | 'view_count': int, |
620 | 'like_count': int, | |
621 | 'repost_count': int, | |
622 | 'comment_count': int, | |
623 | }, | |
a39a7ba8 | 624 | }, { |
625 | # hydration JSON is sent in a <script> element | |
626 | 'url': 'https://www.tiktok.com/@denidil6/video/7065799023130643713', | |
627 | 'info_dict': { | |
628 | 'id': '7065799023130643713', | |
629 | 'ext': 'mp4', | |
630 | 'title': '#denidil#денидил', | |
631 | 'description': '#denidil#денидил', | |
632 | 'uploader': 'denidil6', | |
633 | 'uploader_id': '7046664115636405250', | |
634 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAsvMSzFdQ4ikl3uR2TEJwMBbB2yZh2Zxwhx-WCo3rbDpAharE3GQCrFuJArI3C8QJ', | |
635 | 'artist': 'Holocron Music', | |
636 | 'album': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night', | |
637 | 'track': 'Wolf Sounds (1 Hour) Enjoy the Company of the Animal That Is the Majestic King of the Night', | |
638 | 'timestamp': 1645134536, | |
639 | 'duration': 26, | |
640 | 'upload_date': '20220217', | |
641 | 'view_count': int, | |
642 | 'like_count': int, | |
643 | 'repost_count': int, | |
644 | 'comment_count': int, | |
645 | }, | |
f7c5a5e9 | 646 | 'skip': 'This video is unavailable', |
8ceb07e8 | 647 | }, { |
648 | # slideshow audio-only mp3 format | |
649 | 'url': 'https://www.tiktok.com/@_le_cannibale_/video/7139980461132074283', | |
650 | 'info_dict': { | |
651 | 'id': '7139980461132074283', | |
652 | 'ext': 'mp3', | |
653 | 'title': 'TikTok video #7139980461132074283', | |
654 | 'description': '', | |
f4f9f6d0 | 655 | 'channel': 'Antaura', |
656 | 'creators': ['Antaura'], | |
8ceb07e8 | 657 | 'uploader': '_le_cannibale_', |
658 | 'uploader_id': '6604511138619654149', | |
659 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP', | |
92593690 | 660 | 'channel_id': 'MS4wLjABAAAAoShJqaw_5gvy48y3azFeFcT4jeyKWbB0VVYasOCt2tTLwjNFIaDcHAM4D-QGXFOP', |
f4f9f6d0 | 661 | 'artists': ['nathan !'], |
8ceb07e8 | 662 | 'track': 'grahamscott canon', |
663 | 'upload_date': '20220905', | |
664 | 'timestamp': 1662406249, | |
665 | 'view_count': int, | |
666 | 'like_count': int, | |
667 | 'repost_count': int, | |
668 | 'comment_count': int, | |
f4f9f6d0 | 669 | 'thumbnail': r're:^https://.+\.(?:webp|jpe?g)', |
8ceb07e8 | 670 | }, |
92593690 | 671 | }, { |
672 | # only available via web | |
f4f9f6d0 | 673 | 'url': 'https://www.tiktok.com/@moxypatch/video/7206382937372134662', # FIXME |
b09bd0c1 | 674 | 'md5': '6aba7fad816e8709ff2c149679ace165', |
92593690 | 675 | 'info_dict': { |
676 | 'id': '7206382937372134662', | |
677 | 'ext': 'mp4', | |
678 | 'title': 'md5:1d95c0b96560ca0e8a231af4172b2c0a', | |
679 | 'description': 'md5:1d95c0b96560ca0e8a231af4172b2c0a', | |
f4f9f6d0 | 680 | 'channel': 'MoxyPatch', |
d9b4154c | 681 | 'creators': ['MoxyPatch'], |
92593690 | 682 | 'uploader': 'moxypatch', |
683 | 'uploader_id': '7039142049363379205', | |
684 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V', | |
685 | 'channel_id': 'MS4wLjABAAAAFhqKnngMHJSsifL0w1vFOP5kn3Ndo1ODp0XuIBkNMBCkALTvwILdpu12g3pTtL4V', | |
d9b4154c | 686 | 'artists': ['your worst nightmare'], |
92593690 | 687 | 'track': 'original sound', |
688 | 'upload_date': '20230303', | |
689 | 'timestamp': 1677866781, | |
690 | 'duration': 10, | |
691 | 'view_count': int, | |
692 | 'like_count': int, | |
693 | 'repost_count': int, | |
694 | 'comment_count': int, | |
695 | 'thumbnail': r're:^https://.+', | |
696 | 'thumbnails': 'count:3', | |
697 | }, | |
698 | 'expected_warnings': ['Unable to find video in feed'], | |
c2a1bdb0 | 699 | }, { |
700 | # 1080p format | |
f4f9f6d0 | 701 | 'url': 'https://www.tiktok.com/@tatemcrae/video/7107337212743830830', # FIXME |
c2a1bdb0 | 702 | 'md5': '982512017a8a917124d5a08c8ae79621', |
703 | 'info_dict': { | |
704 | 'id': '7107337212743830830', | |
705 | 'ext': 'mp4', | |
706 | 'title': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok', | |
707 | 'description': 'new music video 4 don’t come backkkk🧸🖤 i hope u enjoy !! @musicontiktok', | |
708 | 'uploader': 'tatemcrae', | |
709 | 'uploader_id': '86328792343818240', | |
710 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd', | |
711 | 'channel_id': 'MS4wLjABAAAA-0bQT0CqebTRr6I4IkYvMDMKSRSJHLNPBo5HrSklJwyA2psXLSZG5FP-LMNpHnJd', | |
f4f9f6d0 | 712 | 'channel': 'tate mcrae', |
713 | 'creators': ['tate mcrae'], | |
714 | 'artists': ['tate mcrae'], | |
c2a1bdb0 | 715 | 'track': 'original sound', |
716 | 'upload_date': '20220609', | |
717 | 'timestamp': 1654805899, | |
718 | 'duration': 150, | |
719 | 'view_count': int, | |
720 | 'like_count': int, | |
721 | 'repost_count': int, | |
722 | 'comment_count': int, | |
723 | 'thumbnail': r're:^https://.+\.webp', | |
724 | }, | |
d9b4154c | 725 | 'skip': 'Unavailable via feed API, no formats available via web', |
b09bd0c1 | 726 | }, { |
727 | # Slideshow, audio-only m4a format | |
728 | 'url': 'https://www.tiktok.com/@hara_yoimiya/video/7253412088251534594', | |
729 | 'md5': '2ff8fe0174db2dbf49c597a7bef4e47d', | |
730 | 'info_dict': { | |
731 | 'id': '7253412088251534594', | |
732 | 'ext': 'm4a', | |
733 | 'title': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ', | |
734 | 'description': 'я ред флаг простите #переписка #щитпост #тревожныйтиппривязанности #рекомендации ', | |
735 | 'uploader': 'hara_yoimiya', | |
736 | 'uploader_id': '6582536342634676230', | |
737 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB', | |
738 | 'channel_id': 'MS4wLjABAAAAIAlDxriiPWLE-p8p1R_0Bx8qWKfi-7zwmGhzU8Mv25W8sNxjfIKrol31qTczzuLB', | |
f4f9f6d0 | 739 | 'channel': 'лампочка', |
740 | 'creators': ['лампочка'], | |
741 | 'artists': ['Øneheart'], | |
b09bd0c1 | 742 | 'album': 'watching the stars', |
743 | 'track': 'watching the stars', | |
744 | 'upload_date': '20230708', | |
745 | 'timestamp': 1688816612, | |
746 | 'view_count': int, | |
747 | 'like_count': int, | |
748 | 'comment_count': int, | |
749 | 'repost_count': int, | |
f4f9f6d0 | 750 | 'thumbnail': r're:^https://.+\.(?:webp|jpe?g)', |
b09bd0c1 | 751 | }, |
e0585e65 M |
752 | }, { |
753 | # Auto-captions available | |
754 | 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758', | |
755 | 'only_matching': True | |
0fd6661e M |
756 | }] |
757 | ||
ce18a19b | 758 | def _real_extract(self, url): |
b801cd71 | 759 | video_id, user_id = self._match_valid_url(url).group('id', 'user_id') |
bd9ff55b M |
760 | try: |
761 | return self._extract_aweme_app(video_id) | |
762 | except ExtractorError as e: | |
d9b4154c | 763 | e.expected = True |
a39a7ba8 | 764 | self.report_warning(f'{e}; trying with webpage') |
bd9ff55b | 765 | |
a39a7ba8 | 766 | url = self._create_url(user_id, video_id) |
216bcb66 | 767 | webpage = self._download_webpage(url, video_id, headers={'User-Agent': 'Mozilla/5.0'}) |
d9b4154c | 768 | |
769 | if universal_data := self._get_universal_data(webpage, video_id): | |
770 | self.write_debug('Found universal data for rehydration') | |
771 | status = traverse_obj(universal_data, ('webapp.video-detail', 'statusCode', {int})) or 0 | |
772 | video_data = traverse_obj(universal_data, ('webapp.video-detail', 'itemInfo', 'itemStruct', {dict})) | |
773 | ||
774 | elif sigi_data := self._get_sigi_state(webpage, video_id): | |
775 | self.write_debug('Found sigi state data') | |
776 | status = traverse_obj(sigi_data, ('VideoPage', 'statusCode', {int})) or 0 | |
777 | video_data = traverse_obj(sigi_data, ('ItemModule', video_id, {dict})) | |
778 | ||
3ee11942 | 779 | elif next_data := self._search_nextjs_data(webpage, video_id, default={}): |
d9b4154c | 780 | self.write_debug('Found next.js data') |
781 | status = traverse_obj(next_data, ('props', 'pageProps', 'statusCode', {int})) or 0 | |
782 | video_data = traverse_obj(next_data, ('props', 'pageProps', 'itemInfo', 'itemStruct', {dict})) | |
783 | ||
11aa91a1 | 784 | else: |
d9b4154c | 785 | raise ExtractorError('Unable to extract webpage video data') |
11aa91a1 | 786 | |
d9b4154c | 787 | if video_data and status == 0: |
92593690 | 788 | return self._parse_aweme_video_web(video_data, url, video_id) |
1418a043 | 789 | elif status == 10216: |
790 | raise ExtractorError('This video is private', expected=True) | |
d9b4154c | 791 | raise ExtractorError(f'Video not available, status code {status}', video_id=video_id) |
f7f18f90 A |
792 | |
793 | ||
0fd6661e | 794 | class TikTokUserIE(TikTokBaseIE): |
f7f18f90 | 795 | IE_NAME = 'tiktok:user' |
0fd6661e | 796 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])' |
f7c5a5e9 | 797 | _WORKING = False |
f7f18f90 | 798 | _TESTS = [{ |
526d74ec | 799 | 'url': 'https://tiktok.com/@corgibobaa?lang=en', |
f7f18f90 A |
800 | 'playlist_mincount': 45, |
801 | 'info_dict': { | |
802 | 'id': '6935371178089399301', | |
0481e266 | 803 | 'title': 'corgibobaa', |
b3187433 | 804 | 'thumbnail': r're:https://.+_1080x1080\.webp' |
f7f18f90 | 805 | }, |
0481e266 | 806 | 'expected_warnings': ['Retrying'] |
5fa3c9a8 HTL |
807 | }, { |
808 | 'url': 'https://www.tiktok.com/@6820838815978423302', | |
809 | 'playlist_mincount': 5, | |
810 | 'info_dict': { | |
811 | 'id': '6820838815978423302', | |
812 | 'title': '6820838815978423302', | |
813 | 'thumbnail': r're:https://.+_1080x1080\.webp' | |
814 | }, | |
815 | 'expected_warnings': ['Retrying'] | |
f7f18f90 A |
816 | }, { |
817 | 'url': 'https://www.tiktok.com/@meme', | |
818 | 'playlist_mincount': 593, | |
819 | 'info_dict': { | |
820 | 'id': '79005827461758976', | |
0481e266 | 821 | 'title': 'meme', |
b3187433 | 822 | 'thumbnail': r're:https://.+_1080x1080\.webp' |
f7f18f90 | 823 | }, |
0481e266 | 824 | 'expected_warnings': ['Retrying'] |
f7f18f90 A |
825 | }] |
826 | ||
0fd6661e M |
827 | r''' # TODO: Fix by adding _signature to api_url |
828 | def _entries(self, webpage, user_id, username): | |
829 | secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username) | |
f7f18f90 A |
830 | verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id') |
831 | if not verifyfp_cookie: | |
832 | raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True) | |
833 | 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=' | |
834 | cursor = '0' | |
835 | for page in itertools.count(): | |
0fd6661e | 836 | data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page) |
f7f18f90 A |
837 | for video in data_json.get('itemList', []): |
838 | video_id = video['id'] | |
839 | video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}' | |
bd9ff55b | 840 | yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc'))) |
526d74ec | 841 | if not data_json.get('hasMore'): |
f7f18f90 A |
842 | break |
843 | cursor = data_json['cursor'] | |
0fd6661e M |
844 | ''' |
845 | ||
b3187433 | 846 | def _video_entries_api(self, webpage, user_id, username): |
0fd6661e M |
847 | query = { |
848 | 'user_id': user_id, | |
849 | 'count': 21, | |
850 | 'max_cursor': 0, | |
851 | 'min_cursor': 0, | |
852 | 'retry_type': 'no_retry', | |
efa944f4 | 853 | '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. |
0fd6661e M |
854 | } |
855 | ||
0fd6661e | 856 | for page in itertools.count(1): |
be5c1ae8 | 857 | for retry in self.RetryManager(): |
0fd6661e | 858 | try: |
be5c1ae8 | 859 | post_list = self._call_api( |
860 | 'aweme/post', query, username, note=f'Downloading user video list page {page}', | |
861 | errnote='Unable to download user video list') | |
0fd6661e | 862 | except ExtractorError as e: |
be5c1ae8 | 863 | if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0: |
864 | retry.error = e | |
0fd6661e M |
865 | continue |
866 | raise | |
b3187433 | 867 | yield from post_list.get('aweme_list', []) |
0fd6661e M |
868 | if not post_list.get('has_more'): |
869 | break | |
870 | query['max_cursor'] = post_list['max_cursor'] | |
f7f18f90 | 871 | |
b3187433 | 872 | def _entries_api(self, user_id, videos): |
873 | for video in videos: | |
874 | yield { | |
875 | **self._parse_aweme_video_app(video), | |
876 | 'extractor_key': TikTokIE.ie_key(), | |
877 | 'extractor': 'TikTok', | |
878 | 'webpage_url': f'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}', | |
879 | } | |
880 | ||
f7f18f90 | 881 | def _real_extract(self, url): |
0481e266 | 882 | user_name = self._match_id(url) |
883 | webpage = self._download_webpage(url, user_name, headers={ | |
0fd6661e M |
884 | 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)' |
885 | }) | |
5fa3c9a8 | 886 | user_id = self._html_search_regex(r'snssdk\d*://user/profile/(\d+)', webpage, 'user ID', default=None) or user_name |
b3187433 | 887 | |
888 | videos = LazyList(self._video_entries_api(webpage, user_id, user_name)) | |
889 | thumbnail = traverse_obj(videos, (0, 'author', 'avatar_larger', 'url_list', 0)) | |
890 | ||
891 | return self.playlist_result(self._entries_api(user_id, videos), user_id, user_name, thumbnail=thumbnail) | |
943d5ab1 M |
892 | |
893 | ||
6368e2e6 | 894 | class TikTokBaseListIE(TikTokBaseIE): # XXX: Conventionally, base classes should end with BaseIE/InfoExtractor |
8126298c M |
895 | def _entries(self, list_id, display_id): |
896 | query = { | |
897 | self._QUERY_NAME: list_id, | |
898 | 'cursor': 0, | |
899 | 'count': 20, | |
900 | 'type': 5, | |
efa944f4 | 901 | 'device_id': ''.join(random.choices(string.digits, k=19)) |
8126298c M |
902 | } |
903 | ||
8126298c | 904 | for page in itertools.count(1): |
be5c1ae8 | 905 | for retry in self.RetryManager(): |
8126298c | 906 | try: |
be5c1ae8 | 907 | post_list = self._call_api( |
908 | self._API_ENDPOINT, query, display_id, note=f'Downloading video list page {page}', | |
909 | errnote='Unable to download video list') | |
8126298c | 910 | except ExtractorError as e: |
be5c1ae8 | 911 | if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0: |
912 | retry.error = e | |
8126298c M |
913 | continue |
914 | raise | |
8126298c M |
915 | for video in post_list.get('aweme_list', []): |
916 | yield { | |
917 | **self._parse_aweme_video_app(video), | |
0b77924a | 918 | 'extractor_key': TikTokIE.ie_key(), |
8126298c M |
919 | 'extractor': 'TikTok', |
920 | 'webpage_url': f'https://tiktok.com/@_/video/{video["aweme_id"]}', | |
921 | } | |
922 | if not post_list.get('has_more'): | |
923 | break | |
924 | query['cursor'] = post_list['cursor'] | |
925 | ||
926 | def _real_extract(self, url): | |
927 | list_id = self._match_id(url) | |
928 | return self.playlist_result(self._entries(list_id, list_id), list_id) | |
929 | ||
930 | ||
931 | class TikTokSoundIE(TikTokBaseListIE): | |
932 | IE_NAME = 'tiktok:sound' | |
933 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?' | |
f7c5a5e9 | 934 | _WORKING = False |
8126298c M |
935 | _QUERY_NAME = 'music_id' |
936 | _API_ENDPOINT = 'music/aweme' | |
937 | _TESTS = [{ | |
938 | 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en', | |
939 | 'playlist_mincount': 100, | |
940 | 'info_dict': { | |
941 | 'id': '6956990112127585029' | |
942 | }, | |
943 | 'expected_warnings': ['Retrying'] | |
944 | }, { | |
945 | # Actual entries are less than listed video count | |
946 | 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381', | |
947 | 'playlist_mincount': 2182, | |
948 | 'info_dict': { | |
949 | 'id': '7036843036118469381' | |
950 | }, | |
951 | 'expected_warnings': ['Retrying'] | |
952 | }] | |
953 | ||
954 | ||
955 | class TikTokEffectIE(TikTokBaseListIE): | |
956 | IE_NAME = 'tiktok:effect' | |
957 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?' | |
f7c5a5e9 | 958 | _WORKING = False |
8126298c M |
959 | _QUERY_NAME = 'sticker_id' |
960 | _API_ENDPOINT = 'sticker/aweme' | |
961 | _TESTS = [{ | |
962 | 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156', | |
963 | 'playlist_mincount': 100, | |
964 | 'info_dict': { | |
965 | 'id': '1258156', | |
966 | }, | |
967 | 'expected_warnings': ['Retrying'] | |
968 | }, { | |
969 | # Different entries between mobile and web, depending on region | |
970 | 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565', | |
971 | 'only_matching': True | |
972 | }] | |
973 | ||
974 | ||
975 | class TikTokTagIE(TikTokBaseListIE): | |
976 | IE_NAME = 'tiktok:tag' | |
977 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)' | |
f7c5a5e9 | 978 | _WORKING = False |
8126298c M |
979 | _QUERY_NAME = 'ch_id' |
980 | _API_ENDPOINT = 'challenge/aweme' | |
981 | _TESTS = [{ | |
982 | 'url': 'https://tiktok.com/tag/hello2018', | |
983 | 'playlist_mincount': 39, | |
984 | 'info_dict': { | |
985 | 'id': '46294678', | |
986 | 'title': 'hello2018', | |
987 | }, | |
988 | 'expected_warnings': ['Retrying'] | |
989 | }, { | |
990 | 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1', | |
991 | 'only_matching': True | |
992 | }] | |
993 | ||
994 | def _real_extract(self, url): | |
995 | display_id = self._match_id(url) | |
996 | webpage = self._download_webpage(url, display_id, headers={ | |
997 | 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)' | |
998 | }) | |
999 | tag_id = self._html_search_regex(r'snssdk\d*://challenge/detail/(\d+)', webpage, 'tag ID') | |
1000 | return self.playlist_result(self._entries(tag_id, display_id), tag_id, display_id) | |
1001 | ||
1002 | ||
ba723997 | 1003 | class DouyinIE(TikTokBaseIE): |
943d5ab1 M |
1004 | _VALID_URL = r'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)' |
1005 | _TESTS = [{ | |
1006 | 'url': 'https://www.douyin.com/video/6961737553342991651', | |
9ff94664 | 1007 | 'md5': '9ecce7bc5b302601018ecb2871c63a75', |
943d5ab1 M |
1008 | 'info_dict': { |
1009 | 'id': '6961737553342991651', | |
1010 | 'ext': 'mp4', | |
1011 | 'title': '#杨超越 小小水手带你去远航❤️', | |
ba723997 | 1012 | 'description': '#杨超越 小小水手带你去远航❤️', |
9ff94664 | 1013 | 'uploader': '6897520xka', |
943d5ab1 | 1014 | 'uploader_id': '110403406559', |
ba723997 | 1015 | 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98', |
92593690 | 1016 | 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98', |
f4f9f6d0 | 1017 | 'channel': '杨超越', |
9ff94664 | 1018 | 'creators': ['杨超越'], |
1019 | 'duration': 19, | |
ba723997 | 1020 | 'timestamp': 1620905839, |
1021 | 'upload_date': '20210513', | |
1022 | 'track': '@杨超越创作的原声', | |
9ff94664 | 1023 | 'artists': ['杨超越'], |
943d5ab1 M |
1024 | 'view_count': int, |
1025 | 'like_count': int, | |
1026 | 'repost_count': int, | |
1027 | 'comment_count': int, | |
92593690 | 1028 | 'thumbnail': r're:https?://.+\.jpe?g', |
ba723997 | 1029 | }, |
943d5ab1 M |
1030 | }, { |
1031 | 'url': 'https://www.douyin.com/video/6982497745948921092', | |
9ff94664 | 1032 | 'md5': '15c5e660b7048af3707304e3cc02bbb5', |
943d5ab1 M |
1033 | 'info_dict': { |
1034 | 'id': '6982497745948921092', | |
1035 | 'ext': 'mp4', | |
1036 | 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想', | |
ba723997 | 1037 | 'description': '这个夏日和小羊@杨超越 一起遇见白色幻想', |
9ff94664 | 1038 | 'uploader': '0731chaoyue', |
943d5ab1 | 1039 | 'uploader_id': '408654318141572', |
ba723997 | 1040 | 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA', |
92593690 | 1041 | 'channel_id': 'MS4wLjABAAAAZJpnglcjW2f_CMVcnqA_6oVBXKWMpH0F8LIHuUu8-lA', |
f4f9f6d0 | 1042 | 'channel': '杨超越工作室', |
9ff94664 | 1043 | 'creators': ['杨超越工作室'], |
1044 | 'duration': 42, | |
ba723997 | 1045 | 'timestamp': 1625739481, |
1046 | 'upload_date': '20210708', | |
1047 | 'track': '@杨超越工作室创作的原声', | |
9ff94664 | 1048 | 'artists': ['杨超越工作室'], |
943d5ab1 M |
1049 | 'view_count': int, |
1050 | 'like_count': int, | |
1051 | 'repost_count': int, | |
1052 | 'comment_count': int, | |
92593690 | 1053 | 'thumbnail': r're:https?://.+\.jpe?g', |
ba723997 | 1054 | }, |
943d5ab1 M |
1055 | }, { |
1056 | 'url': 'https://www.douyin.com/video/6953975910773099811', | |
9ff94664 | 1057 | 'md5': '0e6443758b8355db9a3c34864a4276be', |
943d5ab1 M |
1058 | 'info_dict': { |
1059 | 'id': '6953975910773099811', | |
1060 | 'ext': 'mp4', | |
1061 | 'title': '#一起看海 出现在你的夏日里', | |
ba723997 | 1062 | 'description': '#一起看海 出现在你的夏日里', |
9ff94664 | 1063 | 'uploader': '6897520xka', |
943d5ab1 | 1064 | 'uploader_id': '110403406559', |
ba723997 | 1065 | 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98', |
92593690 | 1066 | 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98', |
f4f9f6d0 | 1067 | 'channel': '杨超越', |
9ff94664 | 1068 | 'creators': ['杨超越'], |
1069 | 'duration': 17, | |
ba723997 | 1070 | 'timestamp': 1619098692, |
1071 | 'upload_date': '20210422', | |
1072 | 'track': '@杨超越创作的原声', | |
9ff94664 | 1073 | 'artists': ['杨超越'], |
943d5ab1 M |
1074 | 'view_count': int, |
1075 | 'like_count': int, | |
1076 | 'repost_count': int, | |
1077 | 'comment_count': int, | |
92593690 | 1078 | 'thumbnail': r're:https?://.+\.jpe?g', |
ba723997 | 1079 | }, |
943d5ab1 M |
1080 | }, { |
1081 | 'url': 'https://www.douyin.com/video/6950251282489675042', | |
1082 | 'md5': 'b4db86aec367ef810ddd38b1737d2fed', | |
1083 | 'info_dict': { | |
1084 | 'id': '6950251282489675042', | |
1085 | 'ext': 'mp4', | |
1086 | 'title': '哈哈哈,成功了哈哈哈哈哈哈', | |
1087 | 'uploader': '杨超越', | |
1088 | 'upload_date': '20210412', | |
1089 | 'timestamp': 1618231483, | |
1090 | 'uploader_id': '110403406559', | |
1091 | 'view_count': int, | |
1092 | 'like_count': int, | |
1093 | 'repost_count': int, | |
1094 | 'comment_count': int, | |
ba723997 | 1095 | }, |
1096 | 'skip': 'No longer available', | |
943d5ab1 M |
1097 | }, { |
1098 | 'url': 'https://www.douyin.com/video/6963263655114722595', | |
9ff94664 | 1099 | 'md5': '1440bcf59d8700f8e014da073a4dfea8', |
943d5ab1 M |
1100 | 'info_dict': { |
1101 | 'id': '6963263655114722595', | |
1102 | 'ext': 'mp4', | |
1103 | 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈', | |
ba723997 | 1104 | 'description': '#哪个爱豆的105度最甜 换个角度看看我哈哈', |
9ff94664 | 1105 | 'uploader': '6897520xka', |
943d5ab1 | 1106 | 'uploader_id': '110403406559', |
ba723997 | 1107 | 'uploader_url': 'https://www.douyin.com/user/MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98', |
92593690 | 1108 | 'channel_id': 'MS4wLjABAAAAEKnfa654JAJ_N5lgZDQluwsxmY0lhfmEYNQBBkwGG98', |
f4f9f6d0 | 1109 | 'channel': '杨超越', |
9ff94664 | 1110 | 'creators': ['杨超越'], |
1111 | 'duration': 15, | |
ba723997 | 1112 | 'timestamp': 1621261163, |
1113 | 'upload_date': '20210517', | |
1114 | 'track': '@杨超越创作的原声', | |
9ff94664 | 1115 | 'artists': ['杨超越'], |
943d5ab1 M |
1116 | 'view_count': int, |
1117 | 'like_count': int, | |
1118 | 'repost_count': int, | |
1119 | 'comment_count': int, | |
92593690 | 1120 | 'thumbnail': r're:https?://.+\.jpe?g', |
ba723997 | 1121 | }, |
943d5ab1 | 1122 | }] |
943d5ab1 | 1123 | _UPLOADER_URL_FORMAT = 'https://www.douyin.com/user/%s' |
53dad39e | 1124 | _WEBPAGE_HOST = 'https://www.douyin.com/' |
943d5ab1 M |
1125 | |
1126 | def _real_extract(self, url): | |
1127 | video_id = self._match_id(url) | |
1128 | ||
9ff94664 | 1129 | detail = traverse_obj(self._download_json( |
1130 | 'https://www.douyin.com/aweme/v1/web/aweme/detail/', video_id, | |
1131 | 'Downloading web detail JSON', 'Failed to download web detail JSON', | |
1132 | query={'aweme_id': video_id}, fatal=False), ('aweme_detail', {dict})) | |
1133 | if not detail: | |
943d5ab1 | 1134 | # TODO: Run verification challenge code to generate signature cookies |
ba723997 | 1135 | raise ExtractorError( |
9ff94664 | 1136 | 'Fresh cookies (not necessarily logged in) are needed', |
1137 | expected=not self._get_cookies(self._WEBPAGE_HOST).get('s_v_web_id')) | |
943d5ab1 | 1138 | |
9ff94664 | 1139 | return self._parse_aweme_video_app(detail) |
88afe056 | 1140 | |
1141 | ||
49895f06 | 1142 | class TikTokVMIE(InfoExtractor): |
ba723997 | 1143 | _VALID_URL = r'https?://(?:(?:vm|vt)\.tiktok\.com|(?:www\.)tiktok\.com/t)/(?P<id>\w+)' |
88afe056 | 1144 | IE_NAME = 'vm.tiktok' |
1145 | ||
49895f06 | 1146 | _TESTS = [{ |
ba723997 | 1147 | 'url': 'https://www.tiktok.com/t/ZTRC5xgJp', |
49895f06 | 1148 | 'info_dict': { |
ba723997 | 1149 | 'id': '7170520270497680683', |
49895f06 | 1150 | 'ext': 'mp4', |
ba723997 | 1151 | 'title': 'md5:c64f6152330c2efe98093ccc8597871c', |
1152 | 'uploader_id': '6687535061741700102', | |
1153 | 'upload_date': '20221127', | |
49895f06 | 1154 | 'view_count': int, |
ba723997 | 1155 | 'like_count': int, |
49895f06 | 1156 | 'comment_count': int, |
ba723997 | 1157 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAObqu3WCTXxmw2xwZ3iLEHnEecEIw7ks6rxWqOqOhaPja9BI7gqUQnjw8_5FSoDXX', |
1158 | 'album': 'Wave of Mutilation: Best of Pixies', | |
1159 | 'thumbnail': r're:https://.+\.webp.*', | |
1160 | 'duration': 5, | |
1161 | 'timestamp': 1669516858, | |
49895f06 | 1162 | 'repost_count': int, |
ba723997 | 1163 | 'artist': 'Pixies', |
1164 | 'track': 'Where Is My Mind?', | |
1165 | 'description': 'md5:c64f6152330c2efe98093ccc8597871c', | |
1166 | 'uploader': 'sigmachaddeus', | |
1167 | 'creator': 'SigmaChad', | |
1168 | }, | |
1169 | }, { | |
c4cbd3be | 1170 | 'url': 'https://vm.tiktok.com/ZTR45GpSF/', |
1171 | 'info_dict': { | |
1172 | 'id': '7106798200794926362', | |
1173 | 'ext': 'mp4', | |
1174 | 'title': 'md5:edc3e7ea587847f8537468f2fe51d074', | |
1175 | 'uploader_id': '6997695878846268418', | |
1176 | 'upload_date': '20220608', | |
1177 | 'view_count': int, | |
1178 | 'like_count': int, | |
1179 | 'comment_count': int, | |
1180 | 'thumbnail': r're:https://.+\.webp.*', | |
1181 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAdZ_NcPPgMneaGrW0hN8O_J_bwLshwNNERRF5DxOw2HKIzk0kdlLrR8RkVl1ksrMO', | |
1182 | 'duration': 29, | |
1183 | 'timestamp': 1654680400, | |
1184 | 'repost_count': int, | |
1185 | 'artist': 'Akihitoko', | |
1186 | 'track': 'original sound', | |
1187 | 'description': 'md5:edc3e7ea587847f8537468f2fe51d074', | |
1188 | 'uploader': 'akihitoko1', | |
1189 | 'creator': 'Akihitoko', | |
1190 | }, | |
49895f06 | 1191 | }, { |
1192 | 'url': 'https://vt.tiktok.com/ZSe4FqkKd', | |
1193 | 'only_matching': True, | |
1194 | }] | |
1195 | ||
88afe056 | 1196 | def _real_extract(self, url): |
11e1c2e3 | 1197 | new_url = self._request_webpage( |
3d2623a8 | 1198 | HEADRequest(url), self._match_id(url), headers={'User-Agent': 'facebookexternalhit/1.1'}).url |
11e1c2e3 | 1199 | if self.suitable(new_url): # Prevent infinite loop in case redirect fails |
1200 | raise UnsupportedError(new_url) | |
1201 | return self.url_result(new_url) | |
933ed882 JC |
1202 | |
1203 | ||
216bcb66 | 1204 | class TikTokLiveIE(TikTokBaseIE): |
1205 | _VALID_URL = r'''(?x)https?://(?: | |
1206 | (?:www\.)?tiktok\.com/@(?P<uploader>[\w.-]+)/live| | |
1207 | m\.tiktok\.com/share/live/(?P<id>\d+) | |
1208 | )''' | |
933ed882 JC |
1209 | IE_NAME = 'tiktok:live' |
1210 | ||
1211 | _TESTS = [{ | |
216bcb66 | 1212 | 'url': 'https://www.tiktok.com/@weathernewslive/live', |
1213 | 'info_dict': { | |
1214 | 'id': '7210809319192726273', | |
1215 | 'ext': 'mp4', | |
1216 | 'title': r're:ウェザーニュースLiVE[\d\s:-]*', | |
1217 | 'creator': 'ウェザーニュースLiVE', | |
1218 | 'uploader': 'weathernewslive', | |
1219 | 'uploader_id': '6621496731283095554', | |
1220 | 'uploader_url': 'https://www.tiktok.com/@weathernewslive', | |
1221 | 'live_status': 'is_live', | |
1222 | 'concurrent_view_count': int, | |
1223 | }, | |
1224 | 'params': {'skip_download': 'm3u8'}, | |
1225 | }, { | |
1226 | 'url': 'https://www.tiktok.com/@pilarmagenta/live', | |
1227 | 'info_dict': { | |
1228 | 'id': '7209423610325322522', | |
1229 | 'ext': 'mp4', | |
1230 | 'title': str, | |
1231 | 'creator': 'Pilarmagenta', | |
1232 | 'uploader': 'pilarmagenta', | |
1233 | 'uploader_id': '6624846890674683909', | |
1234 | 'uploader_url': 'https://www.tiktok.com/@pilarmagenta', | |
1235 | 'live_status': 'is_live', | |
1236 | 'concurrent_view_count': int, | |
1237 | }, | |
1238 | 'skip': 'Livestream', | |
1239 | }, { | |
1240 | 'url': 'https://m.tiktok.com/share/live/7209423610325322522/?language=en', | |
1241 | 'only_matching': True, | |
1242 | }, { | |
933ed882 JC |
1243 | 'url': 'https://www.tiktok.com/@iris04201/live', |
1244 | 'only_matching': True, | |
1245 | }] | |
1246 | ||
216bcb66 | 1247 | def _call_api(self, url, param, room_id, uploader, key=None): |
1248 | response = traverse_obj(self._download_json( | |
1249 | url, room_id, fatal=False, query={ | |
1250 | 'aid': '1988', | |
1251 | param: room_id, | |
1252 | }), (key, {dict}), default={}) | |
1253 | ||
1254 | # status == 2 if live else 4 | |
1255 | if int_or_none(response.get('status')) == 2: | |
1256 | return response | |
1257 | # If room_id is obtained via mobile share URL and cannot be refreshed, do not wait for live | |
1258 | elif not uploader: | |
1259 | raise ExtractorError('This livestream has ended', expected=True) | |
1260 | raise UserNotLive(video_id=uploader) | |
1261 | ||
933ed882 | 1262 | def _real_extract(self, url): |
216bcb66 | 1263 | uploader, room_id = self._match_valid_url(url).group('uploader', 'id') |
1264 | webpage = self._download_webpage( | |
1265 | url, uploader or room_id, headers={'User-Agent': 'Mozilla/5.0'}, fatal=not room_id) | |
1266 | ||
1267 | if webpage: | |
d9b4154c | 1268 | data = self._get_sigi_state(webpage, uploader or room_id) |
216bcb66 | 1269 | room_id = (traverse_obj(data, ('UserModule', 'users', ..., 'roomId', {str_or_none}), get_all=False) |
1270 | or self._search_regex(r'snssdk\d*://live\?room_id=(\d+)', webpage, 'room ID', default=None) | |
1271 | or room_id) | |
1272 | uploader = uploader or traverse_obj( | |
1273 | data, ('LiveRoom', 'liveRoomUserInfo', 'user', 'uniqueId'), | |
1274 | ('UserModule', 'users', ..., 'uniqueId'), get_all=False, expected_type=str) | |
1275 | ||
933ed882 JC |
1276 | if not room_id: |
1277 | raise UserNotLive(video_id=uploader) | |
933ed882 | 1278 | |
216bcb66 | 1279 | formats = [] |
1280 | live_info = self._call_api( | |
1281 | 'https://webcast.tiktok.com/webcast/room/info', 'room_id', room_id, uploader, key='data') | |
1282 | ||
1283 | get_quality = qualities(('SD1', 'ld', 'SD2', 'sd', 'HD1', 'hd', 'FULL_HD1', 'uhd', 'ORIGION', 'origin')) | |
1284 | parse_inner = lambda x: self._parse_json(x, None) | |
1285 | ||
1286 | for quality, stream in traverse_obj(live_info, ( | |
1287 | 'stream_url', 'live_core_sdk_data', 'pull_data', 'stream_data', | |
1288 | {parse_inner}, 'data', {dict}), default={}).items(): | |
1289 | ||
1290 | sdk_params = traverse_obj(stream, ('main', 'sdk_params', {parse_inner}, { | |
1291 | 'vcodec': ('VCodec', {str}), | |
1292 | 'tbr': ('vbitrate', {lambda x: int_or_none(x, 1000)}), | |
1293 | 'resolution': ('resolution', {lambda x: re.match(r'(?i)\d+x\d+|\d+p', x).group().lower()}), | |
1294 | })) | |
1295 | ||
1296 | flv_url = traverse_obj(stream, ('main', 'flv', {url_or_none})) | |
1297 | if flv_url: | |
1298 | formats.append({ | |
1299 | 'url': flv_url, | |
1300 | 'ext': 'flv', | |
1301 | 'format_id': f'flv-{quality}', | |
1302 | 'quality': get_quality(quality), | |
1303 | **sdk_params, | |
1304 | }) | |
1305 | ||
1306 | hls_url = traverse_obj(stream, ('main', 'hls', {url_or_none})) | |
1307 | if hls_url: | |
1308 | formats.append({ | |
1309 | 'url': hls_url, | |
1310 | 'ext': 'mp4', | |
1311 | 'protocol': 'm3u8_native', | |
1312 | 'format_id': f'hls-{quality}', | |
1313 | 'quality': get_quality(quality), | |
1314 | **sdk_params, | |
1315 | }) | |
1316 | ||
1317 | def get_vcodec(*keys): | |
1318 | return traverse_obj(live_info, ( | |
1319 | 'stream_url', *keys, {parse_inner}, 'VCodec', {str})) | |
1320 | ||
1321 | for stream in ('hls', 'rtmp'): | |
1322 | stream_url = traverse_obj(live_info, ('stream_url', f'{stream}_pull_url', {url_or_none})) | |
1323 | if stream_url: | |
1324 | formats.append({ | |
1325 | 'url': stream_url, | |
1326 | 'ext': 'mp4' if stream == 'hls' else 'flv', | |
1327 | 'protocol': 'm3u8_native' if stream == 'hls' else 'https', | |
1328 | 'format_id': f'{stream}-pull', | |
1329 | 'vcodec': get_vcodec(f'{stream}_pull_url_params'), | |
1330 | 'quality': get_quality('ORIGION'), | |
1331 | }) | |
1332 | ||
1333 | for f_id, f_url in traverse_obj(live_info, ('stream_url', 'flv_pull_url', {dict}), default={}).items(): | |
1334 | if not url_or_none(f_url): | |
1335 | continue | |
1336 | formats.append({ | |
1337 | 'url': f_url, | |
1338 | 'ext': 'flv', | |
1339 | 'format_id': f'flv-{f_id}'.lower(), | |
1340 | 'vcodec': get_vcodec('flv_pull_url_params', f_id), | |
1341 | 'quality': get_quality(f_id), | |
1342 | }) | |
1343 | ||
1344 | # If uploader is a guest on another's livestream, primary endpoint will not have m3u8 URLs | |
1345 | if not traverse_obj(formats, lambda _, v: v['ext'] == 'mp4'): | |
1346 | live_info = merge_dicts(live_info, self._call_api( | |
1347 | 'https://www.tiktok.com/api/live/detail/', 'roomID', room_id, uploader, key='LiveRoomInfo')) | |
1348 | if url_or_none(live_info.get('liveUrl')): | |
1349 | formats.append({ | |
1350 | 'url': live_info['liveUrl'], | |
1351 | 'ext': 'mp4', | |
1352 | 'protocol': 'm3u8_native', | |
1353 | 'format_id': 'hls-fallback', | |
1354 | 'vcodec': 'h264', | |
1355 | 'quality': get_quality('origin'), | |
1356 | }) | |
1357 | ||
1358 | uploader = uploader or traverse_obj(live_info, ('ownerInfo', 'uniqueId'), ('owner', 'display_id')) | |
933ed882 JC |
1359 | |
1360 | return { | |
1361 | 'id': room_id, | |
933ed882 | 1362 | 'uploader': uploader, |
216bcb66 | 1363 | 'uploader_url': format_field(uploader, None, self._UPLOADER_URL_FORMAT) or None, |
933ed882 | 1364 | 'is_live': True, |
216bcb66 | 1365 | 'formats': formats, |
1366 | '_format_sort_fields': ('quality', 'ext'), | |
1367 | **traverse_obj(live_info, { | |
1368 | 'title': 'title', | |
1369 | 'uploader_id': (('ownerInfo', 'owner'), 'id', {str_or_none}), | |
1370 | 'creator': (('ownerInfo', 'owner'), 'nickname'), | |
1371 | 'concurrent_view_count': (('user_count', ('liveRoomStats', 'userCount')), {int_or_none}), | |
1372 | }, get_all=False), | |
933ed882 | 1373 | } |