| 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://e-hentai.org/ and https://exhentai.org/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text, util |
| 13 |
import collections |
| 14 |
import itertools |
| 15 |
import math |
| 16 |
|
| 17 |
BASE_PATTERN = r"(?:https?://)?(e[x-]|g\.e-)hentai\.org" |
| 18 |
|
| 19 |
|
| 20 |
class ExhentaiExtractor(Extractor): |
| 21 |
"""Base class for exhentai extractors""" |
| 22 |
category = "exhentai" |
| 23 |
directory_fmt = ("{category}", "{gid} {title[:247]}") |
| 24 |
filename_fmt = "{gid}_{num:>04}_{image_token}_{filename}.{extension}" |
| 25 |
archive_fmt = "{gid}_{num}" |
| 26 |
cookies_domain = ".exhentai.org" |
| 27 |
cookies_names = ("ipb_member_id", "ipb_pass_hash") |
| 28 |
root = "https://exhentai.org" |
| 29 |
request_interval = (3.0, 6.0) |
| 30 |
ciphers = "DEFAULT:!DH" |
| 31 |
|
| 32 |
LIMIT = False |
| 33 |
|
| 34 |
def __init__(self, match): |
| 35 |
Extractor.__init__(self, match) |
| 36 |
self.version = match[1] |
| 37 |
|
| 38 |
def initialize(self): |
| 39 |
domain = self.config("domain", "auto") |
| 40 |
if domain == "auto": |
| 41 |
domain = ("ex" if self.version == "ex" else "e-") + "hentai.org" |
| 42 |
self.root = "https://" + domain |
| 43 |
self.api_url = self.root + "/api.php" |
| 44 |
self.cookies_domain = "." + domain |
| 45 |
|
| 46 |
Extractor.initialize(self) |
| 47 |
|
| 48 |
if self.version != "ex": |
| 49 |
self.cookies.set("nw", "1", domain=self.cookies_domain) |
| 50 |
|
| 51 |
def request(self, url, **kwargs): |
| 52 |
response = Extractor.request(self, url, **kwargs) |
| 53 |
if "Cache-Control" not in response.headers and not response.content: |
| 54 |
self.log.info("blank page") |
| 55 |
raise self.exc.AuthorizationError() |
| 56 |
return response |
| 57 |
|
| 58 |
def login(self): |
| 59 |
"""Login and set necessary cookies""" |
| 60 |
if self.LIMIT: |
| 61 |
raise self.exc.AbortExtraction("Image limit reached!") |
| 62 |
|
| 63 |
if self.cookies_check(self.cookies_names): |
| 64 |
return |
| 65 |
|
| 66 |
username, password = self._get_auth_info() |
| 67 |
if username: |
| 68 |
return self.cookies_update(self.cache( |
| 69 |
self._login_impl, username, password, |
| 70 |
_exp=90*86400, _mem=False)) |
| 71 |
|
| 72 |
if self.version == "ex": |
| 73 |
self.log.info("No username or cookies given; using e-hentai.org") |
| 74 |
self.root = "https://e-hentai.org" |
| 75 |
self.cookies_domain = ".e-hentai.org" |
| 76 |
self.cookies.set("nw", "1", domain=self.cookies_domain) |
| 77 |
self.original = False |
| 78 |
self.limits = False |
| 79 |
|
| 80 |
def _login_impl(self, username, password): |
| 81 |
self.log.info("Logging in as %s", username) |
| 82 |
|
| 83 |
url = "https://forums.e-hentai.org/index.php?act=Login&CODE=01" |
| 84 |
headers = { |
| 85 |
"Referer": "https://e-hentai.org/bounce_login.php?b=d&bt=1-1", |
| 86 |
} |
| 87 |
data = { |
| 88 |
"CookieDate": "1", |
| 89 |
"b": "d", |
| 90 |
"bt": "1-1", |
| 91 |
"UserName": username, |
| 92 |
"PassWord": password, |
| 93 |
"ipb_login_submit": "Login!", |
| 94 |
} |
| 95 |
|
| 96 |
self.cookies.clear() |
| 97 |
|
| 98 |
response = self.request(url, method="POST", headers=headers, data=data) |
| 99 |
content = response.content |
| 100 |
if b"You are now logged in as:" not in content: |
| 101 |
if b"The captcha was not entered correctly" in content: |
| 102 |
raise self.exc.AuthenticationError( |
| 103 |
"CAPTCHA required. Use cookies instead.") |
| 104 |
raise self.exc.AuthenticationError() |
| 105 |
|
| 106 |
# collect more cookies |
| 107 |
url = self.root + "/favorites.php" |
| 108 |
response = self.request(url) |
| 109 |
if response.history: |
| 110 |
self.request(url) |
| 111 |
|
| 112 |
return self.cookies |
| 113 |
|
| 114 |
|
| 115 |
class ExhentaiGalleryExtractor(ExhentaiExtractor): |
| 116 |
"""Extractor for image galleries from exhentai.org""" |
| 117 |
subcategory = "gallery" |
| 118 |
pattern = (BASE_PATTERN + |
| 119 |
r"(?:/(?:g|mpv)/(\d+)/([0-9a-f]{10})(?:/#page(\d+))?" |
| 120 |
r"|/s/([0-9a-f]{10})/(\d+)-(\d+))") |
| 121 |
example = "https://e-hentai.org/g/12345/67890abcde/" |
| 122 |
|
| 123 |
def __init__(self, match): |
| 124 |
ExhentaiExtractor.__init__(self, match) |
| 125 |
self.gallery_id = text.parse_int(match[2] or match[6]) |
| 126 |
self.gallery_token = match[3] |
| 127 |
self.image_token = match[5] |
| 128 |
self.image_num = text.parse_int(match[4] or match[7], 1) |
| 129 |
self.key_start = None |
| 130 |
self.key_show = None |
| 131 |
self.key_next = None |
| 132 |
self.count = 0 |
| 133 |
self.data = None |
| 134 |
self.mpv = False |
| 135 |
|
| 136 |
def _init(self): |
| 137 |
source = self.config("source") |
| 138 |
if source == "hitomi": |
| 139 |
self.items = self._items_hitomi |
| 140 |
elif source == "metadata": |
| 141 |
self.items = self._items_metadata |
| 142 |
elif source == "torrent": |
| 143 |
self.items = self._items_torrents |
| 144 |
|
| 145 |
limits = self.config("limits", False) |
| 146 |
if limits and limits.__class__ is int: |
| 147 |
self.limits = limits |
| 148 |
self._limits_remaining = 0 |
| 149 |
else: |
| 150 |
self.limits = False |
| 151 |
|
| 152 |
self.fallback_retries = self.config("fallback-retries", 2) |
| 153 |
self.original = self.config("original", True) |
| 154 |
|
| 155 |
def finalize(self, status): |
| 156 |
if not status or not self.data: |
| 157 |
return |
| 158 |
|
| 159 |
if self.mpv: |
| 160 |
self.log.info("Use '%s/mpv/%s/%s/#page%s' as input URL " |
| 161 |
"to continue downloading from the current position", |
| 162 |
self.root, self.gallery_id, self.gallery_token, |
| 163 |
self.data["num"]) |
| 164 |
elif token := self.data.get("image_token"): |
| 165 |
self.log.info("Use '%s/s/%s/%s-%s' as input URL " |
| 166 |
"to continue downloading from the current position", |
| 167 |
self.root, token, self.gallery_id, self.data["num"]) |
| 168 |
|
| 169 |
def favorite(self, slot="0"): |
| 170 |
url = self.root + "/gallerypopups.php" |
| 171 |
params = { |
| 172 |
"gid": self.gallery_id, |
| 173 |
"t" : self.gallery_token, |
| 174 |
"act": "addfav", |
| 175 |
} |
| 176 |
data = { |
| 177 |
"favcat" : slot, |
| 178 |
"apply" : "Apply Changes", |
| 179 |
"update" : "1", |
| 180 |
} |
| 181 |
self.request(url, method="POST", params=params, data=data) |
| 182 |
|
| 183 |
def items(self): |
| 184 |
self.login() |
| 185 |
|
| 186 |
if self.gallery_token: |
| 187 |
gpage = self._gallery_page() |
| 188 |
if not self.mpv: |
| 189 |
self.image_token = text.extr(gpage, 'hentai.org/s/', '"') |
| 190 |
if not self.image_token: |
| 191 |
self.log.debug("Page content:\n%s", gpage) |
| 192 |
raise self.exc.AbortExtraction( |
| 193 |
"Failed to extract initial image token") |
| 194 |
ipage = self._image_page() |
| 195 |
else: |
| 196 |
ipage = self._image_page() |
| 197 |
part = text.extr(ipage, 'hentai.org/g/', '"') |
| 198 |
if not part: |
| 199 |
self.log.debug("Page content:\n%s", ipage) |
| 200 |
raise self.exc.AbortExtraction( |
| 201 |
"Failed to extract gallery token") |
| 202 |
self.gallery_token = part.split("/")[1] |
| 203 |
gpage = self._gallery_page() |
| 204 |
|
| 205 |
self.data = data = self.get_metadata(gpage) |
| 206 |
self.count = text.parse_int(data["filecount"]) |
| 207 |
yield Message.Directory, "", data |
| 208 |
|
| 209 |
if self.mpv: |
| 210 |
images = self.images_from_mpv() |
| 211 |
else: |
| 212 |
images = itertools.chain( |
| 213 |
(self.image_from_page(ipage),), self.images_from_api()) |
| 214 |
|
| 215 |
for url, image in images: |
| 216 |
data.update(image) |
| 217 |
if self.limits: |
| 218 |
self._limits_check(data) |
| 219 |
if "/fullimg" in url: |
| 220 |
data["_http_validate"] = self._validate_response |
| 221 |
else: |
| 222 |
data["_http_validate"] = None |
| 223 |
data["_http_signature"] = self._validate_signature |
| 224 |
yield Message.Url, url, data |
| 225 |
|
| 226 |
fav = self.config("fav") |
| 227 |
if fav is not None: |
| 228 |
self.favorite(fav) |
| 229 |
self.data = None |
| 230 |
|
| 231 |
def _items_hitomi(self): |
| 232 |
if self.config("metadata", False): |
| 233 |
data = self.metadata_from_api() |
| 234 |
else: |
| 235 |
data = {} |
| 236 |
|
| 237 |
from .hitomi import HitomiGalleryExtractor |
| 238 |
url = f"https://hitomi.la/galleries/{self.gallery_id}.html" |
| 239 |
data["_extractor"] = HitomiGalleryExtractor |
| 240 |
yield Message.Queue, url, data |
| 241 |
|
| 242 |
def _items_metadata(self): |
| 243 |
yield Message.Directory, "", self.metadata_from_api(update=False) |
| 244 |
|
| 245 |
def _items_torrents(self): |
| 246 |
data = self.metadata_from_api() |
| 247 |
torrents = data.get("torrents") or () |
| 248 |
data["count"] = len(torrents) |
| 249 |
yield Message.Directory, "", data |
| 250 |
|
| 251 |
base = (f"https://ehtracker.org/get/{data['gid']}/" |
| 252 |
if self.root[9] == "-" else |
| 253 |
f"{self.root}/torrent/") |
| 254 |
|
| 255 |
data["extension"] = "torrent" |
| 256 |
for data["num"], torrent in enumerate(torrents, 1): |
| 257 |
data.update(torrent) |
| 258 |
data["date"] = self.parse_timestamp(torrent["added"]) |
| 259 |
data["filename"] = data["name"] |
| 260 |
data["image_token"] = data["hash"][:10] |
| 261 |
data["_fallback"] = self._fallback_torrent(data) |
| 262 |
url = f"{base}{data['gid']}/{data['hash']}.torrent" |
| 263 |
yield Message.Url, url, data |
| 264 |
|
| 265 |
def _fallback_torrent(self, data): |
| 266 |
url = (f"{self.root}/gallerytorrents.php" |
| 267 |
f"?gid={data['gid']}&t={data['token']}") |
| 268 |
tpage = self.request(url).text |
| 269 |
yield text.unescape(text.iextr(tpage, data["hash"], '"', '"')) |
| 270 |
|
| 271 |
def get_metadata(self, page): |
| 272 |
"""Extract gallery metadata""" |
| 273 |
data = self.metadata_from_page(page) |
| 274 |
if self.config("metadata", False): |
| 275 |
data.update(self.metadata_from_api()) |
| 276 |
if self.config("tags", True): |
| 277 |
tags = collections.defaultdict(list) |
| 278 |
for tag in data["tags"]: |
| 279 |
type, _, value = tag.partition(":") |
| 280 |
tags[type].append(value) |
| 281 |
for type, values in tags.items(): |
| 282 |
data["tags_" + type] = values |
| 283 |
return data |
| 284 |
|
| 285 |
def metadata_from_page(self, page): |
| 286 |
extr = text.extract_from(page) |
| 287 |
|
| 288 |
if api_url := extr('var api_url = "', '"'): |
| 289 |
self.api_url = api_url |
| 290 |
|
| 291 |
data = { |
| 292 |
"gid" : self.gallery_id, |
| 293 |
"token" : self.gallery_token, |
| 294 |
"thumb" : extr("background:transparent url(", ")"), |
| 295 |
"title" : text.unescape(extr('<h1 id="gn">', '</h1>')), |
| 296 |
"title_jpn" : text.unescape(extr('<h1 id="gj">', '</h1>')), |
| 297 |
"_" : extr('<div id="gdc"><div class="cs ct', '"'), |
| 298 |
"eh_category" : extr('>', '<'), |
| 299 |
"uploader" : extr('<div id="gdn">', '</div>'), |
| 300 |
"date" : self.parse_datetime_iso(extr( |
| 301 |
'>Posted:</td><td class="gdt2">', '</td>')), |
| 302 |
"parent" : extr( |
| 303 |
'>Parent:</td><td class="gdt2"><a href="', '"'), |
| 304 |
"expunged" : "Yes" != extr( |
| 305 |
'>Visible:</td><td class="gdt2">', '<'), |
| 306 |
"language" : extr('>Language:</td><td class="gdt2">', ' '), |
| 307 |
"filesize" : text.parse_bytes(extr( |
| 308 |
'>File Size:</td><td class="gdt2">', '<').rstrip("Bbi")), |
| 309 |
"filecount" : extr('>Length:</td><td class="gdt2">', ' '), |
| 310 |
"favorites" : extr('id="favcount">', ' '), |
| 311 |
"rating" : extr(">Average: ", "<"), |
| 312 |
"torrentcount" : extr('>Torrent Download (', ')'), |
| 313 |
} |
| 314 |
|
| 315 |
uploader = data["uploader"] |
| 316 |
if uploader and uploader[0] == "<": |
| 317 |
data["uploader"] = text.unescape(text.extr(uploader, ">", "<")) |
| 318 |
|
| 319 |
f = data["favorites"][0] |
| 320 |
if f == "N": |
| 321 |
data["favorites"] = "0" |
| 322 |
elif f == "O": |
| 323 |
data["favorites"] = "1" |
| 324 |
|
| 325 |
data["lang"] = util.language_to_code(data["language"]) |
| 326 |
data["tags"] = [ |
| 327 |
text.unquote(tag.replace("+", " ")) |
| 328 |
for tag in text.extract_iter(page, 'hentai.org/tag/', '"') |
| 329 |
] |
| 330 |
|
| 331 |
return data |
| 332 |
|
| 333 |
def metadata_from_api(self, update=True): |
| 334 |
data = { |
| 335 |
"method" : "gdata", |
| 336 |
"gidlist" : ((self.gallery_id, self.gallery_token),), |
| 337 |
"namespace": 1, |
| 338 |
} |
| 339 |
|
| 340 |
data = self.request_json(self.api_url, method="POST", json=data) |
| 341 |
if "error" in data: |
| 342 |
raise self.exc.AbortExtraction(data["error"]) |
| 343 |
|
| 344 |
data = data["gmetadata"][0] |
| 345 |
if update: |
| 346 |
data["date"] = self.parse_timestamp(data["posted"]) |
| 347 |
data["title"] = text.unescape(data["title"]) |
| 348 |
return data |
| 349 |
|
| 350 |
def image_from_page(self, page): |
| 351 |
"""Get image url and data from webpage""" |
| 352 |
extr = text.extract_from(page) |
| 353 |
|
| 354 |
self.key_start = extr('var startkey="', '";') |
| 355 |
self.key_show = extr('var showkey="', '";') |
| 356 |
extr('<div id="i3"><a onclick="return load_image(', "") |
| 357 |
self.key_next = extr("'", "'") |
| 358 |
|
| 359 |
iurl = extr('<img id="img" src="', '"') |
| 360 |
nl = extr(" nl(", ")").strip("\"'") |
| 361 |
orig = extr('hentai.org/fullimg', '"') |
| 362 |
|
| 363 |
try: |
| 364 |
if self.original and orig: |
| 365 |
url = self.root + "/fullimg" + text.unescape(orig) |
| 366 |
data = self._parse_original_info(extr('ownload original', '<')) |
| 367 |
data["_fallback"] = self._fallback_original(nl, url) |
| 368 |
else: |
| 369 |
url = iurl |
| 370 |
data = self._parse_image_info(url) |
| 371 |
data["_fallback"] = self._fallback_1280(nl, self.image_num) |
| 372 |
except IndexError: |
| 373 |
self.log.debug("Page content:\n%s", page) |
| 374 |
raise self.exc.AbortExtraction( |
| 375 |
f"Unable to parse image info for '{url}'") |
| 376 |
|
| 377 |
data["num"] = self.image_num |
| 378 |
data["image_token"] = self.key_start |
| 379 |
data["_url_1280"] = iurl |
| 380 |
data["_nl"] = nl |
| 381 |
|
| 382 |
self._check_509(iurl) |
| 383 |
return url, text.nameext_from_url(url, data) |
| 384 |
|
| 385 |
def images_from_api(self): |
| 386 |
"""Get image url and data from api calls""" |
| 387 |
api_url = self.api_url |
| 388 |
nextkey = self.key_next |
| 389 |
request = { |
| 390 |
"method" : "showpage", |
| 391 |
"gid" : self.gallery_id, |
| 392 |
"page" : 0, |
| 393 |
"imgkey" : nextkey, |
| 394 |
"showkey": self.key_show, |
| 395 |
} |
| 396 |
|
| 397 |
for request["page"] in range(self.image_num + 1, self.count + 1): |
| 398 |
page = self.request_json(api_url, method="POST", json=request) |
| 399 |
|
| 400 |
i3 = page["i3"] |
| 401 |
i6 = page["i6"] |
| 402 |
|
| 403 |
imgkey = nextkey |
| 404 |
nextkey, pos = text.extract(i3, "'", "'") |
| 405 |
imgurl , pos = text.extract(i3, 'id="img" src="', '"', pos) |
| 406 |
nl , pos = text.extract(i3, " nl(", ")", pos) |
| 407 |
nl = (nl or "").strip("\"'") |
| 408 |
|
| 409 |
try: |
| 410 |
pos = i6.find("hentai.org/fullimg") |
| 411 |
if self.original and pos >= 0: |
| 412 |
origurl, pos = text.rextract(i6, '"', '"', pos) |
| 413 |
url = text.unescape(origurl) |
| 414 |
data = self._parse_original_info(text.extract( |
| 415 |
i6, "ownload original", "<", pos)[0]) |
| 416 |
data["_fallback"] = self._fallback_original(nl, url) |
| 417 |
else: |
| 418 |
url = imgurl |
| 419 |
data = self._parse_image_info(url) |
| 420 |
data["_fallback"] = self._fallback_1280( |
| 421 |
nl, request["page"], imgkey) |
| 422 |
except IndexError: |
| 423 |
self.log.debug("Page content:\n%s", page) |
| 424 |
raise self.exc.AbortExtraction( |
| 425 |
f"Unable to parse image info for '{url}'") |
| 426 |
|
| 427 |
data["num"] = request["page"] |
| 428 |
data["image_token"] = imgkey |
| 429 |
data["_url_1280"] = imgurl |
| 430 |
data["_nl"] = nl |
| 431 |
|
| 432 |
self._check_509(imgurl) |
| 433 |
yield url, text.nameext_from_url(url, data) |
| 434 |
|
| 435 |
request["imgkey"] = nextkey |
| 436 |
|
| 437 |
def images_from_mpv(self): |
| 438 |
"""Get image url and data from MPV""" |
| 439 |
url = f"{self.root}/mpv/{self.gallery_id}/{self.gallery_token}/" |
| 440 |
page = self.request(url).text |
| 441 |
images = util.json_loads(text.extr(page, "var imagelist = ", ";")) |
| 442 |
|
| 443 |
api_url = self.api_url |
| 444 |
pnum = self.image_num - 1 |
| 445 |
request = { |
| 446 |
"method": "imagedispatch", |
| 447 |
"gid" : self.gallery_id, |
| 448 |
"page" : 0, |
| 449 |
"imgkey": "", |
| 450 |
"mpvkey": text.extr(page, 'var mpvkey = "', '"'), |
| 451 |
} |
| 452 |
|
| 453 |
if pnum: |
| 454 |
images = util.advance(images, pnum) |
| 455 |
for image in images: |
| 456 |
pnum += 1 |
| 457 |
request["page"] = pnum |
| 458 |
request["imgkey"] = imgkey = image["k"] |
| 459 |
info = self.request_json(api_url, method="POST", json=request) |
| 460 |
|
| 461 |
try: |
| 462 |
imgurl = info["i"] |
| 463 |
if self.original and info.get("o") and " " in info["o"]: |
| 464 |
url = f"{self.root}/{info['lf']}" |
| 465 |
try: |
| 466 |
data = self._parse_mpv_info(info) |
| 467 |
except ValueError: |
| 468 |
self.log.warning( |
| 469 |
"Failed to extract original file metadata") |
| 470 |
data = self._parse_image_info(imgurl) |
| 471 |
data["_fallback"] = self._fallback_mpv_original(info) |
| 472 |
else: |
| 473 |
url = imgurl |
| 474 |
data = self._parse_image_info(url) |
| 475 |
data["_fallback"] = self._fallback_mpv_1280(info, request) |
| 476 |
except IndexError: |
| 477 |
self.log.debug("Page content:\n%s", info) |
| 478 |
raise self.exc.AbortExtraction( |
| 479 |
f"Unable to parse image info for '{url}'") |
| 480 |
|
| 481 |
data["num"] = pnum |
| 482 |
data["_nl"] = info["s"] |
| 483 |
data["_url_1280"] = imgurl |
| 484 |
data["image_token"] = imgkey |
| 485 |
|
| 486 |
self._check_509(imgurl) |
| 487 |
if name := image.get("name"): |
| 488 |
text.nameext_from_name(name, data) |
| 489 |
else: |
| 490 |
text.nameext_from_url(url, data) |
| 491 |
|
| 492 |
yield url, data |
| 493 |
|
| 494 |
def _validate_response(self, response): |
| 495 |
if response.history or not response.headers.get( |
| 496 |
"content-type", "").startswith("text/html"): |
| 497 |
return True |
| 498 |
|
| 499 |
page = response.text |
| 500 |
self.log.warning("'%s'", page) |
| 501 |
|
| 502 |
if " requires GP" in page: |
| 503 |
gp = self.config("gp") |
| 504 |
if gp == "stop": |
| 505 |
raise self.exc.AbortExtraction("Not enough GP") |
| 506 |
elif gp == "wait": |
| 507 |
self.input("Press ENTER to continue.") |
| 508 |
return response.url |
| 509 |
|
| 510 |
self.log.info("Falling back to non-original downloads") |
| 511 |
self.original = False |
| 512 |
return self.data["_url_1280"] |
| 513 |
|
| 514 |
if " temporarily banned " in page: |
| 515 |
raise self.exc.AuthorizationError("Temporarily Banned") |
| 516 |
|
| 517 |
self._limits_exceeded() |
| 518 |
return response.url |
| 519 |
|
| 520 |
def _validate_signature(self, signature): |
| 521 |
"""Return False if all file signature bytes are zero""" |
| 522 |
if signature: |
| 523 |
if byte := signature[0]: |
| 524 |
# 60 == b"<" |
| 525 |
if byte == 60 and b"<!doctype html".startswith( |
| 526 |
signature[:14].lower()): |
| 527 |
return "HTML response" |
| 528 |
return True |
| 529 |
for byte in signature: |
| 530 |
if byte: |
| 531 |
return True |
| 532 |
return False |
| 533 |
|
| 534 |
def _request_home(self, **kwargs): |
| 535 |
url = "https://e-hentai.org/home.php" |
| 536 |
kwargs["cookies"] = { |
| 537 |
cookie.name: cookie.value |
| 538 |
for cookie in self.cookies |
| 539 |
if cookie.domain == self.cookies_domain and |
| 540 |
cookie.name != "igneous" |
| 541 |
} |
| 542 |
page = self.request(url, **kwargs).text |
| 543 |
|
| 544 |
# update image limits |
| 545 |
current = text.extr(page, "<strong>", "</strong>").replace(",", "") |
| 546 |
self.log.debug("Image Limits: %s/%s", current, self.limits) |
| 547 |
self._limits_remaining = self.limits - text.parse_int(current) |
| 548 |
|
| 549 |
return page |
| 550 |
|
| 551 |
def _check_509(self, url): |
| 552 |
# full 509.gif URLs |
| 553 |
# - https://exhentai.org/img/509.gif |
| 554 |
# - https://ehgt.org/g/509.gif |
| 555 |
if url.endswith(("hentai.org/img/509.gif", |
| 556 |
"ehgt.org/g/509.gif")): |
| 557 |
self.log.debug(url) |
| 558 |
self._limits_exceeded() |
| 559 |
|
| 560 |
def _limits_exceeded(self): |
| 561 |
msg = "Image limit exceeded!" |
| 562 |
action = self.config("limits-action") |
| 563 |
|
| 564 |
if not action or action == "stop": |
| 565 |
ExhentaiExtractor.LIMIT = True |
| 566 |
raise self.exc.AbortExtraction(msg) |
| 567 |
|
| 568 |
self.log.warning(msg) |
| 569 |
if action == "wait": |
| 570 |
self.input("Press ENTER to continue.") |
| 571 |
self._limits_update() |
| 572 |
elif action == "reset": |
| 573 |
self._limits_reset() |
| 574 |
else: |
| 575 |
self.log.error("Invalid 'limits-action' value '%s'", action) |
| 576 |
|
| 577 |
def _limits_check(self, data): |
| 578 |
if not self._limits_remaining or data["num"] % 25 == 0: |
| 579 |
self._limits_update() |
| 580 |
self._limits_remaining -= data["cost"] |
| 581 |
if self._limits_remaining <= 0: |
| 582 |
self._limits_exceeded() |
| 583 |
|
| 584 |
def _limits_reset(self): |
| 585 |
self.log.info("Resetting image limits") |
| 586 |
self._request_home( |
| 587 |
method="POST", |
| 588 |
headers={"Content-Type": "application/x-www-form-urlencoded"}, |
| 589 |
data=b"reset_imagelimit=Reset+Quota") |
| 590 |
|
| 591 |
_limits_update = _request_home |
| 592 |
|
| 593 |
def _gallery_page(self): |
| 594 |
url = f"{self.root}/g/{self.gallery_id}/{self.gallery_token}/" |
| 595 |
response = self.request(url, fatal=False) |
| 596 |
page = response.text |
| 597 |
|
| 598 |
if response.status_code == 404 and "Gallery Not Available" in page: |
| 599 |
raise self.exc.AuthorizationError() |
| 600 |
if page.startswith(("Key missing", "Gallery not found")): |
| 601 |
raise self.exc.NotFoundError("gallery") |
| 602 |
if page.count("hentai.org/mpv/") > 1: |
| 603 |
if self.gallery_token is None: |
| 604 |
raise self.exc.AbortExtraction( |
| 605 |
"'/s/' URLs in MPV mode are not supported") |
| 606 |
self.mpv = True |
| 607 |
return page |
| 608 |
|
| 609 |
def _image_page(self): |
| 610 |
url = (f"{self.root}/s/{self.image_token}" |
| 611 |
f"/{self.gallery_id}-{self.image_num}") |
| 612 |
page = self.request(url, fatal=False).text |
| 613 |
|
| 614 |
if page.startswith(("Invalid page", "Keep trying")): |
| 615 |
raise self.exc.NotFoundError("image page") |
| 616 |
return page |
| 617 |
|
| 618 |
def _fallback_original(self, nl, fullimg): |
| 619 |
url = f"{fullimg}?nl={nl}" |
| 620 |
for _ in util.repeat(self.fallback_retries): |
| 621 |
yield url |
| 622 |
|
| 623 |
def _fallback_mpv_original(self, info): |
| 624 |
url = f"{self.root}/{info['lf']}?nl={info['s']}" |
| 625 |
for _ in util.repeat(self.fallback_retries): |
| 626 |
yield url |
| 627 |
|
| 628 |
def _fallback_1280(self, nl, num, token=None): |
| 629 |
if not token: |
| 630 |
token = self.key_start |
| 631 |
|
| 632 |
for _ in util.repeat(self.fallback_retries): |
| 633 |
url = f"{self.root}/s/{token}/{self.gallery_id}-{num}?nl={nl}" |
| 634 |
|
| 635 |
page = self.request(url, fatal=False).text |
| 636 |
if page.startswith(("Invalid page", "Keep trying")): |
| 637 |
return |
| 638 |
url, data = self.image_from_page(page) |
| 639 |
yield url |
| 640 |
|
| 641 |
nl = data["_nl"] |
| 642 |
|
| 643 |
def _fallback_mpv_1280(self, info, request): |
| 644 |
for _ in util.repeat(self.fallback_retries): |
| 645 |
request["nl"] = info["s"] |
| 646 |
info = self.request_json(self.api_url, method="POST", json=request) |
| 647 |
yield info["i"] |
| 648 |
|
| 649 |
def _parse_image_info(self, url): |
| 650 |
for part in url.split("/")[4:]: |
| 651 |
try: |
| 652 |
_, size, width, height, _ = part.split("-") |
| 653 |
break |
| 654 |
except ValueError: |
| 655 |
pass |
| 656 |
else: |
| 657 |
size = width = height = 0 |
| 658 |
|
| 659 |
return { |
| 660 |
"cost" : 1, |
| 661 |
"size" : text.parse_int(size), |
| 662 |
"width" : text.parse_int(width), |
| 663 |
"height": text.parse_int(height), |
| 664 |
} |
| 665 |
|
| 666 |
def _parse_original_info(self, info): |
| 667 |
parts = info.lstrip().split(" ") |
| 668 |
size = text.parse_bytes(parts[3] + parts[4][0]) |
| 669 |
|
| 670 |
return { |
| 671 |
# 1 initial point + 1 per 0.1 MB |
| 672 |
"cost" : 1 + math.ceil(size / 100_000), |
| 673 |
"size" : size, |
| 674 |
"width" : text.parse_int(parts[0]), |
| 675 |
"height": text.parse_int(parts[2]), |
| 676 |
} |
| 677 |
|
| 678 |
def _parse_mpv_info(self, info): |
| 679 |
_, _, w, _, h, s, u, _ = info["o"].split() |
| 680 |
size = text.parse_bytes(s + u[0]) |
| 681 |
|
| 682 |
return { |
| 683 |
# 1 initial point + 1 per 0.1 MB |
| 684 |
"cost" : 1 + math.ceil(size / 100_000), |
| 685 |
"size" : size, |
| 686 |
"width" : text.parse_int(w), |
| 687 |
"height": text.parse_int(h), |
| 688 |
} |
| 689 |
|
| 690 |
|
| 691 |
class ExhentaiSearchExtractor(ExhentaiExtractor): |
| 692 |
"""Extractor for exhentai search results""" |
| 693 |
subcategory = "search" |
| 694 |
pattern = (BASE_PATTERN + |
| 695 |
r"/(?!favorites\.php)(?:tag/([^/?#]+))?(?:\?([^#]*))?") |
| 696 |
example = "https://e-hentai.org/?f_search=QUERY" |
| 697 |
|
| 698 |
def _init(self): |
| 699 |
self.search_url = self.root |
| 700 |
|
| 701 |
def items(self): |
| 702 |
self.login() |
| 703 |
data = {"_extractor": ExhentaiGalleryExtractor} |
| 704 |
search_url = self.search_url |
| 705 |
|
| 706 |
_, tag, query = self.groups |
| 707 |
params = text.parse_query(query) |
| 708 |
if "next" not in params: |
| 709 |
params["page"] = text.parse_int(params.get("page")) |
| 710 |
if tag: |
| 711 |
if "+" in tag: |
| 712 |
ns, _, tag = tag.rpartition(":") |
| 713 |
tag = f"{ns}:\"{tag.replace('+', ' ')}$\"" |
| 714 |
else: |
| 715 |
tag += "$" |
| 716 |
params["f_search"] = tag |
| 717 |
data["search_tags"] = params.get("f_search", "") |
| 718 |
data["favorite_id"] = params.get("favcat", "") |
| 719 |
|
| 720 |
while True: |
| 721 |
last = None |
| 722 |
page = self.request(search_url, params=params).text |
| 723 |
|
| 724 |
for match in ExhentaiGalleryExtractor.pattern.finditer(page): |
| 725 |
url = match[0] |
| 726 |
if url == last: |
| 727 |
continue |
| 728 |
last = url |
| 729 |
data["gallery_id"] = text.parse_int(match[2]) |
| 730 |
data["gallery_token"] = match[3] |
| 731 |
yield Message.Queue, url + "/", data |
| 732 |
|
| 733 |
next_url = text.extr(page, 'nexturl="', '"', None) |
| 734 |
if next_url is not None: |
| 735 |
if not next_url: |
| 736 |
return |
| 737 |
search_url = next_url |
| 738 |
params = None |
| 739 |
|
| 740 |
elif 'class="ptdd">><' in page or ">No hits found</p>" in page: |
| 741 |
return |
| 742 |
else: |
| 743 |
params["page"] += 1 |
| 744 |
|
| 745 |
|
| 746 |
class ExhentaiFavoriteExtractor(ExhentaiSearchExtractor): |
| 747 |
"""Extractor for favorited exhentai galleries""" |
| 748 |
subcategory = "favorite" |
| 749 |
pattern = BASE_PATTERN + r"/favorites\.php(?:\?()([^#]*))?" |
| 750 |
example = "https://e-hentai.org/favorites.php" |
| 751 |
|
| 752 |
def _init(self): |
| 753 |
self.search_url = self.root + "/favorites.php" |