2 from __future__
import unicode_literals
10 from .common
import InfoExtractor
11 from ..compat
import compat_urllib_parse_unquote
24 class TikTokBaseIE(InfoExtractor
):
25 _APP_VERSION
= '20.9.3'
26 _MANIFEST_APP_VERSION
= '291'
29 _API_HOSTNAME
= 'api-t2.tiktokv.com'
30 _UPLOADER_URL_FORMAT
= 'https://www.tiktok.com/@%s'
31 QUALITIES
= ('360p', '540p', '720p')
33 def _call_api(self
, ep
, query
, video_id
, fatal
=True,
34 note
='Downloading API JSON', errnote
='Unable to download API page'):
37 'version_name': self
._APP
_VERSION
,
38 'version_code': self
._MANIFEST
_APP
_VERSION
,
39 'build_number': self
._APP
_VERSION
,
40 'manifest_version_code': self
._MANIFEST
_APP
_VERSION
,
41 'update_version_code': self
._MANIFEST
_APP
_VERSION
,
42 'openudid': ''.join(random
.choice('0123456789abcdef') for _
in range(16)),
43 'uuid': ''.join([random
.choice(string
.digits
) for _
in range(16)]),
44 '_rticket': int(time
.time() * 1000),
45 'ts': int(time
.time()),
46 'device_brand': 'Google',
47 'device_type': 'Pixel 4',
48 'device_platform': 'android',
49 'resolution': '1080*1920',
53 'carrier_region': 'US',
56 'app_name': self
._APP
_NAME
,
59 'timezone_name': 'America/New_York',
60 'timezone_offset': '-14400',
61 'channel': 'googleplay',
68 'cp': 'cbfhckdckkde1',
70 self
._set
_cookie
(self
._API
_HOSTNAME
, 'odin_tt', ''.join(random
.choice('0123456789abcdef') for _
in range(160)))
71 return self
._download
_json
(
72 'https://%s/aweme/v1/%s/' % (self
._API
_HOSTNAME
, ep
), video_id
=video_id
,
73 fatal
=fatal
, note
=note
, errnote
=errnote
, headers
={
74 '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)',
75 'Accept': 'application/json',
78 def _parse_aweme_video_app(self
, aweme_detail
):
79 aweme_id
= aweme_detail
['aweme_id']
80 video_info
= aweme_detail
['video']
82 def parse_url_key(url_key
):
83 format_id
, codec
, res
, bitrate
= self
._search
_regex
(
84 r
'v[^_]+_(?P<id>(?P<codec>[^_]+)_(?P<res>\d+p)_(?P<bitrate>\d+))', url_key
,
85 'url key', default
=(None, None, None, None), group
=('id', 'codec', 'res', 'bitrate'))
89 'format_id': format_id
,
90 'vcodec': 'h265' if codec
== 'bytevc1' else codec
,
91 'tbr': int_or_none(bitrate
, scale
=1000) or None,
92 'quality': qualities(self
.QUALITIES
)(res
),
95 known_resolutions
= {}
97 def extract_addr(addr
, add_meta
={}):
98 parsed_meta
, res
= parse_url_key(addr
.get('url_key', ''))
100 known_resolutions
.setdefault(res
, {}).setdefault('height', add_meta
.get('height'))
101 known_resolutions
[res
].setdefault('width', add_meta
.get('width'))
102 parsed_meta
.update(known_resolutions
.get(res
, {}))
103 add_meta
.setdefault('height', int_or_none(res
[:-1]))
106 'filesize': int_or_none(addr
.get('data_size')),
109 'source_preference': -2 if 'aweme/v1' in url
else -1, # Downloads from API might get blocked
110 **add_meta
, **parsed_meta
,
111 'format_note': join_nonempty(
112 add_meta
.get('format_note'), '(API)' if 'aweme/v1' in url
else None, delim
=' ')
113 } for url
in addr
.get('url_list') or []]
115 # Hack: Add direct video links first to prioritize them when removing duplicate formats
117 if video_info
.get('play_addr'):
118 formats
.extend(extract_addr(video_info
['play_addr'], {
119 'format_id': 'play_addr',
120 'format_note': 'Direct video',
121 'vcodec': 'h265' if traverse_obj(
122 video_info
, 'is_bytevc1', 'is_h265') else 'h264', # Always h264?
123 'width': video_info
.get('width'),
124 'height': video_info
.get('height'),
126 if video_info
.get('download_addr'):
127 formats
.extend(extract_addr(video_info
['download_addr'], {
128 'format_id': 'download_addr',
129 'format_note': 'Download video%s' % (', watermarked' if video_info
.get('has_watermark') else ''),
131 'width': video_info
.get('width'),
132 'height': video_info
.get('height'),
133 'preference': -2 if video_info
.get('has_watermark') else -1,
135 if video_info
.get('play_addr_h264'):
136 formats
.extend(extract_addr(video_info
['play_addr_h264'], {
137 'format_id': 'play_addr_h264',
138 'format_note': 'Direct video',
141 if video_info
.get('play_addr_bytevc1'):
142 formats
.extend(extract_addr(video_info
['play_addr_bytevc1'], {
143 'format_id': 'play_addr_bytevc1',
144 'format_note': 'Direct video',
148 for bitrate
in video_info
.get('bit_rate', []):
149 if bitrate
.get('play_addr'):
150 formats
.extend(extract_addr(bitrate
['play_addr'], {
151 'format_id': bitrate
.get('gear_name'),
152 'format_note': 'Playback video',
153 'tbr': try_get(bitrate
, lambda x
: x
['bit_rate'] / 1000),
154 'vcodec': 'h265' if traverse_obj(
155 bitrate
, 'is_bytevc1', 'is_h265') else 'h264',
156 'fps': bitrate
.get('FPS'),
159 self
._remove
_duplicate
_formats
(formats
)
160 self
._sort
_formats
(formats
, ('quality', 'codec', 'size', 'br'))
163 for cover_id
in ('cover', 'ai_dynamic_cover', 'animated_cover', 'ai_dynamic_cover_bak',
164 'origin_cover', 'dynamic_cover'):
165 cover
= video_info
.get(cover_id
)
167 for cover_url
in cover
['url_list']:
173 stats_info
= aweme_detail
.get('statistics', {})
174 author_info
= aweme_detail
.get('author', {})
175 music_info
= aweme_detail
.get('music', {})
176 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
177 'sec_uid', 'id', 'uid', 'unique_id',
178 expected_type
=str_or_none
, get_all
=False))
180 contained_music_track
= traverse_obj(
181 music_info
, ('matched_song', 'title'), ('matched_pgc_sound', 'title'), expected_type
=str)
182 contained_music_author
= traverse_obj(
183 music_info
, ('matched_song', 'author'), ('matched_pgc_sound', 'author'), 'author', expected_type
=str)
185 is_generic_og_trackname
= music_info
.get('is_original_sound') and music_info
.get('title') == 'original sound - %s' % music_info
.get('owner_handle')
186 if is_generic_og_trackname
:
187 music_track
, music_author
= contained_music_track
or 'original sound', contained_music_author
189 music_track
, music_author
= music_info
.get('title'), music_info
.get('author')
193 'title': aweme_detail
['desc'],
194 'description': aweme_detail
['desc'],
195 'view_count': int_or_none(stats_info
.get('play_count')),
196 'like_count': int_or_none(stats_info
.get('digg_count')),
197 'repost_count': int_or_none(stats_info
.get('share_count')),
198 'comment_count': int_or_none(stats_info
.get('comment_count')),
199 'uploader': str_or_none(author_info
.get('unique_id')),
200 'creator': str_or_none(author_info
.get('nickname')),
201 'uploader_id': str_or_none(author_info
.get('uid')),
202 'uploader_url': user_url
,
203 'track': music_track
,
204 'album': str_or_none(music_info
.get('album')) or None,
205 'artist': music_author
,
206 'timestamp': int_or_none(aweme_detail
.get('create_time')),
208 'thumbnails': thumbnails
,
209 'duration': int_or_none(traverse_obj(video_info
, 'duration', ('download_addr', 'duration')), scale
=1000)
212 def _parse_aweme_video_web(self
, aweme_detail
, webpage_url
):
213 video_info
= aweme_detail
['video']
214 author_info
= traverse_obj(aweme_detail
, 'author', 'authorInfo', default
={})
215 music_info
= aweme_detail
.get('music') or {}
216 stats_info
= aweme_detail
.get('stats') or {}
217 user_url
= self
._UPLOADER
_URL
_FORMAT
% (traverse_obj(author_info
,
218 'secUid', 'id', 'uid', 'uniqueId',
219 expected_type
=str_or_none
, get_all
=False))
222 play_url
= video_info
.get('playAddr')
223 width
= video_info
.get('width')
224 height
= video_info
.get('height')
225 if isinstance(play_url
, str):
227 'url': self
._proto
_relative
_url
(play_url
),
232 elif isinstance(play_url
, list):
234 'url': self
._proto
_relative
_url
(url
),
238 } for url
in traverse_obj(play_url
, (..., 'src'), expected_type
=url_or_none
, default
=[]) if url
]
240 download_url
= url_or_none(video_info
.get('downloadAddr')) or traverse_obj(video_info
, ('download', 'url'), expected_type
=url_or_none
)
243 'format_id': 'download',
244 'url': self
._proto
_relative
_url
(download_url
),
249 self
._remove
_duplicate
_formats
(formats
)
250 self
._sort
_formats
(formats
)
253 for thumbnail_name
in ('thumbnail', 'cover', 'dynamicCover', 'originCover'):
254 if aweme_detail
.get(thumbnail_name
):
256 'url': self
._proto
_relative
_url
(aweme_detail
[thumbnail_name
]),
262 'id': traverse_obj(aweme_detail
, 'id', 'awemeId', expected_type
=str_or_none
),
263 'title': aweme_detail
.get('desc'),
264 'duration': try_get(aweme_detail
, lambda x
: x
['video']['duration'], int),
265 'view_count': int_or_none(stats_info
.get('playCount')),
266 'like_count': int_or_none(stats_info
.get('diggCount')),
267 'repost_count': int_or_none(stats_info
.get('shareCount')),
268 'comment_count': int_or_none(stats_info
.get('commentCount')),
269 'timestamp': int_or_none(aweme_detail
.get('createTime')),
270 'creator': str_or_none(author_info
.get('nickname')),
271 'uploader': str_or_none(author_info
.get('uniqueId')),
272 'uploader_id': str_or_none(author_info
.get('id')),
273 'uploader_url': user_url
,
274 'track': str_or_none(music_info
.get('title')),
275 'album': str_or_none(music_info
.get('album')) or None,
276 'artist': str_or_none(music_info
.get('authorName')),
278 'thumbnails': thumbnails
,
279 'description': str_or_none(aweme_detail
.get('desc')),
281 'Referer': webpage_url
286 class TikTokIE(TikTokBaseIE
):
287 _VALID_URL
= r
'https?://www\.tiktok\.com/@[\w\.-]+/video/(?P<id>\d+)'
290 'url': 'https://www.tiktok.com/@leenabhushan/video/6748451240264420610',
291 'md5': '736bb7a466c6f0a6afeb597da1e6f5b7',
293 'id': '6748451240264420610',
295 'title': '#jassmanak #lehanga #leenabhushan',
296 'description': '#jassmanak #lehanga #leenabhushan',
300 'uploader': 'leenabhushan',
301 'uploader_id': '6691488002098119685',
302 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAA_Eb4t1vodM1IuTy_cvp9CY22RAb59xqrO0Xtz9CYQJvgXaDvZxYnZYRzDWhhgJmy',
303 'creator': 'facestoriesbyleenabh',
304 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
305 'upload_date': '20191016',
306 'timestamp': 1571246252,
310 'comment_count': int,
313 'url': 'https://www.tiktok.com/@patroxofficial/video/6742501081818877190?langCountry=en',
314 'md5': '6f3cf8cdd9b28cb8363fe0a9a160695b',
316 'id': '6742501081818877190',
318 'title': 'md5:5e2a23877420bb85ce6521dbee39ba94',
319 'description': 'md5:5e2a23877420bb85ce6521dbee39ba94',
323 'uploader': 'patrox',
324 'uploader_id': '18702747',
325 'uploader_url': 'https://www.tiktok.com/@MS4wLjABAAAAiFnldaILebi5heDoVU6bn4jBWWycX6-9U3xuNPqZ8Ws',
327 'thumbnail': r
're:^https?://[\w\/\.\-]+(~[\w\-]+\.image)?',
328 'upload_date': '20190930',
329 'timestamp': 1569860870,
333 'comment_count': int,
336 # Promoted content/ad
337 'url': 'https://www.tiktok.com/@MS4wLjABAAAAAR29F6J2Ktu0Daw03BJyXPNoRQ-W7U5a0Mn3lVCq2rQhjOd_WNLclHUoFgwX8Eno/video/6932675057474981122',
338 'only_matching': True,
341 def _extract_aweme_app(self
, aweme_id
):
342 aweme_detail
= self
._call
_api
('aweme/detail', {'aweme_id': aweme_id}
, aweme_id
,
343 note
='Downloading video details', errnote
='Unable to download video details')['aweme_detail']
344 return self
._parse
_aweme
_video
_app
(aweme_detail
)
346 def _real_extract(self
, url
):
347 video_id
= self
._match
_id
(url
)
350 return self
._extract
_aweme
_app
(video_id
)
351 except ExtractorError
as e
:
352 self
.report_warning(f
'{e}; Retrying with webpage')
354 # If we only call once, we get a 403 when downlaoding the video.
355 self
._download
_webpage
(url
, video_id
)
356 webpage
= self
._download
_webpage
(url
, video_id
, note
='Downloading video webpage')
357 json_string
= self
._search
_regex
(
358 r
'id=\"__NEXT_DATA__\"\s+type=\"application\/json\"\s*[^>]+>\s*(?P<json_string_ld>[^<]+)',
359 webpage
, 'json_string', group
='json_string_ld')
360 json_data
= self
._parse
_json
(json_string
, video_id
)
361 props_data
= try_get(json_data
, lambda x
: x
['props'], expected_type
=dict)
363 # Chech statusCode for success
364 status
= props_data
.get('pageProps').get('statusCode')
366 return self
._parse
_aweme
_video
_web
(props_data
['pageProps']['itemInfo']['itemStruct'], url
)
367 elif status
== 10216:
368 raise ExtractorError('This video is private', expected
=True)
370 raise ExtractorError('Video not available', video_id
=video_id
)
373 class TikTokUserIE(TikTokBaseIE
):
374 IE_NAME
= 'tiktok:user'
375 _VALID_URL
= r
'https?://(?:www\.)?tiktok\.com/@(?P<id>[\w\.-]+)/?(?:$|[#?])'
377 'url': 'https://tiktok.com/@corgibobaa?lang=en',
378 'playlist_mincount': 45,
380 'id': '6935371178089399301',
381 'title': 'corgibobaa',
383 'expected_warnings': ['Retrying']
385 'url': 'https://www.tiktok.com/@meme',
386 'playlist_mincount': 593,
388 'id': '79005827461758976',
391 'expected_warnings': ['Retrying']
394 r
''' # TODO: Fix by adding _signature to api_url
395 def _entries(self, webpage, user_id, username):
396 secuid = self._search_regex(r'\"secUid\":\"(?P<secUid>[^\"]+)', webpage, username)
397 verifyfp_cookie = self._get_cookies('https://www.tiktok.com').get('s_v_web_id')
398 if not verifyfp_cookie:
399 raise ExtractorError('Improper cookies (missing s_v_web_id).', expected=True)
400 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='
402 for page in itertools.count():
403 data_json = self._download_json(api_url + cursor, username, note='Downloading Page %d' % page)
404 for video in data_json.get('itemList', []):
405 video_id = video['id']
406 video_url = f'https://www.tiktok.com/@{user_id}/video/{video_id}'
407 yield self._url_result(video_url, 'TikTok', video_id, str_or_none(video.get('desc')))
408 if not data_json.get('hasMore'):
410 cursor = data_json['cursor']
413 def _entries_api(self
, webpage
, user_id
, username
):
419 'retry_type': 'no_retry',
420 '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.
423 max_retries
= self
.get_param('extractor_retries', 3)
424 for page
in itertools
.count(1):
425 for retries
in itertools
.count():
427 post_list
= self
._call
_api
('aweme/post', query
, username
,
428 note
='Downloading user video list page %d%s' % (page
, f
' (attempt {retries})' if retries
!= 0 else ''),
429 errnote
='Unable to download user video list')
430 except ExtractorError
as e
:
431 if isinstance(e
.cause
, json
.JSONDecodeError
) and e
.cause
.pos
== 0 and retries
!= max_retries
:
432 self
.report_warning('%s. Retrying...' % str(e
.cause
or e
.msg
))
436 for video
in post_list
.get('aweme_list', []):
438 **self
._parse
_aweme
_video
_app
(video
),
439 'ie_key': TikTokIE
.ie_key(),
440 'extractor': 'TikTok',
442 if not post_list
.get('has_more'):
444 query
['max_cursor'] = post_list
['max_cursor']
446 def _real_extract(self
, url
):
447 user_name
= self
._match
_id
(url
)
448 webpage
= self
._download
_webpage
(url
, user_name
, headers
={
449 'User-Agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
451 user_id
= self
._html
_search
_regex
(r
'snssdk\d*://user/profile/(\d+)', webpage
, 'user ID')
452 return self
.playlist_result(self
._entries
_api
(webpage
, user_id
, user_name
), user_id
, user_name
)
455 class DouyinIE(TikTokIE
):
456 _VALID_URL
= r
'https?://(?:www\.)?douyin\.com/video/(?P<id>[0-9]+)'
458 'url': 'https://www.douyin.com/video/6961737553342991651',
459 'md5': '10523312c8b8100f353620ac9dc8f067',
461 'id': '6961737553342991651',
463 'title': '#杨超越 小小水手带你去远航❤️',
465 'upload_date': '20210513',
466 'timestamp': 1620905839,
467 'uploader_id': '110403406559',
471 'comment_count': int,
474 'url': 'https://www.douyin.com/video/6982497745948921092',
475 'md5': 'd78408c984b9b5102904cf6b6bc2d712',
477 'id': '6982497745948921092',
479 'title': '这个夏日和小羊@杨超越 一起遇见白色幻想',
480 'uploader': '杨超越工作室',
481 'upload_date': '20210708',
482 'timestamp': 1625739481,
483 'uploader_id': '408654318141572',
487 'comment_count': int,
490 'url': 'https://www.douyin.com/video/6953975910773099811',
491 'md5': '72e882e24f75064c218b76c8b713c185',
493 'id': '6953975910773099811',
495 'title': '#一起看海 出现在你的夏日里',
497 'upload_date': '20210422',
498 'timestamp': 1619098692,
499 'uploader_id': '110403406559',
503 'comment_count': int,
506 'url': 'https://www.douyin.com/video/6950251282489675042',
507 'md5': 'b4db86aec367ef810ddd38b1737d2fed',
509 'id': '6950251282489675042',
511 'title': '哈哈哈,成功了哈哈哈哈哈哈',
513 'upload_date': '20210412',
514 'timestamp': 1618231483,
515 'uploader_id': '110403406559',
519 'comment_count': int,
522 'url': 'https://www.douyin.com/video/6963263655114722595',
523 'md5': '1abe1c477d05ee62efb40bf2329957cf',
525 'id': '6963263655114722595',
527 'title': '#哪个爱豆的105度最甜 换个角度看看我哈哈',
529 'upload_date': '20210517',
530 'timestamp': 1621261163,
531 'uploader_id': '110403406559',
535 'comment_count': int,
538 _APP_VERSION
= '9.6.0'
539 _MANIFEST_APP_VERSION
= '960'
542 _API_HOSTNAME
= 'aweme.snssdk.com'
543 _UPLOADER_URL_FORMAT
= 'https://www.douyin.com/user/%s'
545 def _real_extract(self
, url
):
546 video_id
= self
._match
_id
(url
)
549 return self
._extract
_aweme
_app
(video_id
)
550 except ExtractorError
as e
:
551 self
.report_warning(f
'{e}; Retrying with webpage')
553 webpage
= self
._download
_webpage
(url
, video_id
)
554 render_data_json
= self
._search
_regex
(
555 r
'<script [^>]*\bid=[\'"]RENDER_DATA[\'"][^
>]*>(%7B
.+%7D
)</script
>',
556 webpage, 'render data
', default=None)
557 if not render_data_json:
558 # TODO: Run verification challenge code to generate signature cookies
559 raise ExtractorError('Fresh
cookies (not necessarily logged
in) are needed
')
561 render_data = self._parse_json(
562 render_data_json, video_id, transform_source=compat_urllib_parse_unquote)
563 return self._parse_aweme_video_web(
564 traverse_obj(render_data, (..., 'aweme
', 'detail
'), get_all=False), url)