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