Debian Codegraph @

gallery_dl/extractor/tiktok.py

raw
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=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
508 class TiktokPostExtractor(TiktokExtractor):
509 """Extract a single video or photo TikTok link"""
510 subcategory = "post"
511 pattern = BASE_PATTERN + r"/(?:@([\w_.-]*)|share)/(?:phot|vide)o/(\d+)"
512 example = "https://www.tiktok.com/@USER/photo/1234567890"
513
514 def posts(self):
515 user, post_id = self.groups
516 url = f"{self.root}/@{user or ''}/video/{post_id}"
517 return {url: None}
518
519
520 class TiktokVmpostExtractor(TiktokExtractor):
521 """Extract a single video or photo TikTok VM link"""
522 subcategory = "vmpost"
523 pattern = (r"(?:https?://)?(?:"
524 r"(?:v[mt]\.)?tiktok\.com|(?:www\.)?tiktok\.com/t"
525 r")/(?!@)([^/?#]+)")
526 example = "https://vm.tiktok.com/1a2B3c4E5"
527
528 def items(self):
529 url = text.ensure_http_scheme(self.url)
530 headers = {"User-Agent": "facebookexternalhit/1.1"}
531
532 url = self.request_location(url, headers=headers, notfound="post")
533 if not url or len(url) <= 28:
534 # https://www.tiktok.com/?_r=1
535 raise self.exc.NotFoundError("post")
536
537 data = {"_extractor": TiktokPostExtractor}
538 yield Message.Queue, url.partition("?")[0], data
539
540
541 class TiktokUserExtractor(Dispatch, TiktokExtractor):
542 """Extractor for a TikTok user profile"""
543 pattern = USER_PATTERN + r"/?(?:$|\?|#)"
544 example = "https://www.tiktok.com/@USER"
545
546 def items(self):
547 base = f"{self.root}/@{self.groups[0]}/"
548 return self._dispatch_extractors((
549 (TiktokAvatarExtractor , base + "avatar"),
550 (TiktokPostsExtractor , base + "posts"),
551 (TiktokRepostsExtractor, base + "reposts"),
552 (TiktokStoriesExtractor, base + "stories"),
553 (TiktokLikesExtractor , base + "likes"),
554 (TiktokSavedExtractor , base + "saved"),
555 ), ("avatar", "posts"))
556
557
558 class TiktokAvatarExtractor(TiktokExtractor):
559 subcategory = "avatar"
560 pattern = USER_PATTERN + r"/avatar"
561 example = "https://www.tiktok.com/@USER/avatar"
562
563 def items(self):
564 user_name = self.groups[0]
565 profile_url = f"{self.root}/@{user_name}"
566
567 data = self._extract_rehydration_data_user(
568 profile_url, ("userInfo", "user"))
569 data["user"] = data.get("uniqueId", user_name)
570 avatar_url = data.get("avatarLarger") or data.get("avatarMedium") \
571 or data["avatarThumb"]
572 avatar = text.nameext_from_url(avatar_url, data.copy())
573 avatar.update({
574 "type" : "avatar",
575 "title" : "@" + data["user"],
576 "id" : data["id"],
577 "file_id": avatar["filename"].partition("~")[0],
578 "num" : 0,
579 })
580
581 yield Message.Directory, "", avatar
582 yield Message.Url, avatar_url, avatar
583
584
585 class TiktokPostsExtractor(TiktokExtractor):
586 subcategory = "posts"
587 pattern = USER_PATTERN + r"/posts"
588 example = "https://www.tiktok.com/@USER/posts"
589
590 def posts(self):
591 user_name = self.groups[0]
592 profile_url = f"{self.root}/@{user_name}"
593 self.user_provided_cookies = bool(self.cookies)
594
595 # If set to "ytdl", we shall first go via yt-dlp. If that fails,
596 # we shall attempt to extract directly.
597 if self.config("ytdl", False):
598 if posts := self._extract_posts_ytdl(profile_url):
599 return posts
600 ytdl = True
601 self.log.warning("Could not extract TikTok user "
602 f"{user_name} via yt-dlp or youtube-dl, "
603 "attempting the extraction directly")
604 else:
605 ytdl = False
606
607 if posts := self._extract_posts_api(profile_url, user_name):
608 return posts
609
610 message = "Could not extract any posts from TikTok user " \
611 f"{user_name}"
612 if not ytdl:
613 message += ", try extracting post information using " \
614 "yt-dlp with the -o ytdl=true argument"
615 self.log.warning(message)
616 return ()
617
618 def _extract_posts_ytdl(self, profile_url):
619 try:
620 module = ytdl.import_module(self.config("module"))
621 except (ImportError, SyntaxError) as exc:
622 self.log.error("Cannot import module '%s'",
623 getattr(exc, "name", ""))
624 self.log.traceback(exc)
625 return []
626
627 extr_opts = {
628 "extract_flat" : True,
629 "ignore_no_formats_error": True,
630 }
631 user_opts = {
632 "retries" : self._retries,
633 "socket_timeout" : self._timeout,
634 "nocheckcertificate" : not self._verify,
635 "playlist_items" : str(self.range),
636 }
637 if self._proxies:
638 user_opts["proxy"] = self._proxies.get("http")
639
640 ytdl_instance = ytdl.construct_YoutubeDL(
641 module, self, user_opts, extr_opts)
642
643 # Transfer cookies to ytdl.
644 if self.cookies:
645 set_cookie = ytdl_instance.cookiejar.set_cookie
646 for cookie in self.cookies:
647 set_cookie(cookie)
648
649 with ytdl_instance as ydl:
650 info_dict = ydl._YoutubeDL__extract_info(
651 profile_url, ydl.get_info_extractor("TikTokUser"),
652 False, {}, True)
653 # This should be a list of video and photo post URLs in /video/
654 # format.
655 return [video["url"].partition("?")[0]
656 for video in info_dict["entries"]]
657
658 def _extract_posts_api(self, profile_url, user_name):
659 self.post_order = self.config("order-posts") or "desc"
660 if self.post_order not in ["desc", "asc", "reverse", "popular"]:
661 self.post_order = "desc"
662 sec_uid = self._extract_sec_uid(profile_url, user_name)
663
664 # If descending order is requested, opt for the more reliable legacy
665 # endpoint instead of trying with the "newer", flakier endpoint.
666 if self.post_order == "desc":
667 return self._extract_posts_api_legacy(
668 profile_url, sec_uid, self.range_predicate)
669
670 if not self.user_provided_cookies:
671 self.log.warning(
672 "%s: no cookies have been provided so the order-posts "
673 "option will not take effect. You must provide cookies in "
674 "order to extract a profile's posts in non-descending "
675 "order",
676 profile_url
677 )
678 return self._extract_posts_api_legacy(
679 profile_url, sec_uid, self.range_predicate)
680
681 try:
682 urls = self._extract_posts_api_order(
683 profile_url, sec_uid, self.range_predicate)
684 if urls:
685 return urls
686 except Exception as exc:
687 self.log.traceback(exc)
688
689 self.log.error(
690 "%s: failed to extract user posts using post/item_list (make sure "
691 "you provide valid cookies). Attempting with legacy "
692 "creator/item_list endpoint that does not support post ordering",
693 profile_url
694 )
695 return self._extract_posts_api_legacy(
696 profile_url, sec_uid, self.range_predicate)
697
698 def _extract_posts_api_order(self, profile_url, sec_uid, range_predicate):
699 post_item_list_request_type = "0"
700 if self.post_order in ["asc", "reverse"]:
701 post_item_list_request_type = "2"
702 elif self.post_order in ["popular"]:
703 post_item_list_request_type = "1"
704 query_parameters = {
705 "secUid": sec_uid,
706 "post_item_list_request_type": post_item_list_request_type,
707 "count": "15",
708 "needPinnedItemIds": "false",
709 }
710 request = TiktokPostItemListRequest(range_predicate)
711 if not request.execute(self, profile_url, query_parameters):
712 return []
713 return request.generate_urls(profile_url, self.video, self.photo,
714 self.audio)
715
716 def _extract_posts_api_legacy(self, profile_url, sec_uid, range_predicate):
717 query_parameters = {
718 "secUid": sec_uid,
719 "type": "1",
720 "count": "15",
721 }
722 request = TiktokCreatorItemListRequest(range_predicate)
723 request.execute(self, profile_url, query_parameters)
724 return request.generate_urls(profile_url, self.video, self.photo,
725 self.audio)
726
727
728 class TiktokRepostsExtractor(TiktokExtractor):
729 subcategory = "reposts"
730 pattern = USER_PATTERN + r"/reposts"
731 example = "https://www.tiktok.com/@USER/reposts"
732
733 def posts(self):
734 user_name = self.groups[0]
735 profile_url = f"{self.root}/@{user_name}"
736
737 query_parameters = {
738 "secUid": self._extract_sec_uid(profile_url, user_name),
739 "post_item_list_request_type": "0",
740 "needPinnedItemIds": "false",
741 "count": "15",
742 }
743 request = TiktokRepostItemListRequest(self.range_predicate)
744 request.execute(self, profile_url, query_parameters)
745 return request.generate_urls(profile_url, self.video, self.photo,
746 self.audio)
747
748
749 class TiktokStoriesExtractor(TiktokExtractor):
750 subcategory = "stories"
751 pattern = USER_PATTERN + r"/stories"
752 example = "https://www.tiktok.com/@USER/stories"
753
754 def posts(self):
755 user_name = self.groups[0]
756 profile_url = f"{self.root}/@{user_name}"
757
758 query_parameters = {
759 "authorId": self._extract_author_id(profile_url, user_name),
760 "loadBackward": "false",
761 "count": "5",
762 }
763 request = TiktokStoryItemListRequest()
764 request.execute(self, profile_url, query_parameters)
765 return request.generate_urls(profile_url, self.video, self.photo,
766 self.audio)
767
768
769 class TiktokLikesExtractor(TiktokExtractor):
770 subcategory = "likes"
771 pattern = USER_PATTERN + r"/like[sd]"
772 example = "https://www.tiktok.com/@USER/liked"
773
774 def posts(self):
775 user_name = self.groups[0]
776 profile_url = f"{self.root}/@{user_name}"
777
778 query_parameters = {
779 "secUid": self._extract_sec_uid(profile_url, user_name),
780 "post_item_list_request_type": "0",
781 "needPinnedItemIds": "false",
782 "count": "15",
783 }
784 request = TiktokFavoriteItemListRequest(self.range_predicate)
785 request.execute(self, profile_url, query_parameters)
786 return request.generate_urls(profile_url, self.video, self.photo,
787 self.audio)
788
789
790 class TiktokSavedExtractor(TiktokExtractor):
791 subcategory = "saved"
792 pattern = USER_PATTERN + r"/saved"
793 example = "https://www.tiktok.com/@USER/saved"
794
795 def posts(self):
796 user_name = self.groups[0]
797 profile_url = f"{self.root}/@{user_name}"
798
799 query_parameters = {
800 "secUid": self._extract_sec_uid(profile_url, user_name),
801 "post_item_list_request_type": "0",
802 "needPinnedItemIds": "false",
803 "count": "15",
804 }
805 request = TiktokSavedPostItemListRequest(self.range_predicate)
806 request.execute(self, profile_url, query_parameters)
807 return request.generate_urls(profile_url, self.video, self.photo,
808 self.audio)
809
810
811 class TiktokFollowingExtractor(TiktokExtractor):
812 """Extract all of the stories of all of the users you follow"""
813 subcategory = "following"
814 pattern = rf"{BASE_PATTERN}/following"
815 example = "https://www.tiktok.com/following"
816
817 def posts(self):
818 """Attempt to extract all of the stories of all of the accounts
819 the user follows"""
820
821 query_parameters = {
822 "storyFeedScene": "3",
823 "count": "15",
824 }
825 request = TiktokStoryUserListRequest()
826 if not request.execute(self, self.url, query_parameters):
827 self.log.error("%s: could not extract follower list, make sure "
828 "you are using logged-in cookies", self.url)
829 users = request.generate_urls()
830 if len(users) == 0:
831 self.log.warning("%s: No followers with stories could be "
832 "extracted", self.url)
833
834 entries = {}
835 # Batch all of the users up into groups of at most ten and use the
836 # batch endpoint to improve performance. The response to the story user
837 # list request may also include the user themselves, so skip them if
838 # they ever turn up.
839 for b in range((len(users) - 1) // 10 + 1):
840 batch_number = b + 1
841 user_batch = users[b*10:batch_number*10]
842
843 # Handle edge case where final batch is composed of a single user
844 # and that user is the one we need to skip. If we don't handle this
845 # here (or when we generate the author ID list later), we will
846 # trigger an AssertionError for an empty author ID list.
847 if len(user_batch) == 1:
848 if self._is_current_user(user_batch[0][0]):
849 continue
850
851 self.log.info("TikTok user stories, batch %d: %s", batch_number,
852 ", ".join([profile_url for user_id, profile_url in
853 user_batch if not self._is_current_user(
854 user_id)]))
855
856 # Since we've already extracted all of the author IDs, we should be
857 # able to avoid having to request rehydration data (except for one
858 # time, since it's required to make _is_current_user() work), but
859 # we should keep this mechanism in place for safety.
860 author_ids = [self._extract_author_id(profile_url, user_id)
861 for user_id, profile_url in user_batch
862 if not self._is_current_user(user_id)]
863 query_parameters = {
864 "authorIds": ",".join(author_ids),
865 "storyCallScene": "2",
866 }
867 request = TiktokStoryBatchItemListRequest()
868 request.execute(self, f"Batch {batch_number}", query_parameters)
869 # We technically don't need to have the correct user name in the
870 # URL and it's easier to just ignore it here.
871 entries.update(request.generate_urls("https://www.tiktok.com/@_",
872 self.video, self.photo,
873 self.audio))
874
875 return entries
876
877 def _is_current_user(self, user_id):
878 self._ensure_rehydration_data_app_context_cache_is_populated()
879 if "user" not in self.rehydration_data_app_context_cache:
880 return False
881 if "uid" not in self.rehydration_data_app_context_cache["user"]:
882 return False
883 return self.rehydration_data_app_context_cache["user"]["uid"] == \
884 user_id
885
886
887 class TiktokPaginationCursor:
888 def current_page(self):
889 """Must return the page the cursor is currently pointing to.
890
891 Returns
892 -------
893 int
894 The current value of the cursor.
895 """
896
897 return 0
898
899 def next_page(self, data, query_parameters):
900 """Must progress the cursor to the next page.
901
902 Parameters
903 ----------
904 data : dict
905 The response of the most recent request.
906 query_parameters : dict
907 All of the query parameters used for the most recent
908 request.
909
910 Returns
911 -------
912 bool
913 True if the cursor detects that we've reached the end, False
914 otherwise.
915 """
916
917 return True
918
919
920 class TiktokTimeCursor(TiktokPaginationCursor):
921 def __init__(self, *, reverse=True, has_more_attribute="hasMore",
922 cursor_attribute="cursor"):
923 super().__init__()
924 self.cursor = 0
925 # If we expect the cursor to go up or down as we go to the next page.
926 # True for down, False for up.
927 self.reverse = reverse
928 self.has_more_key = has_more_attribute
929 self.cursor_key = cursor_attribute
930
931 def current_page(self):
932 return self.cursor
933
934 def next_page(self, data, query_parameters):
935 skip_fallback_logic = self.cursor == 0
936 new_cursor = int(data.get(self.cursor_key, 0))
937 no_cursor = not new_cursor
938 if not skip_fallback_logic:
939 # If the new cursor doesn't go in the direction we expect, use the
940 # fallback logic instead.
941 if self.reverse and (new_cursor > self.cursor or no_cursor):
942 new_cursor = self.fallback_cursor(data)
943 elif not self.reverse and (new_cursor < self.cursor or no_cursor):
944 new_cursor = self.fallback_cursor(data)
945 elif no_cursor:
946 raise self.exc.ExtractionError("Could not extract next cursor")
947 self.cursor = new_cursor
948 return not data.get(self.has_more_key, False)
949
950 def fallback_cursor(self, data):
951 try:
952 return int(data["itemList"][-1]["createTime"]) * 1000
953 except Exception:
954 return 7 * 86_400_000 * (-1 if self.reverse else 1)
955
956
957 class TiktokForwardTimeCursor(TiktokTimeCursor):
958 def __init__(self):
959 super().__init__(reverse=False)
960
961
962 class TiktokBackwardTimeCursor(TiktokTimeCursor):
963 def __init__(self):
964 super().__init__(reverse=True)
965
966
967 class TiktokPopularTimeCursor(TiktokTimeCursor):
968 def __init__(self):
969 super().__init__(reverse=True)
970
971 def fallback_cursor(self, data):
972 # Don't really know what to do here, all I know is that the cursor
973 # for the popular item feed goes down and it does not appear to be
974 # based on item list timestamps at all.
975 return -50_000
976
977
978 class TiktokStoryTimeCursor(TiktokTimeCursor):
979 def __init__(self):
980 super().__init__(reverse=False, has_more_attribute="HasMoreAfter",
981 cursor_attribute="MaxCursor")
982
983
984 class TiktokLegacyTimeCursor(TiktokPaginationCursor):
985 def __init__(self):
986 super().__init__()
987 self.cursor = int(time.time()) * 1000
988
989 def current_page(self):
990 return self.cursor
991
992 def next_page(self, data, query_parameters):
993 old_cursor = self.cursor
994 try:
995 self.cursor = int(data["itemList"][-1]["createTime"]) * 1000
996 except Exception:
997 self.cursor = 0
998 if not self.cursor or old_cursor == self.cursor:
999 # User may not have posted within this ~1 week look back,
1000 # so manually adjust the cursor.
1001 self.cursor = old_cursor - 7 * 86_400_000
1002 # In case 'hasMorePrevious' is wrong, break if we have
1003 # gone back before TikTok existed.
1004 has_more_previous = data.get("hasMorePrevious")
1005 return self.cursor < 1472706000000 or not has_more_previous
1006
1007
1008 class TiktokItemCursor(TiktokPaginationCursor):
1009 def __init__(self, list_key: str = "itemList"):
1010 super().__init__()
1011 self.cursor = 0
1012 self.list_key = list_key
1013
1014 def current_page(self):
1015 return self.cursor
1016
1017 def next_page(self, data, query_parameters):
1018 # We should offset the cursor by the number of items in the response.
1019 # Sometimes less items are returned than what was requested in the
1020 # count parameter! We could fall back onto the count query parameter
1021 # but we could miss out on some posts.
1022 self.cursor += len(data.get(self.list_key, ()))
1023 if "hasMore" in data:
1024 return not data["hasMore"]
1025 return not data.get("HasMoreAfter", False)
1026
1027
1028 class TiktokPaginationRequest:
1029 def __init__(self, endpoint):
1030 self.endpoint = endpoint
1031 self._regenerate_device_id()
1032 self.items = {}
1033
1034 def execute(self, extractor, url, query_parameters):
1035 """Performs requests until all pages have been retrieved.
1036
1037 The items retrieved from this request are stored in self.items.
1038 Each call to execute() will clear the previous value of
1039 self.items.
1040
1041 Usually extractors want a simple list of URLs. For this, each
1042 request subtype is to implement generate_urls().
1043
1044 Parameters
1045 ----------
1046 extractor : TiktokExtractor
1047 The TikTok extractor performing the request.
1048 url : str
1049 The URL associated with this request for logging purposes.
1050 query_parameters : dict[str, str]
1051 The query parameters to apply to this request.
1052
1053 Returns
1054 -------
1055 bool
1056 True if the request was performed successfully and all items
1057 were retrieved, False if no items or only some items could
1058 be retrieved.
1059 """
1060
1061 self.validate_query_parameters(query_parameters)
1062 self.items = {}
1063 cursor_type = self.cursor_type(query_parameters)
1064 cursor = cursor_type() if cursor_type else None
1065 for page in itertools.count(start=1):
1066 item_count = len(self.items)
1067 extractor.log.info("%s: retrieving %s page %d (%d item%s)", url,
1068 self.endpoint, page, item_count,
1069 "" if item_count == 1 else "s")
1070 tries = 0
1071 while True:
1072 try:
1073 data, final_parameters = self._request_data(
1074 extractor,
1075 cursor,
1076 query_parameters
1077 )
1078 incoming_items = self.extract_items(data)
1079 self._detect_duplicate_pages(extractor, url,
1080 set(self.items.keys()),
1081 set(incoming_items.keys()))
1082 self.items.update(incoming_items)
1083 if cursor:
1084 final_page_reached = cursor.next_page(data,
1085 final_parameters)
1086 exit_early = self.exit_early(extractor, url)
1087 if exit_early or final_page_reached:
1088 return True
1089 # Continue to next page and reset tries counter.
1090 break
1091 else:
1092 # This request has no cursor: return immediately.
1093 return True
1094 except Exception as exc:
1095 if tries >= extractor._retries:
1096 extractor.log.error("%s: failed to retrieve %s page "
1097 "%d", url, self.endpoint, page)
1098 extractor.log.traceback(exc)
1099 return False
1100 tries += 1
1101 extractor.log.warning("%s: failed to retrieve %s page %d",
1102 url, self.endpoint, page)
1103 extractor.sleep(extractor._timeout, "retry")
1104
1105 def validate_query_parameters(self, query_parameters):
1106 """Used to validate the given parameters for this type of
1107 pagination request.
1108
1109 For developer purposes only. You should call
1110 super().validate_query_parameters() for most requests as they
1111 will usually have a count parameter.
1112
1113 Parameters
1114 ----------
1115 query_parameters : dict[str, str]
1116 The query parameters to validate.
1117
1118 Raises
1119 -------
1120 AssertionError
1121 If mandatory query parameters are not given, or they are
1122 given in the wrong format.
1123 """
1124
1125 assert "count" in query_parameters
1126 assert type(query_parameters["count"]) is str
1127 assert query_parameters["count"].isdigit()
1128 assert query_parameters["count"] != "0"
1129
1130 def cursor_type(self, query_parameters):
1131 """Used to determine which type of cursor to use for this
1132 request, if any.
1133
1134 Parameters
1135 ----------
1136 query_parameters : dict[str, str]
1137 The query parameters given to the execute() call.
1138
1139 Returns
1140 -------
1141 Type[TiktokPaginationCursor] | None
1142 The type of cursor to use, if any.
1143 """
1144
1145 return None
1146
1147 def extract_items(self, data):
1148 """Used to extract data from the response of a request.
1149
1150 Parameters
1151 ----------
1152 data : dict
1153 The data given by TikTok.
1154
1155 Returns
1156 -------
1157 dict
1158 Each item from the response data, keyed on a unique ID.
1159
1160 Raises
1161 ------
1162 Exception
1163 If items could not be extracted.
1164 """
1165
1166 return {}
1167
1168 def exit_early(self, extractor, url):
1169 """Used to determine if we should exit early from the request.
1170
1171 You have access to the items extracted so far (self.items).
1172
1173 Parameters
1174 ----------
1175 extractor : TiktokExtractor
1176 The extractor making the requests.
1177 url : str
1178 The URL associated with the executing request for logging
1179 purposes.
1180
1181 Returns
1182 -------
1183 bool
1184 True if we should exit early, False otherwise.
1185 """
1186
1187 return False
1188
1189 def generate_urls(self):
1190 """Used to convert the items retrieved from the request into a
1191 list of URLs.
1192
1193 Returns
1194 -------
1195 dict
1196 Ideally one URL for each item, that points to a video detail
1197 object, although subclasses are permitted to return a list
1198 or dict of any format they wish.
1199 """
1200
1201 return []
1202
1203 def _regenerate_device_id(self):
1204 self.device_id = str(random.randint(
1205 7_250_000_000_000_000_000, 7_325_099_899_999_994_577))
1206
1207 def _request_data(self, extractor, cursor, query_parameters):
1208 # Implement simple 1 retry mechanism without delays that handles the
1209 # flaky post/item_list endpoint.
1210 retries = 0
1211 while True:
1212 try:
1213 url, final_parameters = self._build_api_request_url(
1214 cursor,
1215 query_parameters
1216 )
1217 response = extractor.request(url, headers=generate_headers())
1218 return (util.json_loads(response.text), final_parameters)
1219 except ValueError:
1220 if retries == 1:
1221 raise
1222 extractor.log.warning(
1223 "Could not decode response for this page, trying again"
1224 )
1225 retries += 1
1226
1227 def _build_api_request_url(self, cursor, extra_parameters):
1228 query_parameters = {
1229 "aid": "1988",
1230 "app_language": "en",
1231 "app_name": "tiktok_web",
1232 "browser_language": "en-US",
1233 "browser_name": "Mozilla",
1234 "browser_online": "true",
1235 "browser_platform": "Win32",
1236 "browser_version": "5.0 (Windows)",
1237 "channel": "tiktok_web",
1238 "cookie_enabled": "true",
1239 "device_id": self.device_id,
1240 "device_platform": "web_pc",
1241 "focus_state": "true",
1242 "from_page": "user",
1243 "history_len": "2",
1244 "is_fullscreen": "false",
1245 "is_page_visible": "true",
1246 "language": "en",
1247 "os": "windows",
1248 "priority_region": "",
1249 "referer": "",
1250 "region": "US",
1251 "screen_height": "1080",
1252 "screen_width": "1920",
1253 "tz_name": "UTC",
1254 "verifyFp": "verify_" + "".join(random.choices(
1255 "0123456789abcdef", k=7)),
1256 "webcast_language": "en",
1257 }
1258 if cursor:
1259 # We must not write this as a floating-point number:
1260 query_parameters["cursor"] = str(int(cursor.current_page()))
1261 for key, value in extra_parameters.items():
1262 query_parameters[key] = f"{value}"
1263 query_str = text.build_query(query_parameters)
1264 return (f"https://www.tiktok.com/api/{self.endpoint}/?{query_str}",
1265 query_parameters)
1266
1267 def _detect_duplicate_pages(self, extractor, url, seen_ids, incoming_ids):
1268 if incoming_ids and incoming_ids == seen_ids:
1269 # TikTok API keeps sending the same page, likely due to
1270 # a bad device ID. Generate a new one and try again.
1271 self._regenerate_device_id()
1272 extractor.log.warning("%s: TikTok API keeps sending the same "
1273 "page. Taking measures to avoid an infinite "
1274 "loop", url)
1275 raise self.exc.ExtractionError(
1276 "TikTok API keeps sending the same page")
1277
1278
1279 class TiktokItemListRequest(TiktokPaginationRequest):
1280 def __init__(self, endpoint, type_of_items, range_predicate):
1281 super().__init__(endpoint)
1282 self.type_of_items = type_of_items
1283 self.range_predicate = range_predicate
1284 self.exit_early_due_to_no_items = False
1285
1286 def extract_items(self, data):
1287 if "itemList" not in data:
1288 if not data.get("hasMorePrevious", data.get("hasMore", False)):
1289 self.exit_early_due_to_no_items = True
1290 return {}
1291 return {item["id"]: item for item in data["itemList"]}
1292
1293 def exit_early(self, extractor, url):
1294 if self.exit_early_due_to_no_items:
1295 extractor.log.warning("%s: could not extract any %s for this user",
1296 url, self.type_of_items)
1297 return True
1298 if not self.range_predicate:
1299 # No range predicates given.
1300 return False
1301 # If our current selection of items can't satisfy the upper bound of
1302 # the predicate, we must continue extracting them until we can.
1303 return len(self.items) > max(r.stop for r in self.range_predicate) - 1
1304
1305 def generate_urls(self, profile_url, video, photo, audio):
1306 urls = {}
1307 for index, id in enumerate(self.items.keys()):
1308 if not self._matches_filters(self.items.get(id), index + 1, video,
1309 photo, audio):
1310 continue
1311 # Try to grab the author's unique ID, but don't cause the
1312 # extraction to fail if we can't, it's not imperative that the
1313 # URLs include the actual poster's unique ID.
1314 try:
1315 url = f"https://www.tiktok.com/@" \
1316 f"{self.items[id]['author']['uniqueId']}/video/{id}"
1317 except KeyError:
1318 # Use the given profile URL as a back up.
1319 url = f"{profile_url}/video/{id}"
1320 urls[url] = self.items.get(id)
1321 return urls
1322
1323 def _matches_filters(self, item, index, video, photo, audio):
1324 # First, check if this index falls within any of our configured ranges.
1325 # If it doesn't, we filter it out.
1326 if self.range_predicate:
1327 range_match = False
1328 for range in self.range_predicate:
1329 if index in range:
1330 range_match = True
1331 break
1332 if not range_match:
1333 return False
1334
1335 # Then, we apply basic video/photo filtering.
1336 if not item:
1337 return True
1338 is_image_post = "imagePost" in item
1339 if not photo and not audio and is_image_post:
1340 return False
1341 if not video and not is_image_post:
1342 return False
1343 return True
1344
1345
1346 class TiktokCreatorItemListRequest(TiktokItemListRequest):
1347 """A less flaky version of the post/item_list endpoint that doesn't
1348 support latest/popular/oldest ordering."""
1349
1350 def __init__(self, range_predicate):
1351 super().__init__("creator/item_list", "posts", range_predicate)
1352
1353 def validate_query_parameters(self, query_parameters):
1354 super().validate_query_parameters(query_parameters)
1355 assert "secUid" in query_parameters
1356 assert "type" in query_parameters
1357 # Pagination type: 0 == oldest-to-newest, 1 == newest-to-oldest.
1358 # NOTE: ^ this type parameter doesn't seem to do what yt-dlp thinks it
1359 # does. post/item_list is the only way to get an ordered feed
1360 # based on latest/popular/oldest.
1361 assert query_parameters["type"] == "0" or \
1362 query_parameters["type"] == "1"
1363
1364 def cursor_type(self, query_parameters):
1365 return TiktokLegacyTimeCursor
1366
1367
1368 class TiktokPostItemListRequest(TiktokItemListRequest):
1369 """Retrieves posts in latest/popular/oldest ordering.
1370
1371 Very often, this request will just return an empty response, making
1372 it quite flaky, but the next attempt to make the request usually
1373 does return a response. For this reason creator/item_list was kept
1374 as a backup, though it doesn't seem to support ordering.
1375
1376 It also doesn't work without cookies.
1377 """
1378
1379 def __init__(self, range_predicate):
1380 super().__init__("post/item_list", "posts", range_predicate)
1381
1382 def validate_query_parameters(self, query_parameters):
1383 super().validate_query_parameters(query_parameters)
1384 assert "secUid" in query_parameters
1385 assert "post_item_list_request_type" in query_parameters
1386 # Pagination type:
1387 # 0 == newest-to-oldest.
1388 # 1 == popular.
1389 # 2 == oldest-to-newest.
1390 assert query_parameters["post_item_list_request_type"] in \
1391 ["0", "1", "2"]
1392 assert "needPinnedItemIds" in query_parameters
1393 # If this value is set to "true", and "post_item_list_request_type" is
1394 # set to "0", pinned posts will always show up first in the resulting
1395 # itemList. It keeps our logic simpler if we avoid this behavior by
1396 # setting this parameter to "false" (especially if we were to use a
1397 # really small "count" value like "1" or "2").
1398 assert query_parameters["needPinnedItemIds"] in ["false"]
1399
1400 def cursor_type(self, query_parameters):
1401 request_type = query_parameters["post_item_list_request_type"]
1402 if request_type == "2":
1403 return TiktokForwardTimeCursor
1404 elif request_type == "1":
1405 return TiktokPopularTimeCursor
1406 else:
1407 return TiktokBackwardTimeCursor
1408
1409
1410 class TiktokFavoriteItemListRequest(TiktokItemListRequest):
1411 """Retrieves a user's liked posts.
1412
1413 Appears to only support descending order, but it can work without
1414 cookies.
1415 """
1416
1417 def __init__(self, range_predicate):
1418 super().__init__("favorite/item_list", "liked posts", range_predicate)
1419
1420 def validate_query_parameters(self, query_parameters):
1421 super().validate_query_parameters(query_parameters)
1422 assert "secUid" in query_parameters
1423 assert "post_item_list_request_type" in query_parameters
1424 assert query_parameters["post_item_list_request_type"] == "0"
1425 assert "needPinnedItemIds" in query_parameters
1426 assert query_parameters["needPinnedItemIds"] in ["false"]
1427
1428 def cursor_type(self, query_parameters):
1429 return TiktokPopularTimeCursor
1430
1431
1432 class TiktokRepostItemListRequest(TiktokItemListRequest):
1433 """Retrieves a user's reposts.
1434
1435 Appears to only support descending order, but it can work without
1436 cookies.
1437 """
1438
1439 def __init__(self, range_predicate):
1440 super().__init__("repost/item_list", "reposts", range_predicate)
1441
1442 def validate_query_parameters(self, query_parameters):
1443 super().validate_query_parameters(query_parameters)
1444 assert "secUid" in query_parameters
1445 assert "post_item_list_request_type" in query_parameters
1446 assert query_parameters["post_item_list_request_type"] == "0"
1447 assert "needPinnedItemIds" in query_parameters
1448 assert query_parameters["needPinnedItemIds"] in ["false"]
1449
1450 def cursor_type(self, query_parameters):
1451 return TiktokItemCursor
1452
1453
1454 class TiktokSavedPostItemListRequest(TiktokItemListRequest):
1455 """Retrieves a user's saved posts.
1456
1457 Appears to only support descending order, but it can work without
1458 cookies.
1459 """
1460
1461 def __init__(self, range_predicate):
1462 super().__init__("user/collect/item_list", "saved posts",
1463 range_predicate)
1464
1465 def validate_query_parameters(self, query_parameters):
1466 super().validate_query_parameters(query_parameters)
1467 assert "secUid" in query_parameters
1468 assert "post_item_list_request_type" in query_parameters
1469 assert query_parameters["post_item_list_request_type"] == "0"
1470 assert "needPinnedItemIds" in query_parameters
1471 assert query_parameters["needPinnedItemIds"] in ["false"]
1472
1473 def cursor_type(self, query_parameters):
1474 return TiktokPopularTimeCursor
1475
1476
1477 class TiktokStoryItemListRequest(TiktokItemListRequest):
1478 def __init__(self):
1479 super().__init__("story/item_list", "stories", None)
1480
1481 def validate_query_parameters(self, query_parameters):
1482 super().validate_query_parameters(query_parameters)
1483 assert "authorId" in query_parameters
1484 assert "loadBackward" in query_parameters
1485 assert query_parameters["loadBackward"] in ["true", "false"]
1486
1487 def cursor_type(self, query_parameters):
1488 return TiktokStoryTimeCursor
1489
1490
1491 class TiktokStoryBatchItemListRequest(TiktokItemListRequest):
1492 def __init__(self):
1493 super().__init__("story/batch/item_list", "stories", None)
1494
1495 def validate_query_parameters(self, query_parameters):
1496 # This request type does not need a count parameter so don't invoke
1497 # super().validate_query_parameters().
1498 assert "authorIds" in query_parameters
1499 # I'd recommend between 1-10 users at a time, as that's what I see in
1500 # the webapp.
1501 author_count = query_parameters["authorIds"].count(",") + 1
1502 assert author_count >= 1 and author_count <= 10
1503 # Not sure what this parameter does.
1504 assert "storyCallScene" in query_parameters
1505 assert query_parameters["storyCallScene"] == "2"
1506
1507 def extract_items(self, data):
1508 # We need to extract each itemList within the response and combine each
1509 # of them into a single list of items. If even one of the users doesn't
1510 # have an item list, "exit early," but continue to gather the rest
1511 # (this request doesn't use a cursor anyway so there is no concept of
1512 # exiting early).
1513 items = {}
1514 if type(data.get("batchStoryItemLists")) is not list:
1515 self.exit_early_due_to_no_items = True
1516 return items
1517 for userStories in data["batchStoryItemLists"]:
1518 items.update(super().extract_items(userStories))
1519 return items
1520
1521
1522 class TiktokStoryUserListRequest(TiktokPaginationRequest):
1523 def __init__(self):
1524 super().__init__("story/user_list")
1525 self.exit_early_due_to_no_cookies = False
1526
1527 def validate_query_parameters(self, query_parameters):
1528 super().validate_query_parameters(query_parameters)
1529 # Not sure what this parameter does.
1530 assert "storyFeedScene" in query_parameters
1531 assert query_parameters["storyFeedScene"] == "3"
1532
1533 def cursor_type(self, query_parameters):
1534 return functools.partial(TiktokItemCursor, "storyUsers")
1535
1536 def extract_items(self, data):
1537 if "storyUsers" not in data:
1538 self.exit_early_due_to_no_cookies = True
1539 return {}
1540 return {item["user"]["id"]: item["user"]["uniqueId"]
1541 for item in data["storyUsers"]}
1542
1543 def exit_early(self, extractor, url):
1544 if self.exit_early_due_to_no_cookies:
1545 extractor.log.error("You must provide cookies to extract the "
1546 "stories of your following list")
1547 return self.exit_early_due_to_no_cookies
1548
1549 def generate_urls(self):
1550 return [(id, f"https://www.tiktok.com/@{name}")
1551 for id, name in self.items.items()]
1552
1553
1554 def generate_headers(min_headers=3, max_headers=8):
1555 """Randomize HTTP header fingerprint
1556 in an attempt to avoid HTTP Error 403 blockage"""
1557 def randletters(min, max):
1558 return "".join(random.choices(
1559 "bcdfghjklmnpqrstvwxz", k=random.randint(min, max)))
1560 return {
1561 randletters(8, 24): randletters(16, 32)
1562 for _ in range(random.randint(min_headers, max_headers))
1563 }