]>
Commit | Line | Data |
---|---|---|
1ead840d KS |
1 | # coding: utf-8 |
2 | from __future__ import unicode_literals | |
f7f18f90 A |
3 | |
4 | import itertools | |
bd9ff55b M |
5 | import random |
6 | import string | |
7 | import time | |
0fd6661e | 8 | import json |
1ead840d KS |
9 | |
10 | from .common import InfoExtractor | |
be1f331f M |
11 | from ..compat import ( |
12 | compat_urllib_parse_unquote, | |
13 | compat_urllib_parse_urlparse | |
14 | ) | |
1ead840d | 15 | from ..utils import ( |
ce18a19b | 16 | ExtractorError, |
1ead840d | 17 | int_or_none, |
34921b43 | 18 | join_nonempty, |
b3187433 | 19 | LazyList, |
e0585e65 | 20 | srt_subtitles_timecode, |
1ead840d | 21 | str_or_none, |
bd9ff55b M |
22 | traverse_obj, |
23 | try_get, | |
943d5ab1 | 24 | url_or_none, |
bd9ff55b | 25 | qualities, |
1ead840d KS |
26 | ) |
27 | ||
28 | ||
0fd6661e | 29 | class TikTokBaseIE(InfoExtractor): |
96f13f01 | 30 | _APP_VERSION = '20.1.0' |
be1f331f | 31 | _MANIFEST_APP_VERSION = '210' |
943d5ab1 M |
32 | _APP_NAME = 'trill' |
33 | _AID = 1180 | |
53dad39e | 34 | _API_HOSTNAME = 'api-h2.tiktokv.com' |
943d5ab1 | 35 | _UPLOADER_URL_FORMAT = 'https://www.tiktok.com/@%s' |
53dad39e | 36 | _WEBPAGE_HOST = 'https://www.tiktok.com/' |
be1f331f | 37 | QUALITIES = ('360p', '540p', '720p', '1080p') |
ce18a19b | 38 | |
0fd6661e M |
39 | def _call_api(self, ep, query, video_id, fatal=True, |
40 | note='Downloading API JSON', errnote='Unable to download API page'): | |
41 | real_query = { | |
42 | **query, | |
bd9ff55b M |
43 | 'version_name': self._APP_VERSION, |
44 | 'version_code': self._MANIFEST_APP_VERSION, | |
45 | 'build_number': self._APP_VERSION, | |
46 | 'manifest_version_code': self._MANIFEST_APP_VERSION, | |
47 | 'update_version_code': self._MANIFEST_APP_VERSION, | |
0930b11f | 48 | 'openudid': ''.join(random.choice('0123456789abcdef') for _ in range(16)), |
49 | 'uuid': ''.join([random.choice(string.digits) for _ in range(16)]), | |
bd9ff55b M |
50 | '_rticket': int(time.time() * 1000), |
51 | 'ts': int(time.time()), | |
52 | 'device_brand': 'Google', | |
53 | 'device_type': 'Pixel 4', | |
54 | 'device_platform': 'android', | |
55 | 'resolution': '1080*1920', | |
56 | 'dpi': 420, | |
57 | 'os_version': '10', | |
58 | 'os_api': '29', | |
59 | 'carrier_region': 'US', | |
60 | 'sys_region': 'US', | |
61 | 'region': 'US', | |
943d5ab1 | 62 | 'app_name': self._APP_NAME, |
bd9ff55b M |
63 | 'app_language': 'en', |
64 | 'language': 'en', | |
65 | 'timezone_name': 'America/New_York', | |
66 | 'timezone_offset': '-14400', | |
67 | 'channel': 'googleplay', | |
68 | 'ac': 'wifi', | |
69 | 'mcc_mnc': '310260', | |
70 | 'is_my_cn': 0, | |
943d5ab1 | 71 | 'aid': self._AID, |
bd9ff55b M |
72 | 'ssmix': 'a', |
73 | 'as': 'a1qwert123', | |
74 | 'cp': 'cbfhckdckkde1', | |
75 | } | |
0930b11f | 76 | self._set_cookie(self._API_HOSTNAME, 'odin_tt', ''.join(random.choice('0123456789abcdef') for _ in range(160))) |
53dad39e M |
77 | webpage_cookies = self._get_cookies(self._WEBPAGE_HOST) |
78 | if webpage_cookies.get('sid_tt'): | |
79 | self._set_cookie(self._API_HOSTNAME, 'sid_tt', webpage_cookies['sid_tt'].value) | |
0fd6661e | 80 | return self._download_json( |
943d5ab1 | 81 | 'https://%s/aweme/v1/%s/' % (self._API_HOSTNAME, ep), video_id=video_id, |
0fd6661e | 82 | fatal=fatal, note=note, errnote=errnote, headers={ |
bd9ff55b | 83 | 'User-Agent': f'com.ss.android.ugc.trill/{self._MANIFEST_APP_VERSION} (Linux; U; Android 10; en_US; Pixel 4; Build/QQ3A.200805.001; Cronet/58.0.2991.0)', |
0fd6661e M |
84 | 'Accept': 'application/json', |
85 | }, query=real_query) | |
86 | ||
e0585e65 M |
87 | def _get_subtitles(self, aweme_detail, aweme_id): |
88 | # TODO: Extract text positioning info | |
89 | subtitles = {} | |
90 | captions_info = traverse_obj( | |
91 | aweme_detail, ('interaction_stickers', ..., 'auto_video_caption_info', 'auto_captions', ...), expected_type=dict, default=[]) | |
92 | for caption in captions_info: | |
93 | caption_url = traverse_obj(caption, ('url', 'url_list', ...), expected_type=url_or_none, get_all=False) | |
94 | if not caption_url: | |
95 | continue | |
96 | caption_json = self._download_json( | |
97 | caption_url, aweme_id, note='Downloading captions', errnote='Unable to download captions', fatal=False) | |
98 | if not caption_json: | |
99 | continue | |
100 | subtitles.setdefault(caption.get('language', 'en'), []).append({ | |
101 | 'ext': 'srt', | |
102 | 'data': '\n\n'.join( | |
103 | f'{i + 1}\n{srt_subtitles_timecode(line["start_time"] / 1000)} --> {srt_subtitles_timecode(line["end_time"] / 1000)}\n{line["text"]}' | |
104 | for i, line in enumerate(caption_json['utterances']) if line.get('text')) | |
105 | }) | |
106 | return subtitles | |
107 | ||
943d5ab1 | 108 | def _parse_aweme_video_app(self, aweme_detail): |
0fd6661e | 109 | aweme_id = aweme_detail['aweme_id'] |
bd9ff55b M |
110 | video_info = aweme_detail['video'] |
111 | ||
112 | def parse_url_key(url_key): | |
113 | format_id, codec, res, bitrate = self._search_regex( | |
114 | r'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key, | |
115 | 'url key', default=(None, None, None, None), group=('id', 'codec', 'res', 'bitrate')) | |
116 | if not format_id: | |
117 | return {}, None | |
118 | return { | |
119 | 'format_id': format_id, | |
120 | 'vcodec': 'h265' if codec == 'bytevc1' else codec, | |
121 | 'tbr': int_or_none(bitrate, scale=1000) or None, | |
122 | 'quality': qualities(self.QUALITIES)(res), | |
123 | }, res | |
124 | ||
125 | known_resolutions = {} | |
126 | ||
127 | def extract_addr(addr, add_meta={}): | |
128 | parsed_meta, res = parse_url_key(addr.get('url_key', '')) | |
129 | if res: | |
130 | known_resolutions.setdefault(res, {}).setdefault('height', add_meta.get('height')) | |
131 | known_resolutions[res].setdefault('width', add_meta.get('width')) | |
132 | parsed_meta.update(known_resolutions.get(res, {})) | |
133 | add_meta.setdefault('height', int_or_none(res[:-1])) | |
134 | return [{ | |
135 | 'url': url, | |
136 | 'filesize': int_or_none(addr.get('data_size')), | |
137 | 'ext': 'mp4', | |
138 | 'acodec': 'aac', | |
0fd6661e M |
139 | 'source_preference': -2 if 'aweme/v1' in url else -1, # Downloads from API might get blocked |
140 | **add_meta, **parsed_meta, | |
34921b43 | 141 | 'format_note': join_nonempty( |
142 | add_meta.get('format_note'), '(API)' if 'aweme/v1' in url else None, delim=' ') | |
bd9ff55b M |
143 | } for url in addr.get('url_list') or []] |
144 | ||
145 | # Hack: Add direct video links first to prioritize them when removing duplicate formats | |
146 | formats = [] | |
147 | if video_info.get('play_addr'): | |
148 | formats.extend(extract_addr(video_info['play_addr'], { | |
149 | 'format_id': 'play_addr', | |
150 | 'format_note': 'Direct video', | |
151 | 'vcodec': 'h265' if traverse_obj( | |
be1f331f | 152 | video_info, 'is_bytevc1', 'is_h265') else 'h264', # TODO: Check for "direct iOS" videos, like https://www.tiktok.com/@cookierun_dev/video/7039716639834656002 |
bd9ff55b M |
153 | 'width': video_info.get('width'), |
154 | 'height': video_info.get('height'), | |
155 | })) | |
156 | if video_info.get('download_addr'): | |
157 | formats.extend(extract_addr(video_info['download_addr'], { | |
158 | 'format_id': 'download_addr', | |
159 | 'format_note': 'Download video%s' % (', watermarked' if video_info.get('has_watermark') else ''), | |
160 | 'vcodec': 'h264', | |
161 | 'width': video_info.get('width'), | |
162 | 'height': video_info.get('height'), | |
0fd6661e | 163 | 'preference': -2 if video_info.get('has_watermark') else -1, |
bd9ff55b M |
164 | })) |
165 | if video_info.get('play_addr_h264'): | |
166 | formats.extend(extract_addr(video_info['play_addr_h264'], { | |
167 | 'format_id': 'play_addr_h264', | |
168 | 'format_note': 'Direct video', | |
169 | 'vcodec': 'h264', | |
170 | })) | |
171 | if video_info.get('play_addr_bytevc1'): | |
172 | formats.extend(extract_addr(video_info['play_addr_bytevc1'], { | |
173 | 'format_id': 'play_addr_bytevc1', | |
174 | 'format_note': 'Direct video', | |
175 | 'vcodec': 'h265', | |
176 | })) | |
177 | ||
178 | for bitrate in video_info.get('bit_rate', []): | |
179 | if bitrate.get('play_addr'): | |
180 | formats.extend(extract_addr(bitrate['play_addr'], { | |
181 | 'format_id': bitrate.get('gear_name'), | |
182 | 'format_note': 'Playback video', | |
183 | 'tbr': try_get(bitrate, lambda x: x['bit_rate'] / 1000), | |
184 | 'vcodec': 'h265' if traverse_obj( | |
185 | bitrate, 'is_bytevc1', 'is_h265') else 'h264', | |
943d5ab1 | 186 | 'fps': bitrate.get('FPS'), |
bd9ff55b M |
187 | })) |
188 | ||
189 | self._remove_duplicate_formats(formats) | |
6134fbeb M |
190 | auth_cookie = self._get_cookies(self._WEBPAGE_HOST).get('sid_tt') |
191 | if auth_cookie: | |
192 | for f in formats: | |
be1f331f | 193 | self._set_cookie(compat_urllib_parse_urlparse(f['url']).hostname, 'sid_tt', auth_cookie.value) |
0fd6661e | 194 | self._sort_formats(formats, ('quality', 'codec', 'size', 'br')) |
bd9ff55b M |
195 | |
196 | thumbnails = [] | |
197 | for cover_id in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak', | |
198 | 'origin_cover', 'dynamic_cover'): | |
199 | cover = video_info.get(cover_id) | |
200 | if cover: | |
201 | for cover_url in cover['url_list']: | |
202 | thumbnails.append({ | |
203 | 'id': cover_id, | |
204 | 'url': cover_url, | |
205 | }) | |
206 | ||
207 | stats_info = aweme_detail.get('statistics', {}) | |
208 | author_info = aweme_detail.get('author', {}) | |
209 | music_info = aweme_detail.get('music', {}) | |
943d5ab1 M |
210 | user_url = self._UPLOADER_URL_FORMAT % (traverse_obj(author_info, |
211 | 'sec_uid', 'id', 'uid', 'unique_id', | |
212 | expected_type=str_or_none, get_all=False)) | |
a8549f19 | 213 | labels = traverse_obj(aweme_detail, ('hybrid_label', ..., 'text'), expected_type=str, default=[]) |
bd9ff55b M |
214 | |
215 | contained_music_track = traverse_obj( | |
216 | music_info, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type=str) | |
217 | contained_music_author = traverse_obj( | |
218 | music_info, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type=str) | |
219 | ||
220 | is_generic_og_trackname = music_info.get('is_original_sound') and music_info.get('title') == 'original sound - %s' % music_info.get('owner_handle') | |
221 | if is_generic_og_trackname: | |
222 | music_track, music_author = contained_music_track or 'original sound', contained_music_author | |
223 | else: | |
224 | music_track, music_author = music_info.get('title'), music_info.get('author') | |
225 | ||
226 | return { | |
227 | 'id': aweme_id, | |
228 | 'title': aweme_detail['desc'], | |
229 | 'description': aweme_detail['desc'], | |
230 | 'view_count': int_or_none(stats_info.get('play_count')), | |
231 | 'like_count': int_or_none(stats_info.get('digg_count')), | |
232 | 'repost_count': int_or_none(stats_info.get('share_count')), | |
233 | 'comment_count': int_or_none(stats_info.get('comment_count')), | |
234 | 'uploader': str_or_none(author_info.get('unique_id')), | |
943d5ab1 | 235 | 'creator': str_or_none(author_info.get('nickname')), |
bd9ff55b | 236 | 'uploader_id': str_or_none(author_info.get('uid')), |
943d5ab1 | 237 | 'uploader_url': user_url, |
bd9ff55b M |
238 | 'track': music_track, |
239 | 'album': str_or_none(music_info.get('album')) or None, | |
240 | 'artist': music_author, | |
241 | 'timestamp': int_or_none(aweme_detail.get('create_time')), | |
242 | 'formats': formats, | |
e0585e65 | 243 | 'subtitles': self.extract_subtitles(aweme_detail, aweme_id), |
bd9ff55b | 244 | 'thumbnails': thumbnails, |
53dad39e M |
245 | 'duration': int_or_none(traverse_obj(video_info, 'duration', ('download_addr', 'duration')), scale=1000), |
246 | 'availability': self._availability( | |
247 | is_private='Private' in labels, | |
248 | needs_subscription='Friends only' in labels, | |
249 | is_unlisted='Followers only' in labels) | |
bd9ff55b M |
250 | } |
251 | ||
0481e266 | 252 | def _parse_aweme_video_web(self, aweme_detail, webpage_url): |
943d5ab1 | 253 | video_info = aweme_detail['video'] |
11aa91a1 | 254 | author_info = traverse_obj(aweme_detail, 'authorInfo', 'author', expected_type=dict, default={}) |
943d5ab1 M |
255 | music_info = aweme_detail.get('music') or {} |
256 | stats_info = aweme_detail.get('stats') or {} | |
257 | user_url = self._UPLOADER_URL_FORMAT % (traverse_obj(author_info, | |
258 | 'secUid', 'id', 'uid', 'uniqueId', | |
11aa91a1 M |
259 | expected_type=str_or_none, get_all=False) |
260 | or aweme_detail.get('authorSecId')) | |
943d5ab1 M |
261 | |
262 | formats = [] | |
263 | play_url = video_info.get('playAddr') | |
264 | width = video_info.get('width') | |
265 | height = video_info.get('height') | |
266 | if isinstance(play_url, str): | |
267 | formats = [{ | |
268 | 'url': self._proto_relative_url(play_url), | |
269 | 'ext': 'mp4', | |
270 | 'width': width, | |
271 | 'height': height, | |
272 | }] | |
273 | elif isinstance(play_url, list): | |
274 | formats = [{ | |
275 | 'url': self._proto_relative_url(url), | |
276 | 'ext': 'mp4', | |
277 | 'width': width, | |
278 | 'height': height, | |
279 | } for url in traverse_obj(play_url, (..., 'src'), expected_type=url_or_none, default=[]) if url] | |
280 | ||
281 | download_url = url_or_none(video_info.get('downloadAddr')) or traverse_obj(video_info, ('download', 'url'), expected_type=url_or_none) | |
282 | if download_url: | |
283 | formats.append({ | |
284 | 'format_id': 'download', | |
285 | 'url': self._proto_relative_url(download_url), | |
286 | 'ext': 'mp4', | |
287 | 'width': width, | |
288 | 'height': height, | |
289 | }) | |
290 | self._remove_duplicate_formats(formats) | |
291 | self._sort_formats(formats) | |
292 | ||
293 | thumbnails = [] | |
294 | for thumbnail_name in ('thumbnail', 'cover', 'dynamicCover', 'originCover'): | |
295 | if aweme_detail.get(thumbnail_name): | |
296 | thumbnails = [{ | |
297 | 'url': self._proto_relative_url(aweme_detail[thumbnail_name]), | |
298 | 'width': width, | |
299 | 'height': height | |
300 | }] | |
301 | ||
302 | return { | |
303 | 'id': traverse_obj(aweme_detail, 'id', 'awemeId', expected_type=str_or_none), | |
304 | 'title': aweme_detail.get('desc'), | |
305 | 'duration': try_get(aweme_detail, lambda x: x['video']['duration'], int), | |
306 | 'view_count': int_or_none(stats_info.get('playCount')), | |
307 | 'like_count': int_or_none(stats_info.get('diggCount')), | |
308 | 'repost_count': int_or_none(stats_info.get('shareCount')), | |
309 | 'comment_count': int_or_none(stats_info.get('commentCount')), | |
310 | 'timestamp': int_or_none(aweme_detail.get('createTime')), | |
311 | 'creator': str_or_none(author_info.get('nickname')), | |
11aa91a1 M |
312 | 'uploader': str_or_none(author_info.get('uniqueId') or aweme_detail.get('author')), |
313 | 'uploader_id': str_or_none(author_info.get('id') or aweme_detail.get('authorId')), | |
943d5ab1 M |
314 | 'uploader_url': user_url, |
315 | 'track': str_or_none(music_info.get('title')), | |
316 | 'album': str_or_none(music_info.get('album')) or None, | |
317 | 'artist': str_or_none(music_info.get('authorName')), | |
318 | 'formats': formats, | |
319 | 'thumbnails': thumbnails, | |
320 | 'description': str_or_none(aweme_detail.get('desc')), | |
321 | 'http_headers': { | |
0481e266 | 322 | 'Referer': webpage_url |
943d5ab1 M |
323 | } |
324 | } | |
325 | ||
0fd6661e M |
326 | |
327 | class TikTokIE(TikTokBaseIE): | |
328 | _VALID_URL = r'https?://www\.tiktok\.com/@[\w\.-]+/video/(?P<id>\d+)' | |
329 | ||
330 | _TESTS = [{ | |
331 | 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610', | |
0481e266 | 332 | 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7', |
0fd6661e M |
333 | 'info_dict': { |
334 | 'id': '6748451240264420610', | |
335 | 'ext': 'mp4', | |
336 | 'title': '#jassmanak #lehanga #leenabhushan', | |
337 | 'description': '#jassmanak #lehanga #leenabhushan', | |
338 | 'duration': 13, | |
0481e266 | 339 | 'height': 1024, |
340 | 'width': 576, | |
0fd6661e M |
341 | 'uploader': 'leenabhushan', |
342 | 'uploader_id': '6691488002098119685', | |
0481e266 | 343 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy', |
0fd6661e M |
344 | 'creator': 'facestoriesbyleenabh', |
345 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
346 | 'upload_date': '20191016', | |
347 | 'timestamp': 1571246252, | |
348 | 'view_count': int, | |
349 | 'like_count': int, | |
350 | 'repost_count': int, | |
351 | 'comment_count': int, | |
352 | } | |
353 | }, { | |
354 | 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en', | |
0481e266 | 355 | 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b', |
0fd6661e M |
356 | 'info_dict': { |
357 | 'id': '6742501081818877190', | |
358 | 'ext': 'mp4', | |
359 | 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94', | |
360 | 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94', | |
361 | 'duration': 27, | |
362 | 'height': 960, | |
363 | 'width': 540, | |
364 | 'uploader': 'patrox', | |
365 | 'uploader_id': '18702747', | |
0481e266 | 366 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws', |
0fd6661e M |
367 | 'creator': 'patroX', |
368 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
369 | 'upload_date': '20190930', | |
370 | 'timestamp': 1569860870, | |
371 | 'view_count': int, | |
372 | 'like_count': int, | |
373 | 'repost_count': int, | |
374 | 'comment_count': int, | |
375 | } | |
376 | }, { | |
96f13f01 M |
377 | # Banned audio, only available on the app |
378 | 'url': 'https://www.tiktok.com/@barudakhb_/video/6984138651336838402', | |
379 | 'info_dict': { | |
380 | 'id': '6984138651336838402', | |
381 | 'ext': 'mp4', | |
382 | 'title': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥', | |
383 | 'description': 'Balas @yolaaftwsr hayu yu ? #SquadRandom_ 🔥', | |
384 | 'uploader': 'barudakhb_', | |
385 | 'creator': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6', | |
386 | 'uploader_id': '6974687867511718913', | |
387 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAbhBwQC-R1iKoix6jDFsF-vBdfx2ABoDjaZrM9fX6arU3w71q3cOWgWuTXn1soZ7d', | |
388 | 'track': 'Boka Dance', | |
389 | 'artist': 'md5:29f238c49bc0c176cb3cef1a9cea9fa6', | |
390 | 'timestamp': 1626121503, | |
391 | 'duration': 18, | |
392 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
393 | 'upload_date': '20210712', | |
394 | 'view_count': int, | |
395 | 'like_count': int, | |
396 | 'repost_count': int, | |
397 | 'comment_count': int, | |
398 | } | |
399 | }, { | |
400 | # Sponsored video, only available with feed workaround | |
401 | 'url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_/video/7042692929109986561', | |
402 | 'info_dict': { | |
403 | 'id': '7042692929109986561', | |
404 | 'ext': 'mp4', | |
405 | 'title': 'Slap and Run!', | |
406 | 'description': 'Slap and Run!', | |
407 | 'uploader': 'user440922249', | |
408 | 'creator': 'Slap And Run', | |
409 | 'uploader_id': '7036055384943690754', | |
410 | 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAATh8Vewkn0LYM7Fo03iec3qKdeCUOcBIouRk1mkiag6h3o_pQu_dUXvZ2EZlGST7_', | |
411 | 'track': 'Promoted Music', | |
412 | 'timestamp': 1639754738, | |
413 | 'duration': 30, | |
414 | 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?', | |
415 | 'upload_date': '20211217', | |
416 | 'view_count': int, | |
417 | 'like_count': int, | |
418 | 'repost_count': int, | |
419 | 'comment_count': int, | |
420 | }, | |
421 | 'expected_warnings': ['Video not available'] | |
e0585e65 M |
422 | }, { |
423 | # Auto-captions available | |
424 | 'url': 'https://www.tiktok.com/@hankgreen1/video/7047596209028074758', | |
425 | 'only_matching': True | |
0fd6661e M |
426 | }] |
427 | ||
0fd6661e | 428 | def _extract_aweme_app(self, aweme_id): |
e540c56f M |
429 | try: |
430 | aweme_detail = self._call_api('aweme/detail', {'aweme_id': aweme_id}, aweme_id, | |
431 | note='Downloading video details', errnote='Unable to download video details').get('aweme_detail') | |
432 | if not aweme_detail: | |
433 | raise ExtractorError('Video not available', video_id=aweme_id) | |
434 | except ExtractorError as e: | |
435 | self.report_warning(f'{e}; Retrying with feed workaround') | |
436 | feed_list = self._call_api('feed', {'aweme_id': aweme_id}, aweme_id, | |
437 | note='Downloading video feed', errnote='Unable to download video feed').get('aweme_list') or [] | |
be1f331f | 438 | aweme_detail = next((aweme for aweme in feed_list if str(aweme.get('aweme_id')) == aweme_id), None) |
e540c56f M |
439 | if not aweme_detail: |
440 | raise ExtractorError('Unable to find video in feed', video_id=aweme_id) | |
943d5ab1 | 441 | return self._parse_aweme_video_app(aweme_detail) |
0fd6661e | 442 | |
ce18a19b S |
443 | def _real_extract(self, url): |
444 | video_id = self._match_id(url) | |
ce18a19b | 445 | |
bd9ff55b M |
446 | try: |
447 | return self._extract_aweme_app(video_id) | |
448 | except ExtractorError as e: | |
449 | self.report_warning(f'{e}; Retrying with webpage') | |
450 | ||
7bbc0bbc | 451 | # If we only call once, we get a 403 when downlaoding the video. |
61e76c1e | 452 | self._download_webpage(url, video_id) |
6fb11ca8 | 453 | webpage = self._download_webpage(url, video_id, note='Downloading video webpage') |
11aa91a1 M |
454 | next_json = self._search_regex( |
455 | r'id=\"__NEXT_DATA__\"\s+type=\"application\/json\"\s*[^>]+>\s*(?P<next_data>[^<]+)', | |
456 | webpage, 'next data', group='next_data', default=None) | |
457 | ||
458 | if next_json: | |
459 | next_data = self._parse_json(next_json, video_id) | |
460 | status = traverse_obj(next_data, ('props', 'pageProps', 'statusCode'), expected_type=int) or 0 | |
461 | video_data = traverse_obj(next_data, ('props', 'pageProps', 'itemInfo', 'itemStruct'), expected_type=dict) | |
462 | else: | |
463 | sigi_json = self._search_regex( | |
464 | r'>\s*window\[[\'"]SIGI_STATE[\'"]\]\s*=\s*(?P<sigi_state>{.+});', | |
465 | webpage, 'sigi data', group='sigi_state') | |
466 | sigi_data = self._parse_json(sigi_json, video_id) | |
467 | status = traverse_obj(sigi_data, ('VideoPage', 'statusCode'), expected_type=int) or 0 | |
468 | video_data = traverse_obj(sigi_data, ('ItemModule', video_id), expected_type=dict) | |
469 | ||
1418a043 | 470 | if status == 0: |
11aa91a1 | 471 | return self._parse_aweme_video_web(video_data, url) |
1418a043 | 472 | elif status == 10216: |
473 | raise ExtractorError('This video is private', expected=True) | |
6fb11ca8 | 474 | raise ExtractorError('Video not available', video_id=video_id) |
f7f18f90 A |
475 | |
476 | ||
0fd6661e | 477 | class TikTokUserIE(TikTokBaseIE): |
f7f18f90 | 478 | IE_NAME = 'tiktok:user' |
0fd6661e | 479 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])' |
f7f18f90 | 480 | _TESTS = [{ |
526d74ec | 481 | 'url': 'https://tiktok.com/@corgibobaa?lang=en', |
f7f18f90 A |
482 | 'playlist_mincount': 45, |
483 | 'info_dict': { | |
484 | 'id': '6935371178089399301', | |
0481e266 | 485 | 'title': 'corgibobaa', |
b3187433 | 486 | 'thumbnail': r're:https://.+_1080x1080\.webp' |
f7f18f90 | 487 | }, |
0481e266 | 488 | 'expected_warnings': ['Retrying'] |
f7f18f90 A |
489 | }, { |
490 | 'url': 'https://www.tiktok.com/@meme', | |
491 | 'playlist_mincount': 593, | |
492 | 'info_dict': { | |
493 | 'id': '79005827461758976', | |
0481e266 | 494 | 'title': 'meme', |
b3187433 | 495 | 'thumbnail': r're:https://.+_1080x1080\.webp' |
f7f18f90 | 496 | }, |
0481e266 | 497 | 'expected_warnings': ['Retrying'] |
f7f18f90 A |
498 | }] |
499 | ||
0fd6661e M |
500 | r''' # TODO: Fix by adding _signature to api_url |
501 | def _entries(self, webpage, user_id, username): | |
502 | secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username) | |
f7f18f90 A |
503 | verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id') |
504 | if not verifyfp_cookie: | |
505 | raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True) | |
506 | 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=' | |
507 | cursor = '0' | |
508 | for page in itertools.count(): | |
0fd6661e | 509 | data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page) |
f7f18f90 A |
510 | for video in data_json.get('itemList', []): |
511 | video_id = video['id'] | |
512 | video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}' | |
bd9ff55b | 513 | yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc'))) |
526d74ec | 514 | if not data_json.get('hasMore'): |
f7f18f90 A |
515 | break |
516 | cursor = data_json['cursor'] | |
0fd6661e M |
517 | ''' |
518 | ||
b3187433 | 519 | def _video_entries_api(self, webpage, user_id, username): |
0fd6661e M |
520 | query = { |
521 | 'user_id': user_id, | |
522 | 'count': 21, | |
523 | 'max_cursor': 0, | |
524 | 'min_cursor': 0, | |
525 | 'retry_type': 'no_retry', | |
0930b11f | 526 | '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. |
0fd6661e M |
527 | } |
528 | ||
529 | max_retries = self.get_param('extractor_retries', 3) | |
530 | for page in itertools.count(1): | |
531 | for retries in itertools.count(): | |
532 | try: | |
533 | post_list = self._call_api('aweme/post', query, username, | |
534 | note='Downloading user video list page %d%s' % (page, f' (attempt {retries})' if retries != 0 else ''), | |
535 | errnote='Unable to download user video list') | |
536 | except ExtractorError as e: | |
537 | if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0 and retries != max_retries: | |
538 | self.report_warning('%s. Retrying...' % str(e.cause or e.msg)) | |
539 | continue | |
540 | raise | |
541 | break | |
b3187433 | 542 | yield from post_list.get('aweme_list', []) |
0fd6661e M |
543 | if not post_list.get('has_more'): |
544 | break | |
545 | query['max_cursor'] = post_list['max_cursor'] | |
f7f18f90 | 546 | |
b3187433 | 547 | def _entries_api(self, user_id, videos): |
548 | for video in videos: | |
549 | yield { | |
550 | **self._parse_aweme_video_app(video), | |
551 | 'extractor_key': TikTokIE.ie_key(), | |
552 | 'extractor': 'TikTok', | |
553 | 'webpage_url': f'https://tiktok.com/@{user_id}/video/{video["aweme_id"]}', | |
554 | } | |
555 | ||
f7f18f90 | 556 | def _real_extract(self, url): |
0481e266 | 557 | user_name = self._match_id(url) |
558 | webpage = self._download_webpage(url, user_name, headers={ | |
0fd6661e M |
559 | 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)' |
560 | }) | |
0481e266 | 561 | user_id = self._html_search_regex(r'snssdk\d*://user/profile/(\d+)', webpage, 'user ID') |
b3187433 | 562 | |
563 | videos = LazyList(self._video_entries_api(webpage, user_id, user_name)) | |
564 | thumbnail = traverse_obj(videos, (0, 'author', 'avatar_larger', 'url_list', 0)) | |
565 | ||
566 | return self.playlist_result(self._entries_api(user_id, videos), user_id, user_name, thumbnail=thumbnail) | |
943d5ab1 M |
567 | |
568 | ||
8126298c M |
569 | class TikTokBaseListIE(TikTokBaseIE): |
570 | def _entries(self, list_id, display_id): | |
571 | query = { | |
572 | self._QUERY_NAME: list_id, | |
573 | 'cursor': 0, | |
574 | 'count': 20, | |
575 | 'type': 5, | |
576 | 'device_id': ''.join(random.choice(string.digits) for i in range(19)) | |
577 | } | |
578 | ||
579 | max_retries = self.get_param('extractor_retries', 3) | |
580 | for page in itertools.count(1): | |
581 | for retries in itertools.count(): | |
582 | try: | |
583 | post_list = self._call_api(self._API_ENDPOINT, query, display_id, | |
584 | note='Downloading video list page %d%s' % (page, f' (attempt {retries})' if retries != 0 else ''), | |
585 | errnote='Unable to download video list') | |
586 | except ExtractorError as e: | |
587 | if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0 and retries != max_retries: | |
588 | self.report_warning('%s. Retrying...' % str(e.cause or e.msg)) | |
589 | continue | |
590 | raise | |
591 | break | |
592 | for video in post_list.get('aweme_list', []): | |
593 | yield { | |
594 | **self._parse_aweme_video_app(video), | |
0b77924a | 595 | 'extractor_key': TikTokIE.ie_key(), |
8126298c M |
596 | 'extractor': 'TikTok', |
597 | 'webpage_url': f'https://tiktok.com/@_/video/{video["aweme_id"]}', | |
598 | } | |
599 | if not post_list.get('has_more'): | |
600 | break | |
601 | query['cursor'] = post_list['cursor'] | |
602 | ||
603 | def _real_extract(self, url): | |
604 | list_id = self._match_id(url) | |
605 | return self.playlist_result(self._entries(list_id, list_id), list_id) | |
606 | ||
607 | ||
608 | class TikTokSoundIE(TikTokBaseListIE): | |
609 | IE_NAME = 'tiktok:sound' | |
610 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/music/[\w\.-]+-(?P<id>[\d]+)[/?#&]?' | |
611 | _QUERY_NAME = 'music_id' | |
612 | _API_ENDPOINT = 'music/aweme' | |
613 | _TESTS = [{ | |
614 | 'url': 'https://www.tiktok.com/music/Build-a-Btch-6956990112127585029?lang=en', | |
615 | 'playlist_mincount': 100, | |
616 | 'info_dict': { | |
617 | 'id': '6956990112127585029' | |
618 | }, | |
619 | 'expected_warnings': ['Retrying'] | |
620 | }, { | |
621 | # Actual entries are less than listed video count | |
622 | 'url': 'https://www.tiktok.com/music/jiefei-soap-remix-7036843036118469381', | |
623 | 'playlist_mincount': 2182, | |
624 | 'info_dict': { | |
625 | 'id': '7036843036118469381' | |
626 | }, | |
627 | 'expected_warnings': ['Retrying'] | |
628 | }] | |
629 | ||
630 | ||
631 | class TikTokEffectIE(TikTokBaseListIE): | |
632 | IE_NAME = 'tiktok:effect' | |
633 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/sticker/[\w\.-]+-(?P<id>[\d]+)[/?#&]?' | |
634 | _QUERY_NAME = 'sticker_id' | |
635 | _API_ENDPOINT = 'sticker/aweme' | |
636 | _TESTS = [{ | |
637 | 'url': 'https://www.tiktok.com/sticker/MATERIAL-GWOOORL-1258156', | |
638 | 'playlist_mincount': 100, | |
639 | 'info_dict': { | |
640 | 'id': '1258156', | |
641 | }, | |
642 | 'expected_warnings': ['Retrying'] | |
643 | }, { | |
644 | # Different entries between mobile and web, depending on region | |
645 | 'url': 'https://www.tiktok.com/sticker/Elf-Friend-479565', | |
646 | 'only_matching': True | |
647 | }] | |
648 | ||
649 | ||
650 | class TikTokTagIE(TikTokBaseListIE): | |
651 | IE_NAME = 'tiktok:tag' | |
652 | _VALID_URL = r'https?://(?:www\.)?tiktok\.com/tag/(?P<id>[^/?#&]+)' | |
653 | _QUERY_NAME = 'ch_id' | |
654 | _API_ENDPOINT = 'challenge/aweme' | |
655 | _TESTS = [{ | |
656 | 'url': 'https://tiktok.com/tag/hello2018', | |
657 | 'playlist_mincount': 39, | |
658 | 'info_dict': { | |
659 | 'id': '46294678', | |
660 | 'title': 'hello2018', | |
661 | }, | |
662 | 'expected_warnings': ['Retrying'] | |
663 | }, { | |
664 | 'url': 'https://tiktok.com/tag/fypシ?is_copy_url=0&is_from_webapp=v1', | |
665 | 'only_matching': True | |
666 | }] | |
667 | ||
668 | def _real_extract(self, url): | |
669 | display_id = self._match_id(url) | |
670 | webpage = self._download_webpage(url, display_id, headers={ | |
671 | 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)' | |
672 | }) | |
673 | tag_id = self._html_search_regex(r'snssdk\d*://challenge/detail/(\d+)', webpage, 'tag ID') | |
674 | return self.playlist_result(self._entries(tag_id, display_id), tag_id, display_id) | |
675 | ||
676 | ||
943d5ab1 M |
677 | class DouyinIE(TikTokIE): |
678 | _VALID_URL = r'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)' | |
679 | _TESTS = [{ | |
680 | 'url': 'https://www.douyin.com/video/6961737553342991651', | |
681 | 'md5': '10523312c8b8100f353620ac9dc8f067', | |
682 | 'info_dict': { | |
683 | 'id': '6961737553342991651', | |
684 | 'ext': 'mp4', | |
685 | 'title': '#杨超越 小小水手带你去远航❤️', | |
686 | 'uploader': '杨超越', | |
687 | 'upload_date': '20210513', | |
688 | 'timestamp': 1620905839, | |
689 | 'uploader_id': '110403406559', | |
690 | 'view_count': int, | |
691 | 'like_count': int, | |
692 | 'repost_count': int, | |
693 | 'comment_count': int, | |
694 | } | |
695 | }, { | |
696 | 'url': 'https://www.douyin.com/video/6982497745948921092', | |
697 | 'md5': 'd78408c984b9b5102904cf6b6bc2d712', | |
698 | 'info_dict': { | |
699 | 'id': '6982497745948921092', | |
700 | 'ext': 'mp4', | |
701 | 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想', | |
702 | 'uploader': '杨超越工作室', | |
703 | 'upload_date': '20210708', | |
704 | 'timestamp': 1625739481, | |
705 | 'uploader_id': '408654318141572', | |
706 | 'view_count': int, | |
707 | 'like_count': int, | |
708 | 'repost_count': int, | |
709 | 'comment_count': int, | |
710 | } | |
711 | }, { | |
712 | 'url': 'https://www.douyin.com/video/6953975910773099811', | |
713 | 'md5': '72e882e24f75064c218b76c8b713c185', | |
714 | 'info_dict': { | |
715 | 'id': '6953975910773099811', | |
716 | 'ext': 'mp4', | |
717 | 'title': '#一起看海 出现在你的夏日里', | |
718 | 'uploader': '杨超越', | |
719 | 'upload_date': '20210422', | |
720 | 'timestamp': 1619098692, | |
721 | 'uploader_id': '110403406559', | |
722 | 'view_count': int, | |
723 | 'like_count': int, | |
724 | 'repost_count': int, | |
725 | 'comment_count': int, | |
726 | } | |
727 | }, { | |
728 | 'url': 'https://www.douyin.com/video/6950251282489675042', | |
729 | 'md5': 'b4db86aec367ef810ddd38b1737d2fed', | |
730 | 'info_dict': { | |
731 | 'id': '6950251282489675042', | |
732 | 'ext': 'mp4', | |
733 | 'title': '哈哈哈,成功了哈哈哈哈哈哈', | |
734 | 'uploader': '杨超越', | |
735 | 'upload_date': '20210412', | |
736 | 'timestamp': 1618231483, | |
737 | 'uploader_id': '110403406559', | |
738 | 'view_count': int, | |
739 | 'like_count': int, | |
740 | 'repost_count': int, | |
741 | 'comment_count': int, | |
742 | } | |
743 | }, { | |
744 | 'url': 'https://www.douyin.com/video/6963263655114722595', | |
745 | 'md5': '1abe1c477d05ee62efb40bf2329957cf', | |
746 | 'info_dict': { | |
747 | 'id': '6963263655114722595', | |
748 | 'ext': 'mp4', | |
749 | 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈', | |
750 | 'uploader': '杨超越', | |
751 | 'upload_date': '20210517', | |
752 | 'timestamp': 1621261163, | |
753 | 'uploader_id': '110403406559', | |
754 | 'view_count': int, | |
755 | 'like_count': int, | |
756 | 'repost_count': int, | |
757 | 'comment_count': int, | |
758 | } | |
759 | }] | |
760 | _APP_VERSION = '9.6.0' | |
761 | _MANIFEST_APP_VERSION = '960' | |
762 | _APP_NAME = 'aweme' | |
763 | _AID = 1128 | |
764 | _API_HOSTNAME = 'aweme.snssdk.com' | |
765 | _UPLOADER_URL_FORMAT = 'https://www.douyin.com/user/%s' | |
53dad39e | 766 | _WEBPAGE_HOST = 'https://www.douyin.com/' |
943d5ab1 M |
767 | |
768 | def _real_extract(self, url): | |
769 | video_id = self._match_id(url) | |
770 | ||
771 | try: | |
772 | return self._extract_aweme_app(video_id) | |
773 | except ExtractorError as e: | |
774 | self.report_warning(f'{e}; Retrying with webpage') | |
775 | ||
776 | webpage = self._download_webpage(url, video_id) | |
777 | render_data_json = self._search_regex( | |
778 | r'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^>]*>(%7B.+%7D)</script>', | |
779 | webpage, 'render data', default=None) | |
780 | if not render_data_json: | |
781 | # TODO: Run verification challenge code to generate signature cookies | |
782 | raise ExtractorError('Fresh cookies (not necessarily logged in) are needed') | |
783 | ||
784 | render_data = self._parse_json( | |
785 | render_data_json, video_id, transform_source=compat_urllib_parse_unquote) | |
786 | return self._parse_aweme_video_web( | |
0481e266 | 787 | traverse_obj(render_data, (..., 'aweme', 'detail'), get_all=False), url) |