| 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 Gelbooru Beta 0.2 sites""" |
| 10 |
|
| 11 |
from . import booru |
| 12 |
from .. import text, util |
| 13 |
import collections |
| 14 |
|
| 15 |
|
| 16 |
class GelbooruV02Extractor(booru.BooruExtractor): |
| 17 |
basecategory = "gelbooru_v02" |
| 18 |
|
| 19 |
def __init__(self, match): |
| 20 |
booru.BooruExtractor.__init__(self, match) |
| 21 |
self.request_interval = self.config_instance("request-interval", 0.0) |
| 22 |
self.root_api = self.config_instance("root-api") or self.root |
| 23 |
|
| 24 |
def _init(self): |
| 25 |
self.api_key = self.config("api-key") |
| 26 |
self.user_id = self.config("user-id") |
| 27 |
|
| 28 |
if self.category == "rule34": |
| 29 |
self._file_url = self._file_url_rule34 |
| 30 |
elif self.category == "hypnohub": |
| 31 |
self._file_url = self._file_url_hypnohub |
| 32 |
|
| 33 |
def import_blacklist(self): |
| 34 |
url = self.root + "/index.php?page=account&s=options" |
| 35 |
page = self.request(url).text |
| 36 |
tags = text.unescape(text.extr(page, "<textarea", "</textarea>")) |
| 37 |
return (tags[tags.find(">")+1:]).split() |
| 38 |
|
| 39 |
def _api_request(self, params): |
| 40 |
params["api_key"] = self.api_key |
| 41 |
params["user_id"] = self.user_id |
| 42 |
|
| 43 |
url = self.root_api + "/index.php?page=dapi&s=post&q=index" |
| 44 |
root = self.request_xml(url, params=params) |
| 45 |
|
| 46 |
if root.tag == "error": |
| 47 |
msg = root.text |
| 48 |
if msg.lower().startswith("missing authentication"): |
| 49 |
raise self.exc.AuthRequired( |
| 50 |
"'api-key' & 'user-id'", "the API", msg) |
| 51 |
raise self.exc.AbortExtraction(f"'{msg}'") |
| 52 |
|
| 53 |
return root |
| 54 |
|
| 55 |
def _pagination(self, params): |
| 56 |
params["pid"] = self.page_start |
| 57 |
params["limit"] = self.per_page |
| 58 |
|
| 59 |
post = total = None |
| 60 |
count = self.page_start * self.per_page |
| 61 |
|
| 62 |
while True: |
| 63 |
try: |
| 64 |
root = self._api_request(params) |
| 65 |
except SyntaxError: # ElementTree.ParseError |
| 66 |
if "tags" not in params or post is None: |
| 67 |
raise |
| 68 |
taglist = [tag for tag in params["tags"].split() |
| 69 |
if not tag.startswith("id:<")] |
| 70 |
taglist.append("id:<" + str(post.attrib["id"])) |
| 71 |
params["tags"] = " ".join(taglist) |
| 72 |
params["pid"] = 0 |
| 73 |
continue |
| 74 |
|
| 75 |
if total is None: |
| 76 |
try: |
| 77 |
self.kwdict["total"] = total = int(root.attrib["count"]) |
| 78 |
if "search_tags" in self.kwdict: |
| 79 |
self.kwdict["search_count"] = total |
| 80 |
self.log.debug("%s posts in total", total) |
| 81 |
except Exception as exc: |
| 82 |
total = 0 |
| 83 |
self.log.debug( |
| 84 |
"Failed to get total number of posts (%s: %s)", |
| 85 |
exc.__class__.__name__, exc) |
| 86 |
|
| 87 |
post = None |
| 88 |
for post in root: |
| 89 |
yield post.attrib |
| 90 |
|
| 91 |
num = len(root) |
| 92 |
count += num |
| 93 |
if num < self.per_page: |
| 94 |
if not total or count >= total: |
| 95 |
return |
| 96 |
if not num: |
| 97 |
self.log.debug("Empty response - Retrying") |
| 98 |
continue |
| 99 |
|
| 100 |
params["pid"] += 1 |
| 101 |
|
| 102 |
def _pagination_html(self, params): |
| 103 |
url = self.root + "/index.php" |
| 104 |
params["pid"] = self.page_start * self.per_page |
| 105 |
|
| 106 |
data = {} |
| 107 |
find_ids = text.re(r"\sid=\"p(\d+)").findall |
| 108 |
|
| 109 |
while True: |
| 110 |
page = self.request(url, params=params).text |
| 111 |
pids = find_ids(page) |
| 112 |
|
| 113 |
for data["id"] in pids: |
| 114 |
for post in self._api_request(data): |
| 115 |
yield post.attrib |
| 116 |
|
| 117 |
if len(pids) < self.per_page: |
| 118 |
return |
| 119 |
params["pid"] += self.per_page |
| 120 |
|
| 121 |
def _file_url_rule34(self, post): |
| 122 |
url = post["file_url"] |
| 123 |
|
| 124 |
if text.ext_from_url(url) not in util.EXTS_VIDEO: |
| 125 |
path = url.partition(".")[2] |
| 126 |
post["_fallback"] = (url,) |
| 127 |
post["file_url"] = url = "https://wimg." + path |
| 128 |
|
| 129 |
return url |
| 130 |
|
| 131 |
def _file_url_hypnohub(self, post): |
| 132 |
url = post["file_url"] |
| 133 |
return f"{url[:20]}/{url[20:]}" |
| 134 |
|
| 135 |
def _prepare(self, post): |
| 136 |
post["tags"] = post["tags"].strip() |
| 137 |
post["date"] = self.parse_datetime( |
| 138 |
post["created_at"], "%a %b %d %H:%M:%S %z %Y") |
| 139 |
|
| 140 |
def _html(self, post): |
| 141 |
url = f"{self.root}/index.php?page=post&s=view&id={post['id']}" |
| 142 |
return self.request(url).text |
| 143 |
|
| 144 |
def _tags(self, post, page): |
| 145 |
tag_container = (text.extr(page, '<ul id="tag-', '</ul>') or |
| 146 |
text.extr(page, '<ul class="tag-', '</ul>')) |
| 147 |
if not tag_container: |
| 148 |
return |
| 149 |
|
| 150 |
tags = collections.defaultdict(list) |
| 151 |
pattern = text.re(r"(?s)tag-type-([^\"' ]+).*?[?;]tags=([^\"'&]+)") |
| 152 |
for tag_type, tag_name in pattern.findall(tag_container): |
| 153 |
tags[tag_type].append(text.unescape(text.unquote(tag_name))) |
| 154 |
for key, value in tags.items(): |
| 155 |
post["tags_" + key] = " ".join(value) |
| 156 |
|
| 157 |
def _notes(self, post, page): |
| 158 |
note_container = text.extr(page, 'id="note-container"', "<img ") |
| 159 |
if not note_container: |
| 160 |
return |
| 161 |
|
| 162 |
post["notes"] = notes = [] |
| 163 |
for note in note_container.split('class="note-box"')[1:]: |
| 164 |
extr = text.extract_from(note) |
| 165 |
notes.append({ |
| 166 |
"width" : int(extr("width:", "p")), |
| 167 |
"height": int(extr("height:", "p")), |
| 168 |
"y" : int(extr("top:", "p")), |
| 169 |
"x" : int(extr("left:", "p")), |
| 170 |
"id" : int(extr('id="note-body-', '"')), |
| 171 |
"body" : text.unescape(text.remove_html(extr(">", "</div>"))), |
| 172 |
}) |
| 173 |
|
| 174 |
|
| 175 |
BASE_PATTERN = GelbooruV02Extractor.update({ |
| 176 |
"rule34": { |
| 177 |
"root": "https://rule34.xxx", |
| 178 |
"root-api": "https://api.rule34.xxx", |
| 179 |
"request-interval": 1.0, |
| 180 |
"pattern": r"(?:www\.)?rule34\.xxx", |
| 181 |
}, |
| 182 |
"safebooru": { |
| 183 |
"root": "https://safebooru.org", |
| 184 |
"pattern": r"safebooru\.org", |
| 185 |
}, |
| 186 |
"tbib": { |
| 187 |
"root": "https://tbib.org", |
| 188 |
"pattern": r"tbib\.org", |
| 189 |
}, |
| 190 |
"hypnohub": { |
| 191 |
"root": "https://hypnohub.net", |
| 192 |
"pattern": r"hypnohub\.net", |
| 193 |
}, |
| 194 |
"xbooru": { |
| 195 |
"root": "https://xbooru.com", |
| 196 |
"pattern": r"xbooru\.com", |
| 197 |
}, |
| 198 |
}) |
| 199 |
|
| 200 |
|
| 201 |
class GelbooruV02TagExtractor(GelbooruV02Extractor): |
| 202 |
subcategory = "tag" |
| 203 |
directory_fmt = ("{category}", "{search_tags}") |
| 204 |
archive_fmt = "t_{search_tags}_{id}" |
| 205 |
pattern = BASE_PATTERN + r"/index\.php\?page=post&s=list&tags=([^&#]*)" |
| 206 |
example = "https://safebooru.org/index.php?page=post&s=list&tags=TAG" |
| 207 |
|
| 208 |
def posts(self): |
| 209 |
self.kwdict["search_tags"] = tags = text.unquote( |
| 210 |
self.groups[-1].replace("+", " ")) |
| 211 |
|
| 212 |
if tags == "all": |
| 213 |
tags = "" |
| 214 |
return self._pagination({"tags": tags}) |
| 215 |
|
| 216 |
|
| 217 |
class GelbooruV02PoolExtractor(GelbooruV02Extractor): |
| 218 |
subcategory = "pool" |
| 219 |
directory_fmt = ("{category}", "pool", "{pool}") |
| 220 |
archive_fmt = "p_{pool}_{id}" |
| 221 |
pattern = BASE_PATTERN + r"/index\.php\?page=pool&s=show&id=(\d+)" |
| 222 |
example = "https://safebooru.org/index.php?page=pool&s=show&id=12345" |
| 223 |
|
| 224 |
def __init__(self, match): |
| 225 |
GelbooruV02Extractor.__init__(self, match) |
| 226 |
self.pool_id = self.groups[-1] |
| 227 |
|
| 228 |
if self.category == "rule34": |
| 229 |
self.posts = self._posts_pages |
| 230 |
self.per_page = 45 |
| 231 |
else: |
| 232 |
self.post_ids = () |
| 233 |
|
| 234 |
def skip_files(self, num): |
| 235 |
self.page_start += num |
| 236 |
return num |
| 237 |
|
| 238 |
def metadata(self): |
| 239 |
url = f"{self.root}/index.php?page=pool&s=show&id={self.pool_id}" |
| 240 |
page = self.request(url).text |
| 241 |
|
| 242 |
name, pos = text.extract(page, "<h4>Pool: ", "</h4>") |
| 243 |
if not name: |
| 244 |
raise self.exc.NotFoundError("pool") |
| 245 |
self.post_ids = text.extract_iter( |
| 246 |
page, 'class="thumb" id="p', '"', pos) |
| 247 |
|
| 248 |
return { |
| 249 |
"pool": text.parse_int(self.pool_id), |
| 250 |
"pool_name": text.unescape(name), |
| 251 |
} |
| 252 |
|
| 253 |
def posts(self): |
| 254 |
params = {} |
| 255 |
for params["id"] in util.advance(self.post_ids, self.page_start): |
| 256 |
for post in self._api_request(params): |
| 257 |
yield post.attrib |
| 258 |
|
| 259 |
def _posts_pages(self): |
| 260 |
return self._pagination_html({ |
| 261 |
"page": "pool", |
| 262 |
"s" : "show", |
| 263 |
"id" : self.pool_id, |
| 264 |
}) |
| 265 |
|
| 266 |
|
| 267 |
class GelbooruV02FavoriteExtractor(GelbooruV02Extractor): |
| 268 |
subcategory = "favorite" |
| 269 |
directory_fmt = ("{category}", "favorites", "{favorite_id}") |
| 270 |
archive_fmt = "f_{favorite_id}_{id}" |
| 271 |
per_page = 50 |
| 272 |
pattern = BASE_PATTERN + r"/index\.php\?page=favorites&s=view&id=(\d+)" |
| 273 |
example = "https://safebooru.org/index.php?page=favorites&s=view&id=12345" |
| 274 |
|
| 275 |
def metadata(self): |
| 276 |
self.favorite_id = fav_id = self.groups[-1] |
| 277 |
return {"favorite_id": text.parse_int(fav_id)} |
| 278 |
|
| 279 |
def posts(self): |
| 280 |
return self._pagination_html({ |
| 281 |
"page": "favorites", |
| 282 |
"s" : "view", |
| 283 |
"id" : self.favorite_id, |
| 284 |
}) |
| 285 |
|
| 286 |
|
| 287 |
class GelbooruV02PostExtractor(GelbooruV02Extractor): |
| 288 |
subcategory = "post" |
| 289 |
archive_fmt = "{id}" |
| 290 |
pattern = BASE_PATTERN + r"/index\.php\?page=post&s=view&id=(\d+)" |
| 291 |
example = "https://safebooru.org/index.php?page=post&s=view&id=12345" |
| 292 |
|
| 293 |
def posts(self): |
| 294 |
return self._pagination({"id": self.groups[-1]}) |