Debian Codegraph @

gallery_dl/extractor/tiktok.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License version 2 as
5 # published by the Free Software Foundation.
6
7 """Extractors for https://www.tiktok.com/"""
8
9 from .common import Extractor, Message, Dispatch
10 from .. import text, util, ytdl
11 import functools
12 import itertools
13 import hashlib
14 import random
15 import time
16
17 BASE_PATTERN = r"(?:https?://)?(?:www\.)?tiktokv?\.com"
18 USER_PATTERN = BASE_PATTERN + r"/@([\w_.-]+)"
19
20
21 class TiktokExtractor(Extractor):
22 """Base class for TikTok extractors"""
23 category = "tiktok"
24 directory_fmt = ("{category}", "{user}")
25 filename_fmt = (
26 "{id}{num:?_//>02} {title[b:150]}{file_id:? [/]/}.{extension}")
27 archive_fmt = "{id}_{num}_{file_id}"
28 root = "https://www.tiktok.com"
29 cookies_domain = ".tiktok.com"
30 rehydration_data_cache = {}
31 rehydration_data_app_context_cache = {}
32
33 def _init(self):
34 self.photo = self.config("photos", True)
35 self.audio = self.config("audio", True)
36 self.video = self.config("videos", True)
37 self.cover = self.config("covers", False)
38 self.subtitles = self.config("subtitles", False)
39
40 self.range = self.config("tiktok-range") or ""
41 self.range_predicate = util.predicate_range_parse(self.range)
42
43 # If one of these fields is None, the filter for it is disabled.
44 # Therefore, if both fields are none, all subtitles are extracted.
45 self.subtitle_sources = None
46 self.subtitle_langs = None
47
48 if self.subtitles and self.subtitles != "all":
49 if self.subtitles is True or not isinstance(self.subtitles, str):
50 self.subtitles = "ASR"
51
52 known_sources = {"ASR", "MT", "LC"}
53 filters = set(self.subtitles.split(","))
54 self.subtitle_sources = known_sources.intersection(filters) or None
55 self.subtitle_langs = filters.difference(known_sources) or None
56
57 def items(self):
58 for tiktok_url in self.posts():
59 try:
60 tiktok_url = self._sanitize_url(tiktok_url)
61
62 data = self._extract_rehydration_data(tiktok_url)
63 if "webapp.video-detail" not in data:
64 # Only /video/ links result in the video-detail dict we
65 # need. Try again using that form of link.
66 tiktok_url = self._sanitize_url(
67 data["seo.abtest"]["canonical"])
68 data = self._extract_rehydration_data(tiktok_url)
69 video_detail = data["webapp.video-detail"]
70 if not self._check_status_code(
71 video_detail, tiktok_url, "post"):
72 continue
73 post = video_detail["itemInfo"]["itemStruct"]
74
75 post["user"] = \
76 (a := post.get("author")) and a["uniqueId"] or ""
77 post["date"] = self.parse_timestamp(post["createTime"])
78 post["post_type"] = "image" if "imagePost" in post else "video"
79 original_title = title = post["desc"]
80
81 yield Message.Directory, "", post
82 ytdl_media = False
83
84 if "imagePost" in post:
85 if self.photo:
86 if not original_title:
87 title = f"TikTok photo #{post['id']}"
88 img_list = post["imagePost"]["images"]
89 for i, img in enumerate(img_list, 1):
90 url = img["imageURL"]["urlList"][0]
91 text.nameext_from_url(url, post)
92 post.update({
93 "type" : "image",
94 "image" : img,
95 "title" : title,
96 "num" : i,
97 "file_id": post["filename"].partition("~")[0],
98 "width" : img["imageWidth"],
99 "height" : img["imageHeight"],
100 })
101 yield Message.Url, url, post
102
103 if self.audio and "music" in post:
104 if self.audio == "ytdl":
105 ytdl_media = "audio"
106 elif url := self._extract_audio(post):
107 yield Message.Url, url, post
108
109 elif "video" in post:
110 if self.video == "ytdl":
111 ytdl_media = "video"
112 elif self.video and (url := self._extract_video(post)):
113 yield Message.Url, url, post
114 del post["_fallback"]
115
116 if self.cover:
117 for url in self._extract_covers(post, "video"):
118 yield Message.Url, url, post
119 if self.cover != "all":
120 break
121
122 if self.subtitles:
123 for url in self._extract_subtitles(post, "video"):
124 yield Message.Url, url, post
125
126 # remove the subtitle related fields for the next item
127 post.pop("subtitle_lang_id", None)
128 post.pop("subtitle_lang_codename", None)
129 post.pop("subtitle_format", None)
130 post.pop("subtitle_version", None)
131 post.pop("subtitle_source", None)
132 else:
133 self.log.info("%s: Skipping post", tiktok_url)
134
135 if ytdl_media:
136 if not original_title:
137 title = f"TikTok {ytdl_media} #{post['id']}"
138 post.update({
139 "type" : ytdl_media,
140 "image" : None,
141 "filename" : "",
142 "extension" :
143 "mp3" if ytdl_media == "audio" else "mp4",
144 "title" : title,
145 "num" : 0,
146 "file_id" : "",
147 "width" : 0,
148 "height" : 0,
149 })
150 yield Message.Url, "ytdl:" + tiktok_url, post
151 except Exception as exc:
152 self.log.traceback(exc)
153 self.log.error("%s: Failed to extract post (%s: %s)",
154 tiktok_url, exc.__class__.__name__, exc)
155
156 def _sanitize_url(self, url):
157 return text.ensure_http_scheme(url.replace("/photo/", "/video/", 1))
158
159 def _extract_rehydration_data(self, url, additional_keys=[], *,
160 has_keys=[]):
161 tries = 0
162 html = None
163 challenge_attempt = False
164 while True:
165 try:
166 response = self.request(url, headers=self._generate_headers())
167 if response.history and "/login" in response.url:
168 raise self.exc.AuthorizationError(
169 "HTTP redirect to login page "
170 f"('{response.url.partition('?')[0]}')")
171 html = response.text
172 data = text.extr(
173 html, '<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__" '
174 'type="application/json">', '</script>')
175 data = util.json_loads(data)["__DEFAULT_SCOPE__"]
176 for key in additional_keys:
177 data = data[key]
178 for assert_key in has_keys:
179 if assert_key not in data:
180 raise KeyError(assert_key)
181 return data
182 except (ValueError, KeyError):
183 # Even if the retries option has been set to 0, we should
184 # always at least try to solve the JS challenge and go again
185 # immediately.
186 if not challenge_attempt:
187 challenge_attempt = True
188 self.log.info("Solving JavaScript challenge")
189 try:
190 self._solve_challenge(html)
191 html = None
192 continue
193 except Exception as exc:
194 self.log.traceback(exc)
195 self.log.warning(
196 "%s: Failed to solve JavaScript challenge. If you "
197 "keep encountering this issue, please try again "
198 "with the --write-pages option and include the "
199 "resulting page in your bug report",
200 url.rpartition("/")[2])
201
202 # We've already tried resolving the challenge, and either
203 # resolving it failed, or resolving it didn't get us the
204 # rehydration data, so fail this attempt.
205 self.log.warning("%s: Failed to retrieve rehydration data "
206 "(%s/%s)", url.rpartition("/")[2], tries + 1,
207 self._retries)
208 if tries >= self._retries:
209 raise
210 tries += 1
211 self.sleep(self._timeout, "retry")
212 challenge_attempt = False
213 html = None
214
215 def _extract_rehydration_data_user(self, profile_url, additional_keys=()):
216 if profile_url in self.rehydration_data_cache:
217 data = self.rehydration_data_cache[profile_url]
218 else:
219 data = self._extract_rehydration_data(
220 profile_url,
221 has_keys=["webapp.user-detail", "webapp.app-context"]
222 )
223 self.rehydration_data_cache[profile_url] = \
224 data["webapp.user-detail"]
225 self.rehydration_data_app_context_cache = \
226 data["webapp.app-context"]
227 data = data["webapp.user-detail"]
228 if not self._check_status_code(data, profile_url, "profile"):
229 raise self.exc.ExtractionError(
230 f"{profile_url}: could not extract rehydration data")
231 try:
232 for key in additional_keys:
233 data = data[key]
234 except KeyError as exc:
235 self.log.traceback(exc)
236 raise self.exc.ExtractionError(
237 "%s: could not extract rehydration data (%s)",
238 profile_url, ", ".join(additional_keys))
239 return data
240
241 def _ensure_rehydration_data_app_context_cache_is_populated(self):
242 if not self.rehydration_data_app_context_cache:
243 self.rehydration_data_app_context_cache = \
244 self._extract_rehydration_data(
245 "https://www.tiktok.com/", ["webapp.app-context"])
246
247 def _solve_challenge(self, html):
248 cs = text.extr(text.extr(html, 'id="cs"', '>'), 'class="', '"')
249 c = util.json_loads(util.b64decode(cs + "=="))
250
251 # find index of expected digest
252 expected = util.b64rdecode(c["v"]["c"] + "==")
253 base = hashlib.sha256(util.b64rdecode(c["v"]["a"] + "=="))
254 for idx in range(1_000_000):
255 test = base.copy()
256 test.update(str(idx).encode())
257 if test.digest() == expected:
258 break
259 else:
260 raise self.exc.ExtractionError("failed to find matching digest")
261
262 # extract cookie names
263 wci = text.extr(text.extr(html, 'id="wci"', '>'), 'class="', '"')
264 rci = text.extr(text.extr(html, 'id="rci"', '>'), 'class="', '"')
265 rs = text.extr(text.extr(html, 'id="rs"', '>'), 'class="', '"')
266
267 # set cookie values
268 domain = self.cookies_domain
269 expires = int(time.time()) + 5
270 c["d"] = util.b64encode(str(idx).encode())
271 v = util.b64encode(util.json_dumps(c).encode())
272 self.cookies.set(wci, v, domain=domain, expires=expires)
273 if rs:
274 self.cookies.set(rci, rs, domain=domain, expires=expires)
275
276 def _extract_sec_uid(self, profile_url, user_name):
277 sec_uid = self._extract_id(
278 profile_url, user_name, r"MS4wLjABAAAA[\w-]{32,64}", "secUid")
279 if sec_uid is None:
280 raise self.exc.AbortExtraction(
281 f"{user_name}: unable to extract secondary user ID")
282 return sec_uid
283
284 def _extract_author_id(self, profile_url, user_name):
285 author_id = self._extract_id(
286 profile_url, user_name, r"[0-9]+", "id")
287 if author_id is None:
288 raise self.exc.AbortExtraction(
289 f"{user_name}: unable to extract user ID")
290 return author_id
291
292 def _extract_id(self, profile_url, user_name, regex, id_key):
293 match = text.re(regex).fullmatch
294
295 if match(user_name) is not None:
296 # If it was provided in the URL, then we can skip extracting it
297 # from the rehydration data.
298 return user_name
299
300 id = self._extract_rehydration_data_user(
301 profile_url, ("userInfo", "user", id_key))
302 return None if match(id) is None else id
303
304 def _extract_video(self, post):
305 video = post["video"]
306 urls = self._extract_video_urls(video)
307 if not urls:
308 raise self.exc.ExtractionError(
309 f"{post['id']}: Failed to extract video URLs. "
310 f"You may need cookies to continue.")
311
312 url = urls[0]
313 text.nameext_from_url(url, post)
314 post.update({
315 "_fallback": urls[1:],
316 "type" : "video",
317 "image" : None,
318 "title" : post["desc"] or f"TikTok video #{post['id']}",
319 "duration" : video.get("duration"),
320 "num" : 0,
321 "file_id" : "",
322 "width" : video.get("width"),
323 "height" : video.get("height"),
324 })
325 if not post["extension"]:
326 post["extension"] = video.get("format", "mp4")
327 return url
328
329 def _extract_video_urls(self, video):
330 # First, look for bitrateInfo.
331 # This will include URLs pointing to the best quality videos.
332 if "bitrateInfo" in video:
333 bitrate_info = video["bitrateInfo"]
334 if not isinstance(bitrate_info, list):
335 bitrate_info = [bitrate_info]
336 bitrate_urls = {}
337 for video_info in bitrate_info:
338 play_addr = video_info["PlayAddr"]
339 width = text.parse_int(play_addr.get("Width"))
340 height = text.parse_int(play_addr.get("Height"))
341 size = width * height
342 if size in bitrate_urls:
343 bitrate_urls[size] += play_addr.get("UrlList")
344 else:
345 bitrate_urls[size] = play_addr.get("UrlList").copy()
346 # Sort the URLs by descending quality.
347 sizes = list(bitrate_urls)
348 sizes.sort(reverse=True)
349 urls = [url for size in sizes for url in bitrate_urls[size]]
350 else:
351 urls = []
352
353 # As a fallback, try to look for the root playAddr,
354 # which won't necessarily point to the best quality.
355 if "playAddr" in video:
356 urls.append(video["playAddr"])
357
358 return urls
359
360 def _extract_audio(self, post):
361 audio = post["music"]
362 url = audio["playUrl"]
363 text.nameext_from_url(url, post)
364 post.update({
365 "type" : "audio",
366 "image" : None,
367 "title" : post["desc"] or f"TikTok audio #{post['id']}",
368 "duration" : audio.get("duration"),
369 "num" : 0,
370 "file_id" : audio.get("id"),
371 "width" : 0,
372 "height" : 0,
373 })
374 if not post["extension"]:
375 post["extension"] = "mp3"
376 return url
377
378 def _extract_covers(self, post, type):
379 media = post[type]
380
381 for cover_id in ("thumbnail", "cover", "originCover", "dynamicCover"):
382 if url := media.get(cover_id):
383 text.nameext_from_url(url, post)
384 post.update({
385 "type" : "cover",
386 "extension": "jpg",
387 "image" : url,
388 "title" : post["desc"] or
389 f"TikTok {type} cover #{post['id']}",
390 "duration" : media.get("duration"),
391 "num" : 0,
392 "file_id" : cover_id,
393 "width" : 0,
394 "height" : 0,
395 })
396 yield url
397
398 def _extract_subtitles(self, post, type):
399 media = post[type]
400 sources_filtered = self.subtitle_sources is not None
401 langs_filtered = self.subtitle_langs is not None
402
403 for subtitle in media.get("subtitleInfos", ()):
404 sub_lang_id = subtitle.get("LanguageID")
405 sub_lang_codename = subtitle.get("LanguageCodeName")
406 sub_format = subtitle.get("Format")
407 sub_version = subtitle.get("Version")
408 sub_source = subtitle.get("Source")
409
410 # guard the iterable access
411 sources_match = sources_filtered and \
412 sub_source in self.subtitle_sources
413 langs_match = langs_filtered and \
414 sub_lang_codename in self.subtitle_langs
415
416 # Subtitles will be extracted when either filter matches.
417 if not sources_match and not langs_match and \
418 (sources_filtered or langs_filtered):
419 continue
420
421 if url := subtitle.get("Url"):
422 text.nameext_from_url(url, post)
423
424 # subtitle urls may not specify a filename,
425 # so the metadata can be used to build one.
426 if not post["filename"]:
427 post["filename"] = (f"{post['id']}_{sub_lang_codename}_"
428 f"{sub_version}_{sub_source}")
429 post["extension"] = sub_format.lower()
430
431 # replace extensions for known formats
432 if post["extension"] == "webvtt":
433 post["extension"] = "vtt"
434 elif post["extension"] == "creator_caption":
435 post["extension"] = "json"
436
437 post.update({
438 "type" : "subtitle",
439 "image" : None,
440 "title" :
441 post["desc"] or
442 f"TikTok {type} subtitle #{post['id']}",
443 "duration" : media.get("duration"),
444 "num" : 0,
445 "file_id" :
446 f"{sub_lang_id}_{sub_lang_codename}_{sub_source}_"
447 f"{sub_version}_{sub_format}",
448 "subtitle_lang_id" : sub_lang_id,
449 "subtitle_lang_codename": sub_lang_codename,
450 "subtitle_format" : sub_format,
451 "subtitle_version" : sub_version,
452 "subtitle_source" : sub_source,
453 "width" : 0,
454 "height" : 0,
455 })
456 yield url
457
458 def _check_status_code(self, detail, url, type_of_url):
459 status = detail.get("statusCode")
460 if not status:
461 return True
462
463 if status == 10222:
464 # Video count workaround ported from yt-dlp: sometimes TikTok
465 # reports a profile as private even though we have the cookies to
466 # access it. We know that we can access it if we can see the
467 # videos stats. If we can't, we assume that we don't have access
468 # to the profile.
469 # We only care about this workaround for webapp.user-detail
470 # objects, so always fail the workaround for e.g.
471 # webapp.video-detail objects.
472 video_count = self._extract_video_count_from_user_detail(detail)
473 if video_count is None:
474 self.log.error("%s: Login required to access this %s", url,
475 type_of_url)
476 elif video_count > 0:
477 return True
478 else:
479 self.log.error("%s: Login required to access this %s, or this "
480 "profile has no videos posted", url,
481 type_of_url)
482 elif status == 10221:
483 self.log.error("%s: User account could not be found", url)
484 elif status == 10204:
485 self.log.error("%s: Requested %s not available", url, type_of_url)
486 elif status == 10231:
487 self.log.error("%s: Region locked - Try downloading with a "
488 "VPN/proxy connection", url)
489 else:
490 self.log.error(
491 "%s: Received unknown error code %s ('%s')",
492 url, status, detail.get("statusMsg") or "")
493 return False
494
495 def _extract_video_count_from_user_detail(self, detail):
496 user_info = detail.get("userInfo")
497 if not user_info:
498 return None
499 stats = user_info.get("stats") or user_info.get("statsV2")
500 try:
501 # stats.videoCount is an int, but statsV2.videoCount is a
502 # string, so we must explicitly convert the attribute.
503 return int(stats["videoCount"])
504 except (KeyError, ValueError):
505 return None
506
507 def _generate_headers(self, min_headers=3, max_headers=8):
508 """Randomize HTTP header fingerprint
509 in an attempt to avoid HTTP Error 403 blockage"""
510 def randletters(min, max):
511 return "".join(random.choices(
512 "bcdfghjklmnpqrstvwxz", k=random.randint(min, max)))
513 return {
514 randletters(8, 24): randletters(16, 32)
515 for _ in range(random.randint(min_headers, max_headers))
516 }
517
518
519 class TiktokPostExtractor(TiktokExtractor):
520 """Extract a single video or photo TikTok link"""
521 subcategory = "post"
522 pattern = BASE_PATTERN + r"/(?:@([\w_.-]*)|share)/(?:phot|vide)o/(\d+)"
523 example = "https://www.tiktok.com/@USER/photo/1234567890"
524
525 def posts(self):
526 user, post_id = self.groups
527 url = f"{self.root}/@{user or ''}/video/{post_id}"
528 return {url: None}
529
530
531 class TiktokVmpostExtractor(TiktokExtractor):
532 """Extract a single video or photo TikTok VM link"""
533 subcategory = "vmpost"
534 pattern = (r"(?:https?://)?(?:"
535 r"(?:v[mt]\.)?tiktok\.com|(?:www\.)?tiktok\.com/t"
536 r")/(?!@)([^/?#]+)")
537 example = "https://vm.tiktok.com/1a2B3c4E5"
538
539 def items(self):
540 url = text.ensure_http_scheme(self.url)
541 headers = {"User-Agent": "facebookexternalhit/1.1"}
542
543 url = self.request_location(url, headers=headers, notfound="post")
544 if not url or len(url) <= 28:
545 # https://www.tiktok.com/?_r=1
546 raise self.exc.NotFoundError("post")
547
548 data = {"_extractor": TiktokPostExtractor}
549 yield Message.Queue, url.partition("?")[0], data
550
551
552 class TiktokUserExtractor(Dispatch, TiktokExtractor):
553 """Extractor for a TikTok user profile"""
554 pattern = USER_PATTERN + r"/?(?:$|\?|#)"
555 example = "https://www.tiktok.com/@USER"
556
557 def items(self):
558 base = f"{self.root}/@{self.groups[0]}/"
559 return self._dispatch_extractors((
560 (TiktokAvatarExtractor , base + "avatar"),
561 (TiktokPostsExtractor , base + "posts"),
562 (TiktokRepostsExtractor, base + "reposts"),
563 (TiktokStoriesExtractor, base + "stories"),
564 (TiktokLikesExtractor , base + "likes"),
565 (TiktokSavedExtractor , base + "saved"),
566 ), ("avatar", "posts"))
567
568
569 class TiktokAvatarExtractor(TiktokExtractor):
570 subcategory = "avatar"
571 pattern = USER_PATTERN + r"/avatar"
572 example = "https://www.tiktok.com/@USER/avatar"
573
574 def items(self):
575 user_name = self.groups[0]
576 profile_url = f"{self.root}/@{user_name}"
577
578 data = self._extract_rehydration_data_user(
579 profile_url, ("userInfo", "user"))
580 data["user"] = data.get("uniqueId", user_name)
581 avatar_url = data.get("avatarLarger") or data.get("avatarMedium") \
582 or data["avatarThumb"]
583 avatar = text.nameext_from_url(avatar_url, data.copy())
584 avatar.update({
585 "type" : "avatar",
586 "title" : "@" + data["user"],
587 "id" : data["id"],
588 "file_id": avatar["filename"].partition("~")[0],
589 "num" : 0,
590 })
591
592 yield Message.Directory, "", avatar
593 yield Message.Url, avatar_url, avatar
594
595
596 class TiktokPostsExtractor(TiktokExtractor):
597 subcategory = "posts"
598 pattern = USER_PATTERN + r"/posts"
599 example = "https://www.tiktok.com/@USER/posts"
600
601 def posts(self):
602 user_name = self.groups[0]
603 profile_url = f"{self.root}/@{user_name}"
604 self.user_provided_cookies = bool(self.cookies)
605
606 # If set to "ytdl", we shall first go via yt-dlp. If that fails,
607 # we shall attempt to extract directly.
608 if self.config("ytdl", False):
609 if posts := self._extract_posts_ytdl(profile_url):
610 return posts
611 ytdl = True
612 self.log.warning("Could not extract TikTok user "
613 f"{user_name} via yt-dlp or youtube-dl, "
614 "attempting the extraction directly")
615 else:
616 ytdl = False
617
618 if posts := self._extract_posts_api(profile_url, user_name):
619 return posts
620
621 message = "Could not extract any posts from TikTok user " \
622 f"{user_name}"
623 if not ytdl:
624 message += ", try extracting post information using " \
625 "yt-dlp with the -o ytdl=true argument"
626 self.log.warning(message)
627 return ()
628
629 def _extract_posts_ytdl(self, profile_url):
630 try:
631 module = ytdl.import_module(self.config("module"))
632 except (ImportError, SyntaxError) as exc:
633 self.log.error("Cannot import module '%s'",
634 getattr(exc, "name", ""))
635 self.log.traceback(exc)
636 return []
637
638 extr_opts = {
639 "extract_flat" : True,
640 "ignore_no_formats_error": True,
641 }
642 user_opts = {
643 "retries" : self._retries,
644 "socket_timeout" : self._timeout,
645 "nocheckcertificate" : not self._verify,
646 "playlist_items" : str(self.range),
647 }
648 if self._proxies:
649 user_opts["proxy"] = self._proxies.get("http")
650
651 ytdl_instance = ytdl.construct_YoutubeDL(
652 module, self, user_opts, extr_opts)
653
654 # Transfer cookies to ytdl.
655 if self.cookies:
656 set_cookie = ytdl_instance.cookiejar.set_cookie
657 for cookie in self.cookies:
658 set_cookie(cookie)
659
660 with ytdl_instance as ydl:
661 info_dict = ydl._YoutubeDL__extract_info(
662 profile_url, ydl.get_info_extractor("TikTokUser"),
663 False, {}, True)
664 # This should be a list of video and photo post URLs in /video/
665 # format.
666 return [video["url"].partition("?")[0]
667 for video in info_dict["entries"]]
668
669 def _extract_posts_api(self, profile_url, user_name):
670 self.post_order = self.config("order-posts") or "desc"
671 if self.post_order not in ["desc", "asc", "reverse", "popular"]:
672 self.post_order = "desc"
673 sec_uid = self._extract_sec_uid(profile_url, user_name)
674
675 # If descending order is requested, opt for the more reliable legacy
676 # endpoint instead of trying with the "newer", flakier endpoint.
677 if self.post_order == "desc":
678 return self._extract_posts_api_legacy(
679 profile_url, sec_uid, self.range_predicate)
680
681 if not self.user_provided_cookies:
682 self.log.warning(
683 "%s: no cookies have been provided so the order-posts "
684 "option will not take effect. You must provide cookies in "
685 "order to extract a profile's posts in non-descending "
686 "order",
687 profile_url
688 )
689 return self._extract_posts_api_legacy(
690 profile_url, sec_uid, self.range_predicate)
691
692 try:
693 urls = self._extract_posts_api_order(
694 profile_url, sec_uid, self.range_predicate)
695 if urls:
696 return urls
697 except Exception as exc:
698 self.log.traceback(exc)
699
700 self.log.error(
701 "%s: failed to extract user posts using post/item_list (make sure "
702 "you provide valid cookies). Attempting with legacy "
703 "creator/item_list endpoint that does not support post ordering",
704 profile_url
705 )
706 return self._extract_posts_api_legacy(
707 profile_url, sec_uid, self.range_predicate)
708
709 def _extract_posts_api_order(self, profile_url, sec_uid, range_predicate):
710 post_item_list_request_type = "0"
711 if self.post_order in ["asc", "reverse"]:
712 post_item_list_request_type = "2"
713 elif self.post_order in ["popular"]:
714 post_item_list_request_type = "1"
715 query_parameters = {
716 "secUid": sec_uid,
717 "post_item_list_request_type": post_item_list_request_type,
718 "count": "15",
719 "needPinnedItemIds": "false",
720 }
721 request = TiktokPostItemListRequest(range_predicate)
722 if not request.execute(self, profile_url, query_parameters):
723 return []
724 return request.generate_urls(profile_url, self.video, self.photo,
725 self.audio)
726
727 def _extract_posts_api_legacy(self, profile_url, sec_uid, range_predicate):
728 query_parameters = {
729 "secUid": sec_uid,
730 "type": "1",
731 "count": "15",
732 }
733 request = TiktokCreatorItemListRequest(range_predicate)
734 request.execute(self, profile_url, query_parameters)
735 return request.generate_urls(profile_url, self.video, self.photo,
736 self.audio)
737
738
739 class TiktokRepostsExtractor(TiktokExtractor):
740 subcategory = "reposts"
741 pattern = USER_PATTERN + r"/reposts"
742 example = "https://www.tiktok.com/@USER/reposts"
743
744 def posts(self):
745 user_name = self.groups[0]
746 profile_url = f"{self.root}/@{user_name}"
747
748 query_parameters = {
749 "secUid": self._extract_sec_uid(profile_url, user_name),
750 "post_item_list_request_type": "0",
751 "needPinnedItemIds": "false",
752 "count": "15",
753 }
754 request = TiktokRepostItemListRequest(self.range_predicate)
755 request.execute(self, profile_url, query_parameters)
756 return request.generate_urls(profile_url, self.video, self.photo,
757 self.audio)
758
759
760 class TiktokStoriesExtractor(TiktokExtractor):
761 subcategory = "stories"
762 pattern = USER_PATTERN + r"/stories"
763 example = "https://www.tiktok.com/@USER/stories"
764
765 def posts(self):
766 user_name = self.groups[0]
767 profile_url = f"{self.root}/@{user_name}"
768
769 query_parameters = {
770 "authorId": self._extract_author_id(profile_url, user_name),
771 "loadBackward": "false",
772 "count": "5",
773 }
774 request = TiktokStoryItemListRequest()
775 request.execute(self, profile_url, query_parameters)
776 return request.generate_urls(profile_url, self.video, self.photo,
777 self.audio)
778
779
780 class TiktokLikesExtractor(TiktokExtractor):
781 subcategory = "likes"
782 pattern = USER_PATTERN + r"/like[sd]"
783 example = "https://www.tiktok.com/@USER/liked"
784
785 def posts(self):
786 user_name = self.groups[0]
787 profile_url = f"{self.root}/@{user_name}"
788
789 query_parameters = {
790 "secUid": self._extract_sec_uid(profile_url, user_name),
791 "post_item_list_request_type": "0",
792 "needPinnedItemIds": "false",
793 "count": "15",
794 }
795 request = TiktokFavoriteItemListRequest(self.range_predicate)
796 request.execute(self, profile_url, query_parameters)
797 return request.generate_urls(profile_url, self.video, self.photo,
798 self.audio)
799
800
801 class TiktokSavedExtractor(TiktokExtractor):
802 subcategory = "saved"
803 pattern = USER_PATTERN + r"/saved"
804 example = "https://www.tiktok.com/@USER/saved"
805
806 def posts(self):
807 user_name = self.groups[0]
808 profile_url = f"{self.root}/@{user_name}"
809
810 query_parameters = {
811 "secUid": self._extract_sec_uid(profile_url, user_name),
812 "post_item_list_request_type": "0",
813 "needPinnedItemIds": "false",
814 "count": "15",
815 }
816 request = TiktokSavedPostItemListRequest(self.range_predicate)
817 request.execute(self, profile_url, query_parameters)
818 return request.generate_urls(profile_url, self.video, self.photo,
819 self.audio)
820
821
822 class TiktokFollowingExtractor(TiktokExtractor):
823 """Extract all of the stories of all of the users you follow"""
824 subcategory = "following"
825 pattern = rf"{BASE_PATTERN}/following"
826 example = "https://www.tiktok.com/following"
827
828 def posts(self):
829 """Attempt to extract all of the stories of all of the accounts
830 the user follows"""
831
832 query_parameters = {
833 "storyFeedScene": "3",
834 "count": "15",
835 }
836 request = TiktokStoryUserListRequest()
837 if not request.execute(self, self.url, query_parameters):
838 self.log.error("%s: could not extract follower list, make sure "
839 "you are using logged-in cookies", self.url)
840 users = request.generate_urls()
841 if len(users) == 0:
842 self.log.warning("%s: No followers with stories could be "
843 "extracted", self.url)
844
845 entries = {}
846 # Batch all of the users up into groups of at most ten and use the
847 # batch endpoint to improve performance. The response to the story user
848 # list request may also include the user themselves, so skip them if
849 # they ever turn up.
850 for b in range((len(users) - 1) // 10 + 1):
851 batch_number = b + 1
852 user_batch = users[b*10:batch_number*10]
853
854 # Handle edge case where final batch is composed of a single user
855 # and that user is the one we need to skip. If we don't handle this
856 # here (or when we generate the author ID list later), we will
857 # trigger an AssertionError for an empty author ID list.
858 if len(user_batch) == 1:
859 if self._is_current_user(user_batch[0][0]):
860 continue
861
862 self.log.info("TikTok user stories, batch %d: %s", batch_number,
863 ", ".join([profile_url for user_id, profile_url in
864 user_batch if not self._is_current_user(
865 user_id)]))
866
867 # Since we've already extracted all of the author IDs, we should be
868 # able to avoid having to request rehydration data (except for one
869 # time, since it's required to make _is_current_user() work), but
870 # we should keep this mechanism in place for safety.
871 author_ids = [self._extract_author_id(profile_url, user_id)
872 for user_id, profile_url in user_batch
873 if not self._is_current_user(user_id)]
874 query_parameters = {
875 "authorIds": ",".join(author_ids),
876 "storyCallScene": "2",
877 }
878 request = TiktokStoryBatchItemListRequest()
879 request.execute(self, f"Batch {batch_number}", query_parameters)
880 # We technically don't need to have the correct user name in the
881 # URL and it's easier to just ignore it here.
882 entries.update(request.generate_urls("https://www.tiktok.com/@_",
883 self.video, self.photo,
884 self.audio))
885
886 return entries
887
888 def _is_current_user(self, user_id):
889 self._ensure_rehydration_data_app_context_cache_is_populated()
890 if "user" not in self.rehydration_data_app_context_cache:
891 return False
892 if "uid" not in self.rehydration_data_app_context_cache["user"]:
893 return False
894 return self.rehydration_data_app_context_cache["user"]["uid"] == \
895 user_id
896
897
898 class TiktokPaginationCursor:
899 def current_page(self):
900 """Must return the page the cursor is currently pointing to.
901
902 Returns
903 -------
904 int
905 The current value of the cursor.
906 """
907
908 return 0
909
910 def next_page(self, data, query_parameters):
911 """Must progress the cursor to the next page.
912
913 Parameters
914 ----------
915 data : dict
916 The response of the most recent request.
917 query_parameters : dict
918 All of the query parameters used for the most recent
919 request.
920
921 Returns
922 -------
923 bool
924 True if the cursor detects that we've reached the end, False
925 otherwise.
926 """
927
928 return True
929
930
931 class TiktokTimeCursor(TiktokPaginationCursor):
932 def __init__(self, *, reverse=True, has_more_attribute="hasMore",
933 cursor_attribute="cursor"):
934 super().__init__()
935 self.cursor = 0
936 # If we expect the cursor to go up or down as we go to the next page.
937 # True for down, False for up.
938 self.reverse = reverse
939 self.has_more_key = has_more_attribute
940 self.cursor_key = cursor_attribute
941
942 def current_page(self):
943 return self.cursor
944
945 def next_page(self, data, query_parameters):
946 skip_fallback_logic = self.cursor == 0
947 new_cursor = int(data.get(self.cursor_key, 0))
948 no_cursor = not new_cursor
949 if not skip_fallback_logic:
950 # If the new cursor doesn't go in the direction we expect, use the
951 # fallback logic instead.
952 if self.reverse and (new_cursor > self.cursor or no_cursor):
953 new_cursor = self.fallback_cursor(data)
954 elif not self.reverse and (new_cursor < self.cursor or no_cursor):
955 new_cursor = self.fallback_cursor(data)
956 elif no_cursor:
957 raise self.exc.ExtractionError("Could not extract next cursor")
958 self.cursor = new_cursor
959 return not data.get(self.has_more_key, False)
960
961 def fallback_cursor(self, data):
962 try:
963 return int(data["itemList"][-1]["createTime"]) * 1000
964 except Exception:
965 return 7 * 86_400_000 * (-1 if self.reverse else 1)
966
967
968 class TiktokForwardTimeCursor(TiktokTimeCursor):
969 def __init__(self):
970 super().__init__(reverse=False)
971
972
973 class TiktokBackwardTimeCursor(TiktokTimeCursor):
974 def __init__(self):
975 super().__init__(reverse=True)
976
977
978 class TiktokPopularTimeCursor(TiktokTimeCursor):
979 def __init__(self):
980 super().__init__(reverse=True)
981
982 def fallback_cursor(self, data):
983 # Don't really know what to do here, all I know is that the cursor
984 # for the popular item feed goes down and it does not appear to be
985 # based on item list timestamps at all.
986 return -50_000
987
988
989 class TiktokStoryTimeCursor(TiktokTimeCursor):
990 def __init__(self):
991 super().__init__(reverse=False, has_more_attribute="HasMoreAfter",
992 cursor_attribute="MaxCursor")
993
994
995 class TiktokLegacyTimeCursor(TiktokPaginationCursor):
996 def __init__(self):
997 super().__init__()
998 self.cursor = int(time.time()) * 1000
999
1000 def current_page(self):
1001 return self.cursor
1002
1003 def next_page(self, data, query_parameters):
1004 old_cursor = self.cursor
1005 try:
1006 self.cursor = int(data["itemList"][-1]["createTime"]) * 1000
1007 except Exception:
1008 self.cursor = 0
1009 if not self.cursor or old_cursor == self.cursor:
1010 # User may not have posted within this ~1 week look back,
1011 # so manually adjust the cursor.
1012 self.cursor = old_cursor - 7 * 86_400_000
1013 # In case 'hasMorePrevious' is wrong, break if we have
1014 # gone back before TikTok existed.
1015 has_more_previous = data.get("hasMorePrevious")
1016 return self.cursor < 1472706000000 or not has_more_previous
1017
1018
1019 class TiktokItemCursor(TiktokPaginationCursor):
1020 def __init__(self, list_key: str = "itemList"):
1021 super().__init__()
1022 self.cursor = 0
1023 self.list_key = list_key
1024
1025 def current_page(self):
1026 return self.cursor
1027
1028 def next_page(self, data, query_parameters):
1029 # We should offset the cursor by the number of items in the response.
1030 # Sometimes less items are returned than what was requested in the
1031 # count parameter! We could fall back onto the count query parameter
1032 # but we could miss out on some posts.
1033 self.cursor += len(data.get(self.list_key, ()))
1034 if "hasMore" in data:
1035 return not data["hasMore"]
1036 return not data.get("HasMoreAfter", False)
1037
1038
1039 class TiktokPaginationRequest:
1040 def __init__(self, endpoint):
1041 self.endpoint = endpoint
1042 self._regenerate_device_id()
1043 self.items = {}
1044
1045 def execute(self, extractor, url, query_parameters):
1046 """Performs requests until all pages have been retrieved.
1047
1048 The items retrieved from this request are stored in self.items.
1049 Each call to execute() will clear the previous value of
1050 self.items.
1051
1052 Usually extractors want a simple list of URLs. For this, each
1053 request subtype is to implement generate_urls().
1054
1055 Parameters
1056 ----------
1057 extractor : TiktokExtractor
1058 The TikTok extractor performing the request.
1059 url : str
1060 The URL associated with this request for logging purposes.
1061 query_parameters : dict[str, str]
1062 The query parameters to apply to this request.
1063
1064 Returns
1065 -------
1066 bool
1067 True if the request was performed successfully and all items
1068 were retrieved, False if no items or only some items could
1069 be retrieved.
1070 """
1071
1072 self.validate_query_parameters(query_parameters)
1073 self.items = {}
1074 cursor_type = self.cursor_type(query_parameters)
1075 cursor = cursor_type() if cursor_type else None
1076 for page in itertools.count(start=1):
1077 item_count = len(self.items)
1078 extractor.log.info("%s: retrieving %s page %d (%d item%s)", url,
1079 self.endpoint, page, item_count,
1080 "" if item_count == 1 else "s")
1081 tries = 0
1082 while True:
1083 try:
1084 data, final_parameters = self._request_data(
1085 extractor,
1086 cursor,
1087 query_parameters
1088 )
1089 incoming_items = self.extract_items(data)
1090 self._detect_duplicate_pages(extractor, url,
1091 set(self.items.keys()),
1092 set(incoming_items.keys()))
1093 self.items.update(incoming_items)
1094 if cursor:
1095 final_page_reached = cursor.next_page(data,
1096 final_parameters)
1097 exit_early = self.exit_early(extractor, url)
1098 if exit_early or final_page_reached:
1099 return True
1100 # Continue to next page and reset tries counter.
1101 break
1102 else:
1103 # This request has no cursor: return immediately.
1104 return True
1105 except Exception as exc:
1106 if tries >= extractor._retries:
1107 extractor.log.error("%s: failed to retrieve %s page "
1108 "%d", url, self.endpoint, page)
1109 extractor.log.traceback(exc)
1110 return False
1111 tries += 1
1112 extractor.log.warning("%s: failed to retrieve %s page %d",
1113 url, self.endpoint, page)
1114 extractor.sleep(extractor._timeout, "retry")
1115
1116 def validate_query_parameters(self, query_parameters):
1117 """Used to validate the given parameters for this type of
1118 pagination request.
1119
1120 For developer purposes only. You should call
1121 super().validate_query_parameters() for most requests as they
1122 will usually have a count parameter.
1123
1124 Parameters
1125 ----------
1126 query_parameters : dict[str, str]
1127 The query parameters to validate.
1128
1129 Raises
1130 -------
1131 AssertionError
1132 If mandatory query parameters are not given, or they are
1133 given in the wrong format.
1134 """
1135
1136 assert "count" in query_parameters
1137 assert type(query_parameters["count"]) is str
1138 assert query_parameters["count"].isdigit()
1139 assert query_parameters["count"] != "0"
1140
1141 def cursor_type(self, query_parameters):
1142 """Used to determine which type of cursor to use for this
1143 request, if any.
1144
1145 Parameters
1146 ----------
1147 query_parameters : dict[str, str]
1148 The query parameters given to the execute() call.
1149
1150 Returns
1151 -------
1152 Type[TiktokPaginationCursor] | None
1153 The type of cursor to use, if any.
1154 """
1155
1156 return None
1157
1158 def extract_items(self, data):
1159 """Used to extract data from the response of a request.
1160
1161 Parameters
1162 ----------
1163 data : dict
1164 The data given by TikTok.
1165
1166 Returns
1167 -------
1168 dict
1169 Each item from the response data, keyed on a unique ID.
1170
1171 Raises
1172 ------
1173 Exception
1174 If items could not be extracted.
1175 """
1176
1177 return {}
1178
1179 def exit_early(self, extractor, url):
1180 """Used to determine if we should exit early from the request.
1181
1182 You have access to the items extracted so far (self.items).
1183
1184 Parameters
1185 ----------
1186 extractor : TiktokExtractor
1187 The extractor making the requests.
1188 url : str
1189 The URL associated with the executing request for logging
1190 purposes.
1191
1192 Returns
1193 -------
1194 bool
1195 True if we should exit early, False otherwise.
1196 """
1197
1198 return False
1199
1200 def generate_urls(self):
1201 """Used to convert the items retrieved from the request into a
1202 list of URLs.
1203
1204 Returns
1205 -------
1206 dict
1207 Ideally one URL for each item, that points to a video detail
1208 object, although subclasses are permitted to return a list
1209 or dict of any format they wish.
1210 """
1211
1212 return []
1213
1214 def _regenerate_device_id(self):
1215 self.device_id = str(random.randint(
1216 7_250_000_000_000_000_000, 7_325_099_899_999_994_577))
1217
1218 def _request_data(self, extractor, cursor, query_parameters):
1219 # Implement simple 1 retry mechanism without delays that handles the
1220 # flaky post/item_list endpoint.
1221 retries = 0
1222 while True:
1223 try:
1224 url, final_parameters = self._build_api_request_url(
1225 cursor,
1226 query_parameters
1227 )
1228 response = extractor.request(
1229 url, headers=self._generate_headers())
1230 return (util.json_loads(response.text), final_parameters)
1231 except ValueError:
1232 if retries == 1:
1233 raise
1234 extractor.log.warning(
1235 "Could not decode response for this page, trying again"
1236 )
1237 retries += 1
1238
1239 def _build_api_request_url(self, cursor, extra_parameters):
1240 query_parameters = {
1241 "aid": "1988",
1242 "app_language": "en",
1243 "app_name": "tiktok_web",
1244 "browser_language": "en-US",
1245 "browser_name": "Mozilla",
1246 "browser_online": "true",
1247 "browser_platform": "Win32",
1248 "browser_version": "5.0 (Windows)",
1249 "channel": "tiktok_web",
1250 "cookie_enabled": "true",
1251 "device_id": self.device_id,
1252 "device_platform": "web_pc",
1253 "focus_state": "true",
1254 "from_page": "user",
1255 "history_len": "2",
1256 "is_fullscreen": "false",
1257 "is_page_visible": "true",
1258 "language": "en",
1259 "os": "windows",
1260 "priority_region": "",
1261 "referer": "",
1262 "region": "US",
1263 "screen_height": "1080",
1264 "screen_width": "1920",
1265 "tz_name": "UTC",
1266 "verifyFp": "verify_" + "".join(random.choices(
1267 "0123456789abcdef", k=7)),
1268 "webcast_language": "en",
1269 }
1270 if cursor:
1271 # We must not write this as a floating-point number:
1272 query_parameters["cursor"] = str(int(cursor.current_page()))
1273 for key, value in extra_parameters.items():
1274 query_parameters[key] = f"{value}"
1275 query_str = text.build_query(query_parameters)
1276 return (f"https://www.tiktok.com/api/{self.endpoint}/?{query_str}",
1277 query_parameters)
1278
1279 def _detect_duplicate_pages(self, extractor, url, seen_ids, incoming_ids):
1280 if incoming_ids and incoming_ids == seen_ids:
1281 # TikTok API keeps sending the same page, likely due to
1282 # a bad device ID. Generate a new one and try again.
1283 self._regenerate_device_id()
1284 extractor.log.warning("%s: TikTok API keeps sending the same "
1285 "page. Taking measures to avoid an infinite "
1286 "loop", url)
1287 raise self.exc.ExtractionError(
1288 "TikTok API keeps sending the same page")
1289
1290
1291 class TiktokItemListRequest(TiktokPaginationRequest):
1292 def __init__(self, endpoint, type_of_items, range_predicate):
1293 super().__init__(endpoint)
1294 self.type_of_items = type_of_items
1295 self.range_predicate = range_predicate
1296 self.exit_early_due_to_no_items = False
1297
1298 def extract_items(self, data):
1299 if "itemList" not in data:
1300 if not data.get("hasMorePrevious", data.get("hasMore", False)):
1301 self.exit_early_due_to_no_items = True
1302 return {}
1303 return {item["id"]: item for item in data["itemList"]}
1304
1305 def exit_early(self, extractor, url):
1306 if self.exit_early_due_to_no_items:
1307 extractor.log.warning("%s: could not extract any %s for this user",
1308 url, self.type_of_items)
1309 return True
1310 if not self.range_predicate:
1311 # No range predicates given.
1312 return False
1313 # If our current selection of items can't satisfy the upper bound of
1314 # the predicate, we must continue extracting them until we can.
1315 return len(self.items) > max(r.stop for r in self.range_predicate) - 1
1316
1317 def generate_urls(self, profile_url, video, photo, audio):
1318 urls = {}
1319 for index, id in enumerate(self.items.keys()):
1320 if not self._matches_filters(self.items.get(id), index + 1, video,
1321 photo, audio):
1322 continue
1323 # Try to grab the author's unique ID, but don't cause the
1324 # extraction to fail if we can't, it's not imperative that the
1325 # URLs include the actual poster's unique ID.
1326 try:
1327 url = f"https://www.tiktok.com/@" \
1328 f"{self.items[id]['author']['uniqueId']}/video/{id}"
1329 except KeyError:
1330 # Use the given profile URL as a back up.
1331 url = f"{profile_url}/video/{id}"
1332 urls[url] = self.items.get(id)
1333 return urls
1334
1335 def _matches_filters(self, item, index, video, photo, audio):
1336 # First, check if this index falls within any of our configured ranges.
1337 # If it doesn't, we filter it out.
1338 if self.range_predicate:
1339 range_match = False
1340 for range in self.range_predicate:
1341 if index in range:
1342 range_match = True
1343 break
1344 if not range_match:
1345 return False
1346
1347 # Then, we apply basic video/photo filtering.
1348 if not item:
1349 return True
1350 is_image_post = "imagePost" in item
1351 if not photo and not audio and is_image_post:
1352 return False
1353 if not video and not is_image_post:
1354 return False
1355 return True
1356
1357
1358 class TiktokCreatorItemListRequest(TiktokItemListRequest):
1359 """A less flaky version of the post/item_list endpoint that doesn't
1360 support latest/popular/oldest ordering."""
1361
1362 def __init__(self, range_predicate):
1363 super().__init__("creator/item_list", "posts", range_predicate)
1364
1365 def validate_query_parameters(self, query_parameters):
1366 super().validate_query_parameters(query_parameters)
1367 assert "secUid" in query_parameters
1368 assert "type" in query_parameters
1369 # Pagination type: 0 == oldest-to-newest, 1 == newest-to-oldest.
1370 # NOTE: ^ this type parameter doesn't seem to do what yt-dlp thinks it
1371 # does. post/item_list is the only way to get an ordered feed
1372 # based on latest/popular/oldest.
1373 assert query_parameters["type"] == "0" or \
1374 query_parameters["type"] == "1"
1375
1376 def cursor_type(self, query_parameters):
1377 return TiktokLegacyTimeCursor
1378
1379
1380 class TiktokPostItemListRequest(TiktokItemListRequest):
1381 """Retrieves posts in latest/popular/oldest ordering.
1382
1383 Very often, this request will just return an empty response, making
1384 it quite flaky, but the next attempt to make the request usually
1385 does return a response. For this reason creator/item_list was kept
1386 as a backup, though it doesn't seem to support ordering.
1387
1388 It also doesn't work without cookies.
1389 """
1390
1391 def __init__(self, range_predicate):
1392 super().__init__("post/item_list", "posts", range_predicate)
1393
1394 def validate_query_parameters(self, query_parameters):
1395 super().validate_query_parameters(query_parameters)
1396 assert "secUid" in query_parameters
1397 assert "post_item_list_request_type" in query_parameters
1398 # Pagination type:
1399 # 0 == newest-to-oldest.
1400 # 1 == popular.
1401 # 2 == oldest-to-newest.
1402 assert query_parameters["post_item_list_request_type"] in \
1403 ["0", "1", "2"]
1404 assert "needPinnedItemIds" in query_parameters
1405 # If this value is set to "true", and "post_item_list_request_type" is
1406 # set to "0", pinned posts will always show up first in the resulting
1407 # itemList. It keeps our logic simpler if we avoid this behavior by
1408 # setting this parameter to "false" (especially if we were to use a
1409 # really small "count" value like "1" or "2").
1410 assert query_parameters["needPinnedItemIds"] in ["false"]
1411
1412 def cursor_type(self, query_parameters):
1413 request_type = query_parameters["post_item_list_request_type"]
1414 if request_type == "2":
1415 return TiktokForwardTimeCursor
1416 elif request_type == "1":
1417 return TiktokPopularTimeCursor
1418 else:
1419 return TiktokBackwardTimeCursor
1420
1421
1422 class TiktokFavoriteItemListRequest(TiktokItemListRequest):
1423 """Retrieves a user's liked posts.
1424
1425 Appears to only support descending order, but it can work without
1426 cookies.
1427 """
1428
1429 def __init__(self, range_predicate):
1430 super().__init__("favorite/item_list", "liked posts", range_predicate)
1431
1432 def validate_query_parameters(self, query_parameters):
1433 super().validate_query_parameters(query_parameters)
1434 assert "secUid" in query_parameters
1435 assert "post_item_list_request_type" in query_parameters
1436 assert query_parameters["post_item_list_request_type"] == "0"
1437 assert "needPinnedItemIds" in query_parameters
1438 assert query_parameters["needPinnedItemIds"] in ["false"]
1439
1440 def cursor_type(self, query_parameters):
1441 return TiktokPopularTimeCursor
1442
1443
1444 class TiktokRepostItemListRequest(TiktokItemListRequest):
1445 """Retrieves a user's reposts.
1446
1447 Appears to only support descending order, but it can work without
1448 cookies.
1449 """
1450
1451 def __init__(self, range_predicate):
1452 super().__init__("repost/item_list", "reposts", range_predicate)
1453
1454 def validate_query_parameters(self, query_parameters):
1455 super().validate_query_parameters(query_parameters)
1456 assert "secUid" in query_parameters
1457 assert "post_item_list_request_type" in query_parameters
1458 assert query_parameters["post_item_list_request_type"] == "0"
1459 assert "needPinnedItemIds" in query_parameters
1460 assert query_parameters["needPinnedItemIds"] in ["false"]
1461
1462 def cursor_type(self, query_parameters):
1463 return TiktokItemCursor
1464
1465
1466 class TiktokSavedPostItemListRequest(TiktokItemListRequest):
1467 """Retrieves a user's saved posts.
1468
1469 Appears to only support descending order, but it can work without
1470 cookies.
1471 """
1472
1473 def __init__(self, range_predicate):
1474 super().__init__("user/collect/item_list", "saved posts",
1475 range_predicate)
1476
1477 def validate_query_parameters(self, query_parameters):
1478 super().validate_query_parameters(query_parameters)
1479 assert "secUid" in query_parameters
1480 assert "post_item_list_request_type" in query_parameters
1481 assert query_parameters["post_item_list_request_type"] == "0"
1482 assert "needPinnedItemIds" in query_parameters
1483 assert query_parameters["needPinnedItemIds"] in ["false"]
1484
1485 def cursor_type(self, query_parameters):
1486 return TiktokPopularTimeCursor
1487
1488
1489 class TiktokStoryItemListRequest(TiktokItemListRequest):
1490 def __init__(self):
1491 super().__init__("story/item_list", "stories", None)
1492
1493 def validate_query_parameters(self, query_parameters):
1494 super().validate_query_parameters(query_parameters)
1495 assert "authorId" in query_parameters
1496 assert "loadBackward" in query_parameters
1497 assert query_parameters["loadBackward"] in ["true", "false"]
1498
1499 def cursor_type(self, query_parameters):
1500 return TiktokStoryTimeCursor
1501
1502
1503 class TiktokStoryBatchItemListRequest(TiktokItemListRequest):
1504 def __init__(self):
1505 super().__init__("story/batch/item_list", "stories", None)
1506
1507 def validate_query_parameters(self, query_parameters):
1508 # This request type does not need a count parameter so don't invoke
1509 # super().validate_query_parameters().
1510 assert "authorIds" in query_parameters
1511 # I'd recommend between 1-10 users at a time, as that's what I see in
1512 # the webapp.
1513 author_count = query_parameters["authorIds"].count(",") + 1
1514 assert author_count >= 1 and author_count <= 10
1515 # Not sure what this parameter does.
1516 assert "storyCallScene" in query_parameters
1517 assert query_parameters["storyCallScene"] == "2"
1518
1519 def extract_items(self, data):
1520 # We need to extract each itemList within the response and combine each
1521 # of them into a single list of items. If even one of the users doesn't
1522 # have an item list, "exit early," but continue to gather the rest
1523 # (this request doesn't use a cursor anyway so there is no concept of
1524 # exiting early).
1525 items = {}
1526 if type(data.get("batchStoryItemLists")) is not list:
1527 self.exit_early_due_to_no_items = True
1528 return items
1529 for userStories in data["batchStoryItemLists"]:
1530 items.update(super().extract_items(userStories))
1531 return items
1532
1533
1534 class TiktokStoryUserListRequest(TiktokPaginationRequest):
1535 def __init__(self):
1536 super().__init__("story/user_list")
1537 self.exit_early_due_to_no_cookies = False
1538
1539 def validate_query_parameters(self, query_parameters):
1540 super().validate_query_parameters(query_parameters)
1541 # Not sure what this parameter does.
1542 assert "storyFeedScene" in query_parameters
1543 assert query_parameters["storyFeedScene"] == "3"
1544
1545 def cursor_type(self, query_parameters):
1546 return functools.partial(TiktokItemCursor, "storyUsers")
1547
1548 def extract_items(self, data):
1549 if "storyUsers" not in data:
1550 self.exit_early_due_to_no_cookies = True
1551 return {}
1552 return {item["user"]["id"]: item["user"]["uniqueId"]
1553 for item in data["storyUsers"]}
1554
1555 def exit_early(self, extractor, url):
1556 if self.exit_early_due_to_no_cookies:
1557 extractor.log.error("You must provide cookies to extract the "
1558 "stories of your following list")
1559 return self.exit_early_due_to_no_cookies
1560
1561 def generate_urls(self):
1562 return [(id, f"https://www.tiktok.com/@{name}")
1563 for id, name in self.items.items()]