Debian Codegraph @

gallery_dl/extractor/kemono.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2021-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Extractors for https://kemono.cr/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13 import itertools
14 import json
15
16 BASE_PATTERN = (r"(?:https?://)?(?:www\.|beta\.)?"
17 r"(kemono|coomer)\.(cr|s[tu]|party)")
18 USER_PATTERN = BASE_PATTERN + r"/([^/?#]+)/user/([^/?#]+)"
19 HASH_PATTERN = r"/[0-9a-f]{2}/[0-9a-f]{2}/([0-9a-f]{64})"
20
21
22 class KemonoExtractor(Extractor):
23 """Base class for kemono extractors"""
24 category = "kemono"
25 root = "https://kemono.cr"
26 directory_fmt = ("{category}", "{service}", "{user}")
27 filename_fmt = "{id}_{title[:180]}_{num:>02}_{filename[:180]}.{extension}"
28 archive_fmt = "{service}_{user}_{id}_{num}"
29 cookies_domain = ".kemono.cr"
30
31 def __init__(self, match):
32 if match[1] == "coomer":
33 self.category = "coomer"
34 self.root = "https://coomer.st"
35 self.cookies_domain = ".coomer.st"
36 Extractor.__init__(self, match)
37
38 def _init(self):
39 self.api = KemonoAPI(self)
40 self.revisions = self.config("revisions")
41 if self.revisions:
42 self.revisions_unique = (self.revisions == "unique")
43 order = self.config("order-revisions")
44 self.revisions_reverse = order[0] in {"r", "a"} if order else False
45
46 self._find_inline = text.re(
47 r'src="(?:https?://(?:kemono\.cr|coomer\.st))?(/inline/[^"]+'
48 r'|/[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{64}\.[^"]+)').findall
49 self._json_dumps = json.JSONEncoder(
50 ensure_ascii=False, check_circular=False,
51 sort_keys=True, separators=(",", ":")).encode
52
53 def items(self):
54 find_hash = text.re(HASH_PATTERN).match
55 generators = self._build_file_generators(self.config("files"))
56 announcements = True if self.config("announcements") else None
57 archives = True if self.config("archives") else False
58 archives_type = dict if self.config("archives-format") in {
59 "dict", "object"} else list
60 comments = True if self.config("comments") else False
61 dms = True if self.config("dms") else None
62 max_posts = self.config("max-posts")
63 creator_info = {} if self.config("metadata", True) else None
64 exts_archive = util.EXTS_ARCHIVE
65
66 if self.config("original", False):
67 original = True
68 else:
69 original = False
70 root_thmb = self.root.replace("://", "://img.") + "/thumbnail/data"
71 exts_thmb = util.EXTS_IMAGE
72
73 if duplicates := self.config("duplicates"):
74 if isinstance(duplicates, str):
75 duplicates = set(duplicates.split(","))
76 elif isinstance(duplicates, (list, tuple)):
77 duplicates = set(duplicates)
78 else:
79 duplicates = {"file", "attachment", "inline"}
80 else:
81 duplicates = ()
82
83 # prevent files from being sent with gzip compression
84 headers = {"Accept-Encoding": "identity"}
85
86 posts = self.posts()
87 if max_posts:
88 posts = itertools.islice(posts, max_posts)
89 if self.revisions:
90 posts = self._revisions(posts)
91
92 for post in posts:
93 if "post" in post:
94 post = post["post"]
95 headers["Referer"] = (f"{self.root}/{post['service']}/user/"
96 f"{post['user']}/post/{post['id']}")
97 post["_http_headers"] = headers
98 post["date"] = self._parse_datetime(
99 post.get("published") or post.get("added") or "")
100 service = post["service"]
101 creator_id = post["user"]
102
103 if creator_info is not None:
104 key = f"{service}_{creator_id}"
105 if key not in creator_info:
106 try:
107 creator = creator_info[key] = self.api.creator_profile(
108 service, creator_id)
109 except self.exc.HttpError:
110 self.log.warning("%s/%s/%s: 'Creator not found'",
111 service, creator_id, post["id"])
112 creator = creator_info[key] = util.NONE
113 else:
114 creator = creator_info[key]
115
116 post["user_profile"] = creator
117 post["username"] = creator["name"]
118
119 if comments:
120 post["comments"] = cmts = self.api.creator_post_comments(
121 service, creator_id, post["id"])
122 if not isinstance(cmts, list):
123 self.log.debug("%s/%s: %s", creator_id, post["id"], cmts)
124 post["comments"] = ()
125 if dms is not None:
126 if dms is True:
127 dms = self.api.creator_dms(
128 post["service"], post["user"])
129 post["dms"] = dms
130 if announcements is not None:
131 if announcements is True:
132 announcements = self.api.creator_announcements(
133 post["service"], post["user"])
134 post["announcements"] = announcements
135
136 files = []
137 hashes = set()
138 post_archives = post["archives"] = archives_type()
139
140 for file in itertools.chain.from_iterable(
141 g(post) for g in generators):
142 url = file["path"]
143
144 if "\\" in url:
145 file["path"] = url = url.replace("\\", "/")
146
147 if match := find_hash(url):
148 file["hash"] = hash = match[1]
149 if file["type"] not in duplicates and hash in hashes:
150 self.log.debug("Skipping %s %s (duplicate)",
151 file["type"], url)
152 continue
153 hashes.add(hash)
154 else:
155 file["hash"] = hash = ""
156
157 if url[0] == "/":
158 url = f"{self.root}/data{url}"
159 elif url.startswith(self.root):
160 url = f"{self.root}/data{url[20:]}"
161 file["url"] = url
162
163 if name := file.get("name"):
164 text.nameext_from_name(name, file)
165 ext = text.ext_from_url(url)
166
167 if not file["extension"]:
168 file["extension"] = ext
169 elif ext == "txt" and file["extension"] != "txt":
170 file["_http_validate"] = _validate
171 else:
172 text.nameext_from_url(url, file)
173 ext = file["extension"]
174
175 if ext in exts_archive or \
176 ext == "bin" and file["extension"] in exts_archive:
177 file["type"] = "archive"
178 if archives:
179 try:
180 archive = self.api.file(hash)
181 archive.update(file)
182 except Exception as exc:
183 self.log.warning(
184 "%s: Failed to retrieve archive metadata of "
185 "'%s' (%s: %s)", post["id"], file.get("name"),
186 exc.__class__.__name__, exc)
187 archive = file.copy()
188 else:
189 archive = file.copy()
190 if archives_type is dict:
191 post_archives[hash] = archive
192 else:
193 post_archives.append(archive)
194
195 files.append(file)
196
197 post["count"] = len(files)
198 yield Message.Directory, "", post
199 if original:
200 for post["num"], file in enumerate(files, 1):
201 if "id" in file:
202 del file["id"]
203 post.update(file)
204 yield Message.Url, file["url"], post
205
206 else:
207 for post["num"], file in enumerate(files, 1):
208 if file["extension"] in exts_thmb:
209 if "id" in file:
210 del file["id"]
211 post.update(file)
212 yield Message.Url, root_thmb + file["path"], post
213 else:
214 self.log.warning("%s: Skipping %s",
215 post["id"], file["path"][7:])
216
217 def login(self):
218 username, password = self._get_auth_info()
219 if username:
220 self.cookies_update(self.cache(
221 self._login_impl, (username, self.cookies_domain), password,
222 _exp=3650*86400, _mem=False))
223
224 def _login_impl(self, username, password):
225 username = username[0]
226 self.log.info("Logging in as %s", username)
227
228 url = self.root + "/api/v1/authentication/login"
229 data = {"username": username, "password": password}
230
231 response = self.request(url, method="POST", json=data, fatal=False)
232 if response.status_code >= 400:
233 try:
234 msg = f'"{response.json()["error"]}"'
235 except Exception:
236 msg = '"Username or password is incorrect"'
237 raise self.exc.AuthenticationError(msg)
238
239 return {c.name: c.value for c in response.cookies}
240
241 def _file(self, post):
242 file = post["file"]
243 if not file or "path" not in file:
244 return ()
245 file["type"] = "file"
246 return (file,)
247
248 def _attachments(self, post):
249 for attachment in post["attachments"]:
250 attachment["type"] = "attachment"
251 return post["attachments"]
252
253 def _inline(self, post):
254 for path in self._find_inline(post.get("content") or ""):
255 yield {"path": path, "name": path, "type": "inline"}
256
257 def _build_file_generators(self, filetypes):
258 if filetypes is None:
259 if self.category == "coomer":
260 return (self._file, self._attachments, self._inline)
261 return (self._attachments, self._file, self._inline)
262 genmap = {
263 "file" : self._file,
264 "attachments": self._attachments,
265 "inline" : self._inline,
266 }
267 if isinstance(filetypes, str):
268 filetypes = filetypes.split(",")
269 return [genmap[ft] for ft in filetypes]
270
271 def _parse_datetime(self, date_string):
272 if len(date_string) > 19:
273 date_string = date_string[:19]
274 return self.parse_datetime_iso(date_string)
275
276 def _revisions(self, posts):
277 return itertools.chain.from_iterable(
278 self._revisions_post(post) for post in posts)
279
280 def _revisions_get(self, post):
281 if (props := post.get("props")) and "revisions" in props:
282 return [
283 rev[1]
284 for rev in props["revisions"]
285 if "revision_id" in rev[1]
286 ]
287 return self.api.creator_post_revisions(
288 post["service"], post["user"], post["id"])
289
290 def _revisions_post(self, post):
291 revs = self._revisions_get(post)
292
293 if "post" in post:
294 post = post["post"]
295 post["revision_id"] = 0
296
297 if not revs:
298 post["revision_hash"] = self._revision_hash(post)
299 post["revision_index"] = 1
300 post["revision_count"] = 1
301 return (post,)
302
303 revs.insert(0, post)
304 for rev in revs:
305 rev["revision_hash"] = self._revision_hash(rev)
306
307 if self.revisions_unique:
308 uniq = []
309 last = None
310 for rev in revs:
311 if last != rev["revision_hash"]:
312 last = rev["revision_hash"]
313 uniq.append(rev)
314 revs = uniq
315
316 cnt = idx = len(revs)
317 for rev in revs:
318 rev["revision_index"] = idx
319 rev["revision_count"] = cnt
320 idx -= 1
321
322 if self.revisions_reverse:
323 revs.reverse()
324
325 return revs
326
327 def _revisions_all(self, post):
328 revs = self._revisions_get(post)
329
330 cnt = idx = len(revs)
331 for rev in revs:
332 rev["revision_hash"] = self._revision_hash(rev)
333 rev["revision_index"] = idx
334 rev["revision_count"] = cnt
335 idx -= 1
336
337 if self.revisions_reverse:
338 revs.reverse()
339
340 return revs
341
342 def _revision_hash(self, revision):
343 if isinstance(revision["file"], str):
344 revision["file"] = util.json_loads(revision["file"])
345 revision["attachments"] = [
346 util.json_loads(a) for a in revision["attachments"]]
347
348 rev = revision.copy()
349 rev.pop("revision_id", None)
350 rev.pop("added", None)
351 rev.pop("next", None)
352 rev.pop("prev", None)
353 rev["file"] = rev["file"].copy()
354 rev["file"].pop("name", None)
355 rev["attachments"] = [a.copy() for a in rev["attachments"]]
356 for a in rev["attachments"]:
357 a.pop("name", None)
358 return util.sha1(self._json_dumps(rev))
359
360 def _discord_server_info(self, server_id):
361 server = self.api.discord_server(server_id)
362 return server, {
363 channel["id"]: channel
364 for channel in server.pop("channels")
365 }
366
367
368 def _validate(response):
369 return (response.headers["content-length"] != "9" or
370 response.content != b"not found")
371
372
373 class KemonoUserExtractor(KemonoExtractor):
374 """Extractor for all posts from a kemono.cr user listing"""
375 subcategory = "user"
376 pattern = USER_PATTERN + r"/?(?:\?([^#]+))?(?:$|\?|#)"
377 example = "https://kemono.cr/SERVICE/user/12345"
378
379 def __init__(self, match):
380 self.subcategory = match[3]
381 KemonoExtractor.__init__(self, match)
382
383 def posts(self):
384 _, _, service, creator_id, query = self.groups
385 params = text.parse_query(query)
386
387 if self.config("endpoint") in {"posts+", "legacy+"}:
388 endpoint = self.api.creator_posts_expand
389 else:
390 endpoint = self.api.creator_posts
391
392 return endpoint(service, creator_id,
393 params.get("o"), params.get("q"), params.get("tag"))
394
395
396 class KemonoPostsExtractor(KemonoExtractor):
397 """Extractor for kemono.cr post listings"""
398 subcategory = "posts"
399 pattern = BASE_PATTERN + r"/posts()()(?:/?\?([^#]+))?"
400 example = "https://kemono.cr/posts"
401
402 def posts(self):
403 params = text.parse_query(self.groups[4])
404 return self.api.posts(
405 params.get("o"), params.get("q"), params.get("tag"))
406
407
408 class KemonoPostExtractor(KemonoExtractor):
409 """Extractor for a single kemono.cr post"""
410 subcategory = "post"
411 pattern = USER_PATTERN + r"/post/([^/?#]+)(/revisions?(?:/(\d*))?)?"
412 example = "https://kemono.cr/SERVICE/user/12345/post/12345"
413
414 def __init__(self, match):
415 self.subcategory = match[3]
416 KemonoExtractor.__init__(self, match)
417
418 def posts(self):
419 _, _, service, creator_id, post_id, revision, revision_id = self.groups
420 post = self.api.creator_post(service, creator_id, post_id)
421 if not revision:
422 return (post,)
423
424 self.revisions = False
425
426 revs = self._revisions_all(post)
427 if not revision_id:
428 return revs
429
430 for rev in revs:
431 if str(rev["revision_id"]) == revision_id:
432 return (rev,)
433
434 raise self.exc.NotFoundError("revision")
435
436
437 class KemonoDiscordExtractor(KemonoExtractor):
438 """Extractor for kemono.cr discord servers"""
439 subcategory = "discord"
440 directory_fmt = ("{category}", "discord",
441 "{server_id} {server}", "{channel_id} {channel}")
442 filename_fmt = "{id}_{num:>02}_{filename}.{extension}"
443 archive_fmt = "discord_{server_id}_{id}_{num}"
444 pattern = BASE_PATTERN + r"/discord/server/(\d+)[/#](?:channel/)?(\d+)"
445 example = "https://kemono.cr/discord/server/12345/12345"
446
447 def items(self):
448 _, _, server_id, channel_id = self.groups
449
450 try:
451 server, channels = self.cache(self._discord_server_info, server_id)
452 channel = channels[channel_id]
453 except Exception:
454 raise self.exc.NotFoundError("channel")
455
456 metadata = {
457 "server" : server["name"],
458 "server_id" : server["id"],
459 "channel" : channel["name"],
460 "channel_id" : channel["id"],
461 "channel_nsfw" : channel["is_nsfw"],
462 "channel_type" : channel["type"],
463 "channel_topic": channel["topic"],
464 "parent_id" : channel["parent_channel_id"],
465 }
466
467 find_inline = text.re(
468 r"https?://(?:cdn\.discordapp.com|media\.discordapp\.net)"
469 r"(/[A-Za-z0-9-._~:/?#\[\]@!$&'()*+,;%=]+)").findall
470 find_hash = text.re(HASH_PATTERN).match
471 archives = True if self.config("archives") else False
472 archives_type = dict if self.config("archives-format") in {
473 "dict", "object"} else list
474 exts_archive = util.EXTS_ARCHIVE
475
476 if self.config("original", False):
477 original = True
478 else:
479 original = False
480 root_thmb = self.root.replace("://", "://img.") + "/thumbnail/data"
481 exts_thmb = util.EXTS_IMAGE
482
483 if (order := self.config("order-posts")) and order[0] in {"r", "d"}:
484 posts = self.api.discord_channel(channel_id, channel["post_count"])
485 else:
486 posts = self.api.discord_channel(channel_id)
487
488 if max_posts := self.config("max-posts"):
489 posts = itertools.islice(posts, max_posts)
490
491 for post in posts:
492 files = []
493 for attachment in post["attachments"]:
494 match = find_hash(attachment["path"])
495 attachment["hash"] = match[1] if match else ""
496 attachment["type"] = "attachment"
497 files.append(attachment)
498 for path in find_inline(post["content"] or ""):
499 files.append({"path": "https://cdn.discordapp.com" + path,
500 "name": path, "type": "inline", "hash": ""})
501
502 post.update(metadata)
503 post["date"] = self._parse_datetime(post["published"])
504 post["count"] = len(files)
505 post["archives"] = post_archives = ()
506
507 yield Message.Directory, "", post
508
509 for post["num"], file in enumerate(files, 1):
510 post["hash"] = hash = file["hash"]
511 post["type"] = file["type"]
512 url = file["path"]
513
514 if name := file.get("name"):
515 text.nameext_from_name(name, post)
516 ext = text.ext_from_url(url)
517 if not post["extension"]:
518 post["extension"] = ext
519 else:
520 text.nameext_from_url(url, post)
521 ext = post["extension"]
522
523 if ext in exts_archive:
524 if not post_archives:
525 post["archives"] = post_archives = archives_type()
526 post["type"] = "archive"
527 if archives:
528 try:
529 archive = self.api.file(hash)
530 archive.update(file)
531 except Exception as exc:
532 self.log.warning(
533 "%s: Failed to retrieve archive metadata of "
534 "'%s' (%s: %s)", post["id"], file.get("name"),
535 exc.__class__.__name__, exc)
536 archive = file.copy()
537 else:
538 archive = file.copy()
539 if archives_type is dict:
540 post_archives[hash] = archive
541 else:
542 post_archives.append(archive)
543
544 if original:
545 if url[0] == "/":
546 url = f"{self.root}/data{url}"
547 elif url.startswith(self.root):
548 url = f"{self.root}/data{url[20:]}"
549 elif ext in exts_thmb:
550 url = root_thmb + file["path"]
551 else:
552 self.log.warning("%s: Skipping %s",
553 post["id"], file["path"][7:])
554 continue
555 yield Message.Url, url, post
556
557
558 class KemonoDiscordServerExtractor(KemonoExtractor):
559 subcategory = "discord-server"
560 pattern = BASE_PATTERN + r"/discord/server/(\d+)"
561 example = "https://kemono.cr/discord/server/12345"
562
563 def items(self):
564 server_id = self.groups[2]
565 server, channels = self.cache(self._discord_server_info, server_id)
566 for channel in channels.values():
567 url = (f"{self.root}/discord/server/{server_id}/"
568 f"{channel['id']}#{channel['name']}")
569 yield Message.Queue, url, {
570 "server" : server,
571 "channel" : channel,
572 "_extractor": KemonoDiscordExtractor,
573 }
574
575
576 class KemonoFavoriteExtractor(KemonoExtractor):
577 """Extractor for kemono.cr favorites"""
578 subcategory = "favorite"
579 pattern = BASE_PATTERN + r"/(?:account/)?favorites()()(?:/?\?([^#]+))?"
580 example = "https://kemono.cr/account/favorites/artists"
581
582 def items(self):
583 self.login()
584
585 params = text.parse_query(self.groups[4])
586 type = params.get("type") or self.config("favorites") or "artist"
587
588 sort = params.get("sort")
589 order = params.get("order") or "desc"
590
591 if type == "artist":
592 users = self.api.account_favorites("artist")
593
594 if not sort:
595 sort = "updated"
596 users.sort(key=lambda x: x[sort] or util.NONE,
597 reverse=(order == "desc"))
598
599 for user in users:
600 service = user["service"]
601 if service == "discord":
602 user["_extractor"] = KemonoDiscordServerExtractor
603 url = f"{self.root}/discord/server/{user['id']}"
604 else:
605 user["_extractor"] = KemonoUserExtractor
606 url = f"{self.root}/{service}/user/{user['id']}"
607 yield Message.Queue, url, user
608
609 elif type == "post":
610 posts = self.api.account_favorites("post")
611
612 if not sort:
613 sort = "faved_seq"
614 posts.sort(key=lambda x: x[sort] or util.NONE,
615 reverse=(order == "desc"))
616
617 for post in posts:
618 post["_extractor"] = KemonoPostExtractor
619 url = (f"{self.root}/{post['service']}/user/"
620 f"{post['user']}/post/{post['id']}")
621 yield Message.Queue, url, post
622
623
624 class KemonoArtistsExtractor(KemonoExtractor):
625 """Extractor for kemono artists"""
626 subcategory = "artists"
627 pattern = BASE_PATTERN + r"/artists(?:\?([^#]+))?"
628 example = "https://kemono.cr/artists"
629
630 def items(self):
631 params = text.parse_query(self.groups[2])
632 users = self.api.creators()
633
634 if params.get("service"):
635 service = params["service"].lower()
636 users = [user for user in users
637 if user["service"] == service]
638
639 if params.get("q"):
640 q = params["q"].lower()
641 users = [user for user in users
642 if q in user["name"].lower()]
643
644 sort = params.get("sort_by") or "favorited"
645 order = params.get("order") or "desc"
646 users.sort(key=lambda user: user[sort] or util.NONE,
647 reverse=(order != "asc"))
648
649 for user in users:
650 service = user["service"]
651 if service == "discord":
652 user["_extractor"] = KemonoDiscordServerExtractor
653 url = f"{self.root}/discord/server/{user['id']}"
654 else:
655 user["_extractor"] = KemonoUserExtractor
656 url = f"{self.root}/{service}/user/{user['id']}"
657 yield Message.Queue, url, user
658
659
660 class KemonoAPI():
661 """Interface for the Kemono API v1.3.0
662
663 https://kemono.cr/documentation/api
664 """
665
666 def __init__(self, extractor):
667 self.extractor = extractor
668 self.root = extractor.root + "/api"
669 self.headers = {"Accept": "text/css"}
670
671 def posts(self, offset=0, query=None, tags=None):
672 endpoint = "/v1/posts"
673 params = {"q": query, "o": offset, "tag": tags}
674 return self._pagination(endpoint, params, 50, "posts")
675
676 def file(self, file_hash):
677 endpoint = "/v1/file/" + file_hash
678 return self._call(endpoint)
679
680 def creators(self):
681 endpoint = "/v1/creators"
682 return self._call(endpoint)
683
684 def creator_posts(self, service, creator_id,
685 offset=0, query=None, tags=None):
686 endpoint = f"/v1/{service}/user/{creator_id}/posts"
687 params = {"o": offset, "tag": tags, "q": query}
688 return self._pagination(endpoint, params, 50)
689
690 def creator_posts_expand(self, service, creator_id,
691 offset=0, query=None, tags=None):
692 for post in self.creator_posts(
693 service, creator_id, offset, query, tags):
694 yield self.creator_post(
695 service, creator_id, post["id"])["post"]
696
697 def creator_announcements(self, service, creator_id):
698 endpoint = f"/v1/{service}/user/{creator_id}/announcements"
699 return self._call(endpoint)
700
701 def creator_dms(self, service, creator_id):
702 endpoint = f"/v1/{service}/user/{creator_id}/dms"
703 return self._call(endpoint)
704
705 def creator_fancards(self, service, creator_id):
706 endpoint = f"/v1/{service}/user/{creator_id}/fancards"
707 return self._call(endpoint)
708
709 def creator_post(self, service, creator_id, post_id):
710 endpoint = f"/v1/{service}/user/{creator_id}/post/{post_id}"
711 return self._call(endpoint)
712
713 def creator_post_comments(self, service, creator_id, post_id):
714 endpoint = f"/v1/{service}/user/{creator_id}/post/{post_id}/comments"
715 return self._call(endpoint, fatal=False)
716
717 def creator_post_revisions(self, service, creator_id, post_id):
718 endpoint = f"/v1/{service}/user/{creator_id}/post/{post_id}/revisions"
719 return self._call(endpoint, fatal=False)
720
721 def creator_profile(self, service, creator_id):
722 endpoint = f"/v1/{service}/user/{creator_id}/profile"
723 return self._call(endpoint)
724
725 def creator_links(self, service, creator_id):
726 endpoint = f"/v1/{service}/user/{creator_id}/links"
727 return self._call(endpoint)
728
729 def creator_tags(self, service, creator_id):
730 endpoint = f"/v1/{service}/user/{creator_id}/tags"
731 return self._call(endpoint)
732
733 def discord_channel(self, channel_id, post_count=None):
734 endpoint = "/v1/discord/channel/" + channel_id
735 if post_count is None:
736 return self._pagination(endpoint, {}, 150)
737 else:
738 return self._pagination_reverse(endpoint, {}, 150, post_count)
739
740 def discord_channel_lookup(self, server_id):
741 endpoint = "/v1/discord/channel/lookup/" + server_id
742 return self._call(endpoint)
743
744 def discord_server(self, server_id):
745 endpoint = "/v1/discord/server/" + server_id
746 return self._call(endpoint)
747
748 def account_favorites(self, type):
749 endpoint = "/v1/account/favorites"
750 params = {"type": type}
751 return self._call(endpoint, params)
752
753 def _call(self, endpoint, params=None, headers=None, fatal=True):
754 if headers is None:
755 headers = self.headers
756 else:
757 headers = {**self.headers, **headers}
758
759 return self.extractor.request_json(
760 self.root + endpoint, params=params, headers=headers,
761 encoding="utf-8", fatal=fatal)
762
763 def _pagination(self, endpoint, params, batch=50, key=None):
764 offset = text.parse_int(params.get("o"))
765 params["o"] = offset - offset % batch
766
767 while True:
768 data = self._call(endpoint, params)
769
770 if key is not None:
771 data = data.get(key)
772 if not data:
773 return
774 yield from data
775
776 if len(data) < batch:
777 return
778 params["o"] += batch
779
780 def _pagination_reverse(self, endpoint, params, batch, count):
781 params["o"] = count // batch * batch
782
783 while True:
784 data = self._call(endpoint, params)
785
786 if not data:
787 return
788 data.reverse()
789 yield from data
790
791 if not params["o"]:
792 return
793 params["o"] -= batch