]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/tiktok.py
[Newgrounds] Add age_limit and fix duration (#1156)
[yt-dlp.git] / yt_dlp / extractor / tiktok.py
CommitLineData
1ead840d
KS
1# coding: utf-8
2from __future__ import unicode_literals
f7f18f90
A
3
4import itertools
bd9ff55b
M
5import random
6import string
7import time
0fd6661e 8import json
1ead840d
KS
9
10from .common import InfoExtractor
11from ..utils import (
ce18a19b 12 ExtractorError,
1ead840d
KS
13 int_or_none,
14 str_or_none,
bd9ff55b
M
15 traverse_obj,
16 try_get,
17 qualities,
1ead840d
KS
18)
19
20
0fd6661e 21class TikTokBaseIE(InfoExtractor):
bd9ff55b
M
22 _APP_VERSION = '20.9.3'
23 _MANIFEST_APP_VERSION = '291'
24 QUALITIES = ('360p', '540p', '720p')
ce18a19b 25
0fd6661e
M
26 def _call_api(self, ep, query, video_id, fatal=True,
27 note='Downloading API JSON', errnote='Unable to download API page'):
28 real_query = {
29 **query,
bd9ff55b
M
30 'version_name': self._APP_VERSION,
31 'version_code': self._MANIFEST_APP_VERSION,
32 'build_number': self._APP_VERSION,
33 'manifest_version_code': self._MANIFEST_APP_VERSION,
34 'update_version_code': self._MANIFEST_APP_VERSION,
35 'openudid': ''.join(random.choice('0123456789abcdef') for i in range(16)),
36 'uuid': ''.join([random.choice(string.digits) for num in range(16)]),
37 '_rticket': int(time.time() * 1000),
38 'ts': int(time.time()),
39 'device_brand': 'Google',
40 'device_type': 'Pixel 4',
41 'device_platform': 'android',
42 'resolution': '1080*1920',
43 'dpi': 420,
44 'os_version': '10',
45 'os_api': '29',
46 'carrier_region': 'US',
47 'sys_region': 'US',
48 'region': 'US',
49 'app_name': 'trill',
50 'app_language': 'en',
51 'language': 'en',
52 'timezone_name': 'America/New_York',
53 'timezone_offset': '-14400',
54 'channel': 'googleplay',
55 'ac': 'wifi',
56 'mcc_mnc': '310260',
57 'is_my_cn': 0,
58 'aid': 1180,
59 'ssmix': 'a',
60 'as': 'a1qwert123',
61 'cp': 'cbfhckdckkde1',
62 }
bd9ff55b 63 self._set_cookie('.tiktokv.com', 'odin_tt', ''.join(random.choice('0123456789abcdef') for i in range(160)))
0fd6661e
M
64 return self._download_json(
65 'https://api-t2.tiktokv.com/aweme/v1/%s/' % ep, video_id=video_id,
66 fatal=fatal, note=note, errnote=errnote, headers={
bd9ff55b 67 '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
68 'Accept': 'application/json',
69 }, query=real_query)
70
71 def _parse_aweme_video(self, aweme_detail):
72 aweme_id = aweme_detail['aweme_id']
bd9ff55b
M
73 video_info = aweme_detail['video']
74
75 def parse_url_key(url_key):
76 format_id, codec, res, bitrate = self._search_regex(
77 r'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key,
78 'url key', default=(None, None, None, None), group=('id', 'codec', 'res', 'bitrate'))
79 if not format_id:
80 return {}, None
81 return {
82 'format_id': format_id,
83 'vcodec': 'h265' if codec == 'bytevc1' else codec,
84 'tbr': int_or_none(bitrate, scale=1000) or None,
85 'quality': qualities(self.QUALITIES)(res),
86 }, res
87
88 known_resolutions = {}
89
90 def extract_addr(addr, add_meta={}):
91 parsed_meta, res = parse_url_key(addr.get('url_key', ''))
92 if res:
93 known_resolutions.setdefault(res, {}).setdefault('height', add_meta.get('height'))
94 known_resolutions[res].setdefault('width', add_meta.get('width'))
95 parsed_meta.update(known_resolutions.get(res, {}))
96 add_meta.setdefault('height', int_or_none(res[:-1]))
97 return [{
98 'url': url,
99 'filesize': int_or_none(addr.get('data_size')),
100 'ext': 'mp4',
101 'acodec': 'aac',
0fd6661e
M
102 'source_preference': -2 if 'aweme/v1' in url else -1, # Downloads from API might get blocked
103 **add_meta, **parsed_meta,
104 'format_note': ' '.join(filter(None, (
105 add_meta.get('format_note'), '(API)' if 'aweme/v1' in url else '')))
bd9ff55b
M
106 } for url in addr.get('url_list') or []]
107
108 # Hack: Add direct video links first to prioritize them when removing duplicate formats
109 formats = []
110 if video_info.get('play_addr'):
111 formats.extend(extract_addr(video_info['play_addr'], {
112 'format_id': 'play_addr',
113 'format_note': 'Direct video',
114 'vcodec': 'h265' if traverse_obj(
115 video_info, 'is_bytevc1', 'is_h265') else 'h264', # Always h264?
116 'width': video_info.get('width'),
117 'height': video_info.get('height'),
118 }))
119 if video_info.get('download_addr'):
120 formats.extend(extract_addr(video_info['download_addr'], {
121 'format_id': 'download_addr',
122 'format_note': 'Download video%s' % (', watermarked' if video_info.get('has_watermark') else ''),
123 'vcodec': 'h264',
124 'width': video_info.get('width'),
125 'height': video_info.get('height'),
0fd6661e 126 'preference': -2 if video_info.get('has_watermark') else -1,
bd9ff55b
M
127 }))
128 if video_info.get('play_addr_h264'):
129 formats.extend(extract_addr(video_info['play_addr_h264'], {
130 'format_id': 'play_addr_h264',
131 'format_note': 'Direct video',
132 'vcodec': 'h264',
133 }))
134 if video_info.get('play_addr_bytevc1'):
135 formats.extend(extract_addr(video_info['play_addr_bytevc1'], {
136 'format_id': 'play_addr_bytevc1',
137 'format_note': 'Direct video',
138 'vcodec': 'h265',
139 }))
140
141 for bitrate in video_info.get('bit_rate', []):
142 if bitrate.get('play_addr'):
143 formats.extend(extract_addr(bitrate['play_addr'], {
144 'format_id': bitrate.get('gear_name'),
145 'format_note': 'Playback video',
146 'tbr': try_get(bitrate, lambda x: x['bit_rate'] / 1000),
147 'vcodec': 'h265' if traverse_obj(
148 bitrate, 'is_bytevc1', 'is_h265') else 'h264',
149 }))
150
151 self._remove_duplicate_formats(formats)
0fd6661e 152 self._sort_formats(formats, ('quality', 'codec', 'size', 'br'))
bd9ff55b
M
153
154 thumbnails = []
155 for cover_id in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
156 'origin_cover', 'dynamic_cover'):
157 cover = video_info.get(cover_id)
158 if cover:
159 for cover_url in cover['url_list']:
160 thumbnails.append({
161 'id': cover_id,
162 'url': cover_url,
163 })
164
165 stats_info = aweme_detail.get('statistics', {})
166 author_info = aweme_detail.get('author', {})
167 music_info = aweme_detail.get('music', {})
168 user_id = str_or_none(author_info.get('nickname'))
169
170 contained_music_track = traverse_obj(
171 music_info, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type=str)
172 contained_music_author = traverse_obj(
173 music_info, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type=str)
174
175 is_generic_og_trackname = music_info.get('is_original_sound') and music_info.get('title') == 'original sound - %s' % music_info.get('owner_handle')
176 if is_generic_og_trackname:
177 music_track, music_author = contained_music_track or 'original sound', contained_music_author
178 else:
179 music_track, music_author = music_info.get('title'), music_info.get('author')
180
181 return {
182 'id': aweme_id,
183 'title': aweme_detail['desc'],
184 'description': aweme_detail['desc'],
185 'view_count': int_or_none(stats_info.get('play_count')),
186 'like_count': int_or_none(stats_info.get('digg_count')),
187 'repost_count': int_or_none(stats_info.get('share_count')),
188 'comment_count': int_or_none(stats_info.get('comment_count')),
189 'uploader': str_or_none(author_info.get('unique_id')),
190 'creator': user_id,
191 'uploader_id': str_or_none(author_info.get('uid')),
192 'uploader_url': f'https://www.tiktok.com/@{user_id}' if user_id else None,
193 'track': music_track,
194 'album': str_or_none(music_info.get('album')) or None,
195 'artist': music_author,
196 'timestamp': int_or_none(aweme_detail.get('create_time')),
197 'formats': formats,
198 'thumbnails': thumbnails,
199 'duration': int_or_none(traverse_obj(video_info, 'duration', ('download_addr', 'duration')), scale=1000)
200 }
201
0fd6661e
M
202
203class TikTokIE(TikTokBaseIE):
204 _VALID_URL = r'https?://www\.tiktok\.com/@[\w\.-]+/video/(?P<id>\d+)'
205
206 _TESTS = [{
207 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
208 'md5': '34a7543afd5a151b0840ba6736fb633b',
209 'info_dict': {
210 'id': '6748451240264420610',
211 'ext': 'mp4',
212 'title': '#jassmanak #lehanga #leenabhushan',
213 'description': '#jassmanak #lehanga #leenabhushan',
214 'duration': 13,
215 'height': 1280,
216 'width': 720,
217 'uploader': 'leenabhushan',
218 'uploader_id': '6691488002098119685',
219 'uploader_url': 'https://www.tiktok.com/@leenabhushan',
220 'creator': 'facestoriesbyleenabh',
221 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
222 'upload_date': '20191016',
223 'timestamp': 1571246252,
224 'view_count': int,
225 'like_count': int,
226 'repost_count': int,
227 'comment_count': int,
228 }
229 }, {
230 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
231 'md5': '06b9800d47d5fe51a19e322dd86e61c9',
232 'info_dict': {
233 'id': '6742501081818877190',
234 'ext': 'mp4',
235 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
236 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
237 'duration': 27,
238 'height': 960,
239 'width': 540,
240 'uploader': 'patrox',
241 'uploader_id': '18702747',
242 'uploader_url': 'https://www.tiktok.com/@patrox',
243 'creator': 'patroX',
244 'thumbnail': r're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
245 'upload_date': '20190930',
246 'timestamp': 1569860870,
247 'view_count': int,
248 'like_count': int,
249 'repost_count': int,
250 'comment_count': int,
251 }
252 }, {
253 # Promoted content/ad
254 'url': 'https://www.tiktok.com/@MS4wLjABAAAAAR29F6J2Ktu0Daw03BJyXPNoRQ-W7U5a0Mn3lVCq2rQhjOd_WNLclHUoFgwX8Eno/video/6932675057474981122',
255 'only_matching': True,
256 }]
257
258 def _extract_aweme(self, props_data, webpage, url):
259 video_info = try_get(
260 props_data, lambda x: x['pageProps']['itemInfo']['itemStruct'], dict)
261 author_info = try_get(
262 props_data, lambda x: x['pageProps']['itemInfo']['itemStruct']['author'], dict) or {}
263 music_info = try_get(
264 props_data, lambda x: x['pageProps']['itemInfo']['itemStruct']['music'], dict) or {}
265 stats_info = try_get(props_data, lambda x: x['pageProps']['itemInfo']['itemStruct']['stats'], dict) or {}
266
267 user_id = str_or_none(author_info.get('uniqueId'))
268 download_url = try_get(video_info, (lambda x: x['video']['playAddr'],
269 lambda x: x['video']['downloadAddr']))
270 height = try_get(video_info, lambda x: x['video']['height'], int)
271 width = try_get(video_info, lambda x: x['video']['width'], int)
272 thumbnails = [{
273 'url': video_info.get('thumbnail') or self._og_search_thumbnail(webpage),
274 'width': width,
275 'height': height
276 }]
277 tracker = try_get(props_data, lambda x: x['initialProps']['$wid'])
278
279 return {
280 'id': str_or_none(video_info.get('id')),
281 'url': download_url,
282 'ext': 'mp4',
283 'height': height,
284 'width': width,
285 'title': video_info.get('desc') or self._og_search_title(webpage),
286 'duration': try_get(video_info, lambda x: x['video']['duration'], int),
287 'view_count': int_or_none(stats_info.get('playCount')),
288 'like_count': int_or_none(stats_info.get('diggCount')),
289 'repost_count': int_or_none(stats_info.get('shareCount')),
290 'comment_count': int_or_none(stats_info.get('commentCount')),
291 'timestamp': try_get(video_info, lambda x: int(x['createTime']), int),
292 'creator': str_or_none(author_info.get('nickname')),
293 'uploader': user_id,
294 'uploader_id': str_or_none(author_info.get('id')),
295 'uploader_url': f'https://www.tiktok.com/@{user_id}',
296 'track': str_or_none(music_info.get('title')),
297 'album': str_or_none(music_info.get('album')) or None,
298 'artist': str_or_none(music_info.get('authorName')),
299 'thumbnails': thumbnails,
300 'description': str_or_none(video_info.get('desc')),
301 'webpage_url': self._og_search_url(webpage),
302 'http_headers': {
303 'Referer': url,
304 'Cookie': 'tt_webid=%s; tt_webid_v2=%s' % (tracker, tracker),
305 }
306 }
307
308 def _extract_aweme_app(self, aweme_id):
309 aweme_detail = self._call_api('aweme/detail', {'aweme_id': aweme_id}, aweme_id,
310 note='Downloading video details', errnote='Unable to download video details')['aweme_detail']
311 return self._parse_aweme_video(aweme_detail)
312
ce18a19b
S
313 def _real_extract(self, url):
314 video_id = self._match_id(url)
ce18a19b 315
bd9ff55b
M
316 try:
317 return self._extract_aweme_app(video_id)
318 except ExtractorError as e:
319 self.report_warning(f'{e}; Retrying with webpage')
320
7bbc0bbc 321 # If we only call once, we get a 403 when downlaoding the video.
61e76c1e 322 self._download_webpage(url, video_id)
6fb11ca8 323 webpage = self._download_webpage(url, video_id, note='Downloading video webpage')
4b6d03ed 324 json_string = self._search_regex(
6255e567
AG
325 r'id=\"__NEXT_DATA__\"\s+type=\"application\/json\"\s*[^>]+>\s*(?P<json_string_ld>[^<]+)',
326 webpage, 'json_string', group='json_string_ld')
4b6d03ed 327 json_data = self._parse_json(json_string, video_id)
4f5a0ad8 328 props_data = try_get(json_data, lambda x: x['props'], expected_type=dict)
ce18a19b 329
4b6d03ed 330 # Chech statusCode for success
1418a043 331 status = props_data.get('pageProps').get('statusCode')
332 if status == 0:
4f5a0ad8 333 return self._extract_aweme(props_data, webpage, url)
1418a043 334 elif status == 10216:
335 raise ExtractorError('This video is private', expected=True)
4b6d03ed 336
6fb11ca8 337 raise ExtractorError('Video not available', video_id=video_id)
f7f18f90
A
338
339
0fd6661e 340class TikTokUserIE(TikTokBaseIE):
f7f18f90 341 IE_NAME = 'tiktok:user'
0fd6661e 342 _VALID_URL = r'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
f7f18f90 343 _TESTS = [{
526d74ec 344 'url': 'https://tiktok.com/@corgibobaa?lang=en',
f7f18f90
A
345 'playlist_mincount': 45,
346 'info_dict': {
347 'id': '6935371178089399301',
348 },
f7f18f90
A
349 }, {
350 'url': 'https://www.tiktok.com/@meme',
351 'playlist_mincount': 593,
352 'info_dict': {
353 'id': '79005827461758976',
354 },
f7f18f90
A
355 }]
356
0fd6661e
M
357 r''' # TODO: Fix by adding _signature to api_url
358 def _entries(self, webpage, user_id, username):
359 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
f7f18f90
A
360 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
361 if not verifyfp_cookie:
362 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
363 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='
364 cursor = '0'
365 for page in itertools.count():
0fd6661e 366 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
f7f18f90
A
367 for video in data_json.get('itemList', []):
368 video_id = video['id']
369 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
bd9ff55b 370 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
526d74ec 371 if not data_json.get('hasMore'):
f7f18f90
A
372 break
373 cursor = data_json['cursor']
0fd6661e
M
374 '''
375
376 def _entries_api(self, webpage, user_id, username):
377 query = {
378 'user_id': user_id,
379 'count': 21,
380 'max_cursor': 0,
381 'min_cursor': 0,
382 'retry_type': 'no_retry',
383 'device_id': ''.join(random.choice(string.digits) for i in range(19)), # Some endpoints don't like randomized device_id, so it isn't directly set in _call_api.
384 }
385
386 max_retries = self.get_param('extractor_retries', 3)
387 for page in itertools.count(1):
388 for retries in itertools.count():
389 try:
390 post_list = self._call_api('aweme/post', query, username,
391 note='Downloading user video list page %d%s' % (page, f' (attempt {retries})' if retries != 0 else ''),
392 errnote='Unable to download user video list')
393 except ExtractorError as e:
394 if isinstance(e.cause, json.JSONDecodeError) and e.cause.pos == 0 and retries != max_retries:
395 self.report_warning('%s. Retrying...' % str(e.cause or e.msg))
396 continue
397 raise
398 break
399 for video in post_list.get('aweme_list', []):
400 yield {
401 **self._parse_aweme_video(video),
402 'ie_key': TikTokIE.ie_key(),
403 'extractor': 'TikTok',
404 }
405 if not post_list.get('has_more'):
406 break
407 query['max_cursor'] = post_list['max_cursor']
f7f18f90
A
408
409 def _real_extract(self, url):
410 user_id = self._match_id(url)
0fd6661e
M
411 webpage = self._download_webpage(url, user_id, headers={
412 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
413 })
414 own_id = self._html_search_regex(r'snssdk\d*://user/profile/(\d+)', webpage, 'user ID')
415 return self.playlist_result(self._entries_api(webpage, own_id, user_id), user_id)