Debian Codegraph @

gallery_dl/extractor/twibooru.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2022-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://twibooru.org/"""
10
11 from .booru import BooruExtractor
12 from .. import text
13 import operator
14
15 BASE_PATTERN = r"(?:https?://)?(?:www\.)?twibooru\.org"
16
17
18 class TwibooruExtractor(BooruExtractor):
19 """Base class for twibooru extractors"""
20 category = "twibooru"
21 basecategory = "philomena"
22 root = "https://twibooru.org"
23 filename_fmt = "{id}_{filename}.{extension}"
24 archive_fmt = "{id}"
25 request_interval = (6.0, 6.1)
26 page_start = 1
27 per_page = 50
28
29 def _init(self):
30 self.api = TwibooruAPI(self)
31 self.comments = self.config("comments", False)
32 if not self.config("svg", True):
33 self._file_url = operator.itemgetter("view_url")
34
35 def _file_url(self, post):
36 if post["format"] == "svg":
37 return post["view_url"].rpartition(".")[0] + ".svg"
38 return post["view_url"]
39
40 def _prepare(self, post):
41 post["date"] = self.parse_datetime_iso(post["created_at"])
42
43 if self.comments:
44 post["comments"] = (self.api.comments(post["id"])
45 if post.get("comment_count") else ())
46
47 if "name" in post:
48 name, sep, rest = post["name"].rpartition(".")
49 post["filename"] = name if sep else rest
50
51
52 class TwibooruPostExtractor(TwibooruExtractor):
53 """Extractor for single twibooru posts"""
54 subcategory = "post"
55 request_interval = (0.5, 1.5)
56 pattern = BASE_PATTERN + r"/(\d+)"
57 example = "https://twibooru.org/12345"
58
59 def __init__(self, match):
60 TwibooruExtractor.__init__(self, match)
61 self.post_id = match[1]
62
63 def posts(self):
64 return (self.api.post(self.post_id),)
65
66
67 class TwibooruSearchExtractor(TwibooruExtractor):
68 """Extractor for twibooru search results"""
69 subcategory = "search"
70 directory_fmt = ("{category}", "{search_tags}")
71 pattern = BASE_PATTERN + r"/(?:search/?\?([^#]+)|tags/([^/?#]+))"
72 example = "https://twibooru.org/search?q=TAG"
73
74 def __init__(self, match):
75 TwibooruExtractor.__init__(self, match)
76 query, tag = match.groups()
77 if tag:
78 q = tag.replace("+", " ")
79 for old, new in (
80 ("-colon-" , ":"),
81 ("-dash-" , "-"),
82 ("-dot-" , "."),
83 ("-plus-" , "+"),
84 ("-fwslash-", "/"),
85 ("-bwslash-", "\\"),
86 ):
87 if old in q:
88 q = q.replace(old, new)
89 self.params = {"q": text.unquote(text.unquote(q))}
90 else:
91 self.params = text.parse_query(query)
92
93 def metadata(self):
94 return {"search_tags": self.params.get("q", "")}
95
96 def posts(self):
97 return self.api.search(self.params)
98
99
100 class TwibooruGalleryExtractor(TwibooruExtractor):
101 """Extractor for twibooru galleries"""
102 subcategory = "gallery"
103 directory_fmt = ("{category}", "galleries",
104 "{gallery[id]} {gallery[title]}")
105 pattern = BASE_PATTERN + r"/galleries/(\d+)"
106 example = "https://twibooru.org/galleries/12345"
107
108 def __init__(self, match):
109 TwibooruExtractor.__init__(self, match)
110 self.gallery_id = match[1]
111
112 def metadata(self):
113 return {"gallery": self.api.gallery(self.gallery_id)}
114
115 def posts(self):
116 gallery_id = "gallery_id:" + self.gallery_id
117 params = {"sd": "desc", "sf": gallery_id, "q" : gallery_id}
118 return self.api.search(params)
119
120
121 class TwibooruAPI():
122 """Interface for the Twibooru API
123
124 https://twibooru.org/pages/api
125 """
126
127 def __init__(self, extractor):
128 self.extractor = extractor
129 self.root = "https://twibooru.org/api"
130
131 def comments(self, post_id):
132 endpoint = f"/v3/posts/{post_id}/comments"
133 return self._call(endpoint)
134
135 def gallery(self, gallery_id):
136 endpoint = "/v3/galleries/" + gallery_id
137 return self._call(endpoint)["gallery"]
138
139 def post(self, post_id):
140 endpoint = "/v3/posts/" + post_id
141 return self._call(endpoint)["post"]
142
143 def search(self, params):
144 endpoint = "/v3/search/posts"
145 return self._pagination(endpoint, params)
146
147 def _call(self, endpoint, params=None):
148 url = self.root + endpoint
149
150 while True:
151 response = self.extractor.request(url, params=params, fatal=None)
152
153 if response.status_code < 400:
154 return response.json()
155
156 if response.status_code == 429:
157 until = self.parse_datetime_iso(
158 response.headers["X-RL-Reset"][:19])
159 # wait an extra minute, just to be safe
160 self.extractor.wait(until=until, adjust=60.0)
161 continue
162
163 # error
164 self.extractor.log.debug(response.content)
165 raise self.extractor.exc.HttpError("", response)
166
167 def _pagination(self, endpoint, params):
168 extr = self.extractor
169
170 if api_key := extr.config("api-key"):
171 params["key"] = api_key
172
173 if filter_id := extr.config("filter"):
174 params["filter_id"] = filter_id
175 elif not api_key:
176 params["filter_id"] = "2"
177
178 params["page"] = extr.page_start
179 params["per_page"] = per_page = extr.per_page
180
181 while True:
182 data = self._call(endpoint, params)
183 yield from data["posts"]
184
185 if len(data["posts"]) < per_page:
186 return
187 params["page"] += 1