Debian Codegraph @

gallery_dl/extractor/sankaku.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2014-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://sankaku.app/"""
10
11 from .booru import BooruExtractor
12 from .common import Message
13 from .. import text, util
14 import collections
15
16 BASE_PATTERN = r"(?:https?://)?" \
17 r"(?:(?:chan|www|beta|black|white)\.sankakucomplex\.com|sankaku\.app)" \
18 r"(?:/[a-z]{2}(?:[-_][A-Z]{2})?)?"
19
20
21 class SankakuExtractor(BooruExtractor):
22 """Base class for sankaku channel extractors"""
23 basecategory = "booru"
24 category = "sankaku"
25 root = "https://sankaku.app"
26 filename_fmt = "{category}_{id}_{md5}.{extension}"
27 _warning = True
28
29 TAG_TYPES = {
30 0: "general",
31 1: "artist",
32 2: "studio",
33 3: "copyright",
34 4: "character",
35 5: "genre",
36 6: "",
37 7: "",
38 8: "medium",
39 9: "meta",
40 }
41
42 skip_files = None
43
44 def import_blacklist(self):
45 self.api.authenticate()
46 return self.api.users_blacklist()
47
48 def _init(self):
49 self.api = SankakuAPI(self)
50 if self.config("tags") == "extended":
51 self._tags = self._tags_extended
52 self._tags_findall = text.re(
53 r"(?s)tag-type-([^\"' ]+).*?\?tags=([^\"'&]+)").findall
54
55 def _file_url(self, post):
56 url = post["file_url"]
57 if not url:
58 if post["status"] != "active":
59 self.log.warning(
60 "Unable to download post %s (%s)",
61 post["id"], post["status"])
62 elif self._warning:
63 self.log.warning(
64 "Login required to download 'contentious_content' posts")
65 SankakuExtractor._warning = False
66 elif url[4] != "s":
67 url = "https" + url[4:]
68 return url
69
70 def _prepare(self, post):
71 post["created_at"] = post["created_at"]["s"]
72 post["date"] = self.parse_timestamp(post["created_at"])
73 post["tags"] = post.pop("tag_names", ())
74 post["tag_string"] = " ".join(post["tags"])
75 post["_http_validate"] = self._check_expired
76
77 def _check_expired(self, response):
78 return not response.history or '.com/expired.png' not in response.url
79
80 def _tags(self, post, page):
81 tags = collections.defaultdict(list)
82 for tag in self.api.tags(post["id"]):
83 if name := tag["name"]:
84 tags[tag["type"]].append(name.lower().replace(" ", "_"))
85 types = self.TAG_TYPES
86 for type, values in tags.items():
87 name = types[type]
88 post["tags_" + name] = values
89 post["tag_string_" + name] = " ".join(values)
90
91 def _tags_extended(self, post, page):
92 try:
93 url = "https://chan.sankakucomplex.com/posts/" + post["id"]
94 headers = {"Referer": url}
95 page = self.request(url, headers=headers).text
96 except Exception as exc:
97 return self.log.warning(
98 "%s: Failed to extract extended tag categories (%s: %s)",
99 post["id"], exc.__class__.__name__, exc)
100
101 tags = collections.defaultdict(list)
102 tag_sidebar = text.extr(page, '<ul id="tag-sidebar"', "</ul>")
103 for tag_type, tag_name in self._tags_findall(tag_sidebar):
104 tags[tag_type].append(text.unescape(text.unquote(tag_name)))
105 for type, values in tags.items():
106 post["tags_" + type] = values
107 post["tag_string_" + type] = " ".join(values)
108
109 def _notes(self, post, page):
110 if post.get("has_notes"):
111 post["notes"] = self.api.notes(post["id"])
112 for note in post["notes"]:
113 note["created_at"] = note["created_at"]["s"]
114 note["updated_at"] = note["updated_at"]["s"]
115 else:
116 post["notes"] = ()
117
118
119 class SankakuTagExtractor(SankakuExtractor):
120 """Extractor for images from sankaku.app by search-tags"""
121 subcategory = "tag"
122 directory_fmt = ("{category}", "{search_tags}")
123 archive_fmt = "t_{search_tags}_{id}"
124 pattern = BASE_PATTERN + r"(?:/posts)?/?\?([^#]*)"
125 example = "https://sankaku.app/?tags=TAG"
126
127 def __init__(self, match):
128 SankakuExtractor.__init__(self, match)
129 query = text.parse_query(match[1])
130 self.tags = query.get("tags", "")
131
132 if "date:" in self.tags:
133 # rewrite 'date:' tags (#1790)
134 self.tags = text.re(
135 r"date:(\d\d)[.-](\d\d)[.-](\d\d\d\d)(?!T)").sub(
136 r"date:\3-\2-\1T00:00", self.tags)
137 self.tags = text.re(
138 r"date:(\d\d\d\d)[.-](\d\d)[.-](\d\d)(?!T)").sub(
139 r"date:\1-\2-\3T00:00", self.tags)
140
141 def metadata(self):
142 return {"search_tags": self.tags}
143
144 def posts(self):
145 posts = self.api.posts_keyset({"tags": self.tags})
146
147 if "parent:" in self.tags:
148 import itertools
149 parent = self.api.posts_keyset({"tags": text.re(
150 r"\bparent:(\w+)").sub(r"id_range:\1", self.tags)})
151 posts = itertools.chain(parent, posts)
152
153 return posts
154
155
156 class SankakuPoolExtractor(SankakuExtractor):
157 """Extractor for image pools or books from sankaku.app"""
158 subcategory = "pool"
159 directory_fmt = ("{category}", "pool", "{pool[id]} {pool[name_en]}")
160 archive_fmt = "p_{pool}_{id}"
161 pattern = BASE_PATTERN + r"/(?:books|pools?/show)/(\w+)"
162 example = "https://sankaku.app/books/12345"
163
164 def metadata(self):
165 pool = self.api.pools(self.groups[0])
166 pool["tags"] = [tag["name"] for tag in pool["tags"]]
167 pool["artist_tags"] = [tag["name"] for tag in pool["artist_tags"]]
168
169 self._posts = pool.pop("posts")
170 for num, post in enumerate(self._posts, 1):
171 post["num"] = num
172
173 return {"pool": pool}
174
175 def posts(self):
176 return self._posts
177
178
179 class SankakuPostExtractor(SankakuExtractor):
180 """Extractor for single posts from sankaku.app"""
181 subcategory = "post"
182 archive_fmt = "{id}"
183 pattern = BASE_PATTERN + r"/posts?(?:/show)?/(\w+)"
184 example = "https://sankaku.app/post/show/12345"
185
186 def posts(self):
187 return self.api.posts(self.groups[0])
188
189
190 class SankakuBooksExtractor(SankakuExtractor):
191 """Extractor for books by tag search on sankaku.app"""
192 subcategory = "books"
193 pattern = BASE_PATTERN + r"/books/?\?([^#]*)"
194 example = "https://sankaku.app/books?tags=TAG"
195
196 def __init__(self, match):
197 SankakuExtractor.__init__(self, match)
198 query = text.parse_query(match[1])
199 self.tags = text.unquote(query.get("tags", "").replace("+", " "))
200
201 def items(self):
202 params = {"tags": self.tags, "pool_type": "0"}
203 for pool in self.api.pools_keyset(params):
204 pool["_extractor"] = SankakuPoolExtractor
205 url = "https://sankaku.app/books/" + pool["id"]
206 yield Message.Queue, url, pool
207
208
209 class SankakuAPI():
210 """Interface for the sankaku.app API"""
211 ROOT = "https://sankakuapi.com"
212 VERSION = None
213
214 def __init__(self, extractor):
215 self.extractor = extractor
216 self.headers = {
217 "Accept" : "application/vnd.sankaku.api+json;v=2",
218 "Api-Version": self.VERSION,
219 "Origin" : extractor.root,
220 }
221
222 self.username, self.password = extractor._get_auth_info()
223 if not self.username:
224 self.authenticate = util.noop
225
226 def notes(self, post_id):
227 params = {"lang": "en"}
228 return self._call(f"/posts/{post_id}/notes", params)
229
230 def tags(self, post_id):
231 endpoint = f"/posts/{post_id}/tags"
232 params = {
233 "lang" : "en",
234 "page" : 1,
235 "limit": 100,
236 }
237
238 tags = None
239 while True:
240 data = self._call(endpoint, params)
241
242 tags_new = data["data"]
243 if not tags_new:
244 return tags or []
245 elif tags is None:
246 tags = tags_new
247 else:
248 tags.extend(tags_new)
249
250 if len(tags_new) < 80 or len(tags) >= data["total"]:
251 return tags
252 params["page"] += 1
253
254 def pools(self, pool_id):
255 params = {"lang": "en"}
256 return self._call("/pools/" + pool_id, params)
257
258 def pools_keyset(self, params):
259 return self._pagination("/pools/keyset", params)
260
261 def pools_series(self, params):
262 params_ = {
263 "lang" : "en",
264 "filledPools": "true",
265 "includes[]" : "pools",
266 }
267 params_.update(params)
268 return self._pagination("/poolseriesv2", params)
269
270 def posts(self, post_id):
271 params = {
272 "lang" : "en",
273 "page" : "1",
274 "limit": "1",
275 "tags" : ("md5:" if len(post_id) == 32 else "id_range:") + post_id,
276 }
277 return self._call("/v2/posts", params)
278
279 def posts_keyset(self, params):
280 return self._pagination("/v2/posts/keyset", params)
281
282 def users_blacklist(self):
283 endpoint = "/users/blacklist"
284 params = {
285 "entity": "tags",
286 "lang" : "en",
287 "page" : 1,
288 "limit" : 100,
289 }
290
291 results = []
292 while True:
293 data = self._call(endpoint, params)
294
295 if items := data.get("list"):
296 for result in items:
297 results.append(" ".join(result["tags"]))
298
299 if len(items) < params["limit"]:
300 break
301 params["page"] += 1
302 return results
303
304 def authenticate(self):
305 self.headers["Authorization"] = self.extractor.cache(
306 self._authenticate_impl, self.username, self.password,
307 _exp=365*86400, _mem=False)
308
309 def _authenticate_impl(self, username, password):
310 self.extractor.log.info("Logging in as %s", username)
311
312 self.headers["Authorization"] = None
313 url = self.ROOT + "/auth/token"
314 data = {"login": username, "password": password}
315
316 response = self.extractor.request(
317 url, method="POST", headers=self.headers, json=data, fatal=False)
318 data = response.json()
319
320 if response.status_code >= 400 or not data.get("success"):
321 raise self.extractor.exc.AuthenticationError(data.get("error"))
322 return "Bearer " + data["access_token"]
323
324 def _call(self, endpoint, params=None):
325 url = self.ROOT + endpoint
326 for _ in range(5):
327 self.authenticate()
328 response = self.extractor.request(
329 url, params=params, headers=self.headers, fatal=None)
330
331 if response.status_code == 429:
332 until = response.headers.get("X-RateLimit-Reset")
333 if not until and b"_tags-explicit-limit" in response.content:
334 raise self.extractor.exc.AuthorizationError(
335 "Search tag limit exceeded")
336 seconds = None if until else 600
337 self.extractor.wait(until=until, seconds=seconds)
338 continue
339
340 data = response.json()
341 try:
342 success = data.get("success", True)
343 except AttributeError:
344 success = True
345 if not success:
346 code = data.get("code")
347 if code and code.endswith(
348 ("unauthorized", "invalid-token", "invalid_token")):
349 self.extractor.cache_update(
350 self._authenticate_impl, self.username)
351 continue
352 try:
353 code = code.rpartition(
354 "__")[2].replace("-", " ").replace("_", " ")
355 code = f"'{code}'"
356 except Exception:
357 pass
358 raise self.extractor.exc.AbortExtraction(code)
359 return data
360
361 def _pagination(self, endpoint, params):
362 params["lang"] = "en"
363 params["limit"] = str(self.extractor.per_page)
364
365 if refresh := self.extractor.config("refresh", False):
366 offset = expires = 0
367 from time import time
368
369 while True:
370 data = self._call(endpoint, params)
371
372 if refresh:
373 posts = data["data"]
374 if offset:
375 posts = util.advance(posts, offset)
376
377 for post in posts:
378 if not expires:
379 if url := post["file_url"]:
380 expires = text.parse_int(
381 text.extr(url, "e=", "&")) - 60
382
383 if 0 < expires <= time():
384 self.extractor.log.debug("Refreshing download URLs")
385 expires = None
386 break
387
388 offset += 1
389 yield post
390
391 if expires is None:
392 expires = 0
393 continue
394 offset = expires = 0
395
396 else:
397 yield from data["data"]
398
399 params["next"] = data["meta"]["next"]
400 if not params["next"]:
401 return