tiktok.py 42 KB

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