Debian Codegraph @

gallery_dl/extractor/rule34xyz.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2024-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://rule34.world/ and https://rule34.xyz/"""
10
11 from .booru import BooruExtractor
12 from .. import text
13 import collections
14
15 BASE_PATTERN = r"(?:https?://)?(?:www\.)?rule34\.(xyz|world)"
16
17
18 class Rule34xyzExtractor(BooruExtractor):
19 category = "rule34xyz"
20 root = "https://rule34.xyz"
21 root_cdn = "https://rule34xyz.b-cdn.net"
22 filename_fmt = "{category}_{id}.{extension}"
23 per_page = 60
24
25 TAG_TYPES = {
26 None: "general",
27 0 : "general",
28 1 : "general",
29 2 : "copyright",
30 4 : "character",
31 8 : "artist",
32 16 : "system",
33 32 : "meta",
34 }
35 FORMATS = {
36 "10" : "pic.jpg",
37 "100": "mov.mp4",
38 "101": "mov720.mp4",
39 "102": "mov480.mp4",
40 }
41
42 def __init__(self, match):
43 if match[1] == "world":
44 self.category = "rule34world"
45 self.root = "https://rule34.world"
46 self.root_cdn = "https://rule34storage.b-cdn.net"
47 BooruExtractor.__init__(self, match)
48
49 def _init(self):
50 if formats := self.config("format"):
51 if isinstance(formats, str):
52 formats = formats.split(",")
53 self.formats = formats
54 else:
55 self.formats = ("100", "101", "102", "10")
56
57 def _file_url(self, post):
58 files = post["files"]
59
60 for fmt in self.formats:
61 if fmt in files:
62 extension = self.FORMATS.get(fmt)
63 break
64 else:
65 self.log.warning("%s: Requested format not available", post["id"])
66 fmt = next(iter(files))
67
68 post_id = post["id"]
69 root = self.root_cdn if files[fmt][0] else self.root
70 post["file_url"] = url = \
71 f"{root}/posts/{post_id // 1000}/{post_id}/{post_id}.{extension}"
72 post["format_id"] = fmt
73 post["format"] = extension.partition(".")[0]
74
75 return url
76
77 def _prepare(self, post):
78 post.pop("files", None)
79 post["date"] = self.parse_datetime_iso(post["created"])
80 post["filename"], _, post["format"] = post["filename"].rpartition(".")
81 if "tags" in post:
82 post["tags"] = [t["value"] for t in post["tags"]]
83
84 def _tags(self, post, _):
85 if "tags" not in post:
86 post.update(self._fetch_post(post["id"]))
87
88 tags = collections.defaultdict(list)
89 for tag in post["tags"]:
90 tags[tag["type"]].append(tag["value"])
91 types = self.TAG_TYPES
92 for type, values in tags.items():
93 post["tags_" + types[type]] = values
94
95 def _fetch_post(self, post_id):
96 url = f"{self.root}/api/v2/post/{post_id}"
97 return self.request_json(url)
98
99 def _pagination(self, endpoint, params=None):
100 url = f"{self.root}/api{endpoint}"
101
102 if params is None:
103 params = {}
104 params["Skip"] = self.page_start * self.per_page
105 params["take"] = self.per_page
106 params["CountTotal"] = False
107 params["IncludeLinks"] = True
108 params["OrderBy"] = 0
109 threshold = self.per_page
110
111 while True:
112 data = self.request_json(url, method="POST", json=params)
113
114 yield from data["items"]
115
116 if len(data["items"]) < threshold:
117 return
118 params["Skip"] += self.per_page
119 params["cursor"] = data["cursor"]
120
121 def login(self):
122 username, password = self._get_auth_info()
123 if username:
124 self.session.headers["Authorization"] = self.cache(
125 self._login_impl, username, password,
126 _exp=3650*86400, _mem=False)
127
128 def _login_impl(self, username, password):
129 self.log.info("Logging in as %s", username)
130
131 url = self.root + "/api/v2/auth/signin"
132 data = {"email": username, "password": password}
133 response = self.request_json(
134 url, method="POST", json=data, fatal=False)
135
136 if jwt := response.get("jwt"):
137 return "Bearer " + jwt
138 raise self.exc.AuthenticationError(
139 (msg := response.get("message")) and f'"{msg}"')
140
141
142 class Rule34xyzPostExtractor(Rule34xyzExtractor):
143 subcategory = "post"
144 archive_fmt = "{id}"
145 pattern = BASE_PATTERN + r"/post/(\d+)"
146 example = "https://rule34.xyz/post/12345"
147
148 def posts(self):
149 return (self._fetch_post(self.groups[1]),)
150
151
152 class Rule34xyzPlaylistExtractor(Rule34xyzExtractor):
153 subcategory = "playlist"
154 directory_fmt = ("{category}", "{playlist_id}")
155 archive_fmt = "p_{playlist_id}_{id}"
156 pattern = BASE_PATTERN + r"/playlists/view/(\d+)"
157 example = "https://rule34.xyz/playlists/view/12345"
158
159 def metadata(self):
160 return {"playlist_id": self.groups[1]}
161
162 def posts(self):
163 endpoint = "/v2/post/search/playlist/" + self.groups[1]
164 return self._pagination(endpoint)
165
166
167 class Rule34xyzTagExtractor(Rule34xyzExtractor):
168 subcategory = "tag"
169 directory_fmt = ("{category}", "{search_tags}")
170 archive_fmt = "t_{search_tags}_{id}"
171 pattern = BASE_PATTERN + r"/([^/?#]+)$"
172 example = "https://rule34.xyz/TAG"
173
174 def metadata(self):
175 self.tags = text.unquote(text.unquote(
176 self.groups[1]).replace("_", " ")).split("|")
177 return {"search_tags": ", ".join(self.tags)}
178
179 def posts(self):
180 endpoint = "/v2/post/search/root"
181 params = {"includeTags": self.tags}
182 return self._pagination(endpoint, params)