| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2024-2025 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://niyaniya.moe/""" |
| 10 |
|
| 11 |
from .common import GalleryExtractor, Extractor, Message |
| 12 |
from .. import text |
| 13 |
import collections |
| 14 |
|
| 15 |
BASE_PATTERN = ( |
| 16 |
r"(?i)(?:https?://)?(" |
| 17 |
r"(?:niyaniya|shupogaki)\.moe|" |
| 18 |
r"(?:koharu|anchira|seia)\.to|" |
| 19 |
r"(?:hoshino)\.one" |
| 20 |
r")" |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
class SchalenetworkExtractor(Extractor): |
| 25 |
"""Base class for schale.network extractors""" |
| 26 |
category = "schalenetwork" |
| 27 |
root = "https://niyaniya.moe" |
| 28 |
root_api = "https://api.schale.network" |
| 29 |
root_auth = "https://auth.schale.network" |
| 30 |
extr_class = None |
| 31 |
request_interval = (0.5, 1.5) |
| 32 |
|
| 33 |
def _init(self): |
| 34 |
self.headers = { |
| 35 |
"Accept" : "*/*", |
| 36 |
"Referer": self.root + "/", |
| 37 |
"Origin" : self.root, |
| 38 |
} |
| 39 |
|
| 40 |
def _pagination(self, endpoint, params): |
| 41 |
url_api = self.root_api + endpoint |
| 42 |
cls = self.extr_class |
| 43 |
|
| 44 |
while True: |
| 45 |
data = self.request_json( |
| 46 |
url_api, params=params, headers=self.headers) |
| 47 |
|
| 48 |
try: |
| 49 |
entries = data["entries"] |
| 50 |
except KeyError: |
| 51 |
return |
| 52 |
|
| 53 |
for entry in entries: |
| 54 |
url = f"{self.root}/g/{entry['id']}/{entry['key']}" |
| 55 |
entry["_extractor"] = cls |
| 56 |
yield Message.Queue, url, entry |
| 57 |
|
| 58 |
try: |
| 59 |
if data["limit"] * data["page"] >= data["total"]: |
| 60 |
return |
| 61 |
except Exception: |
| 62 |
pass |
| 63 |
params["page"] += 1 |
| 64 |
|
| 65 |
def _token(self, required=True): |
| 66 |
if token := self.config("token"): |
| 67 |
return "Bearer " + token.rpartition(' ')[2] |
| 68 |
if required: |
| 69 |
raise self.exc.AuthRequired("'token'", "your favorites") |
| 70 |
|
| 71 |
def _crt(self): |
| 72 |
crt = self.config("crt") |
| 73 |
if not crt: |
| 74 |
self._require_auth() |
| 75 |
|
| 76 |
if not text.re(r"^[0-9a-f-]+$").match(crt): |
| 77 |
path, _, qs = crt.partition("?") |
| 78 |
if not qs: |
| 79 |
qs = path |
| 80 |
crt = text.parse_query(qs).get("crt") |
| 81 |
if not crt: |
| 82 |
self._require_auth() |
| 83 |
|
| 84 |
return crt |
| 85 |
|
| 86 |
def _require_auth(self, exc=None): |
| 87 |
if exc is None: |
| 88 |
msg = None |
| 89 |
else: |
| 90 |
msg = f"{exc.status} {exc.response.reason}" |
| 91 |
raise self.exc.AuthRequired( |
| 92 |
"'crt' query parameter & matching 'user-agent'", None, msg) |
| 93 |
|
| 94 |
|
| 95 |
class SchalenetworkGalleryExtractor(SchalenetworkExtractor, GalleryExtractor): |
| 96 |
"""Extractor for schale.network galleries""" |
| 97 |
filename_fmt = "{num:>03}.{extension}" |
| 98 |
directory_fmt = ("{category}", "{id} {title}") |
| 99 |
archive_fmt = "{id}_{num}" |
| 100 |
request_interval = 0.0 |
| 101 |
pattern = BASE_PATTERN + r"/(?:g|reader)/(\d+)/(\w+)" |
| 102 |
example = "https://niyaniya.moe/g/12345/67890abcde/" |
| 103 |
|
| 104 |
TAG_TYPES = { |
| 105 |
0 : "general", |
| 106 |
1 : "artist", |
| 107 |
2 : "circle", |
| 108 |
3 : "parody", |
| 109 |
4 : "magazine", |
| 110 |
5 : "character", |
| 111 |
6 : "", |
| 112 |
7 : "uploader", |
| 113 |
8 : "male", |
| 114 |
9 : "female", |
| 115 |
10: "mixed", |
| 116 |
11: "language", |
| 117 |
12: "other", |
| 118 |
13: "reclass", |
| 119 |
} |
| 120 |
|
| 121 |
def metadata(self, _): |
| 122 |
_, gid, gkey = self.groups |
| 123 |
|
| 124 |
url = f"{self.root_api}/books/detail/{gid}/{gkey}" |
| 125 |
headers = self.headers |
| 126 |
data = self.request_json(url, headers=headers) |
| 127 |
|
| 128 |
try: |
| 129 |
data["date"] = self.parse_timestamp(data["created_at"] / 1000) |
| 130 |
data["count"] = len(data["thumbnails"]["entries"]) |
| 131 |
del data["thumbnails"] |
| 132 |
except Exception: |
| 133 |
pass |
| 134 |
|
| 135 |
tags = [] |
| 136 |
types = self.TAG_TYPES |
| 137 |
for tag in data["tags"]: |
| 138 |
name = tag["name"] |
| 139 |
namespace = tag.get("namespace", 0) |
| 140 |
tags.append(types[namespace] + ":" + name) |
| 141 |
if self.config("tags", True): |
| 142 |
categories = collections.defaultdict(list) |
| 143 |
for tag in data["tags"]: |
| 144 |
categories[tag.get("namespace", 0)].append(tag["name"]) |
| 145 |
for type, values in categories.items(): |
| 146 |
data["tags_" + types[type]] = values |
| 147 |
data["tags"] = tags |
| 148 |
|
| 149 |
url = f"{self.root_api}/books/detail/{gid}/{gkey}?crt={self._crt()}" |
| 150 |
if token := self._token(False): |
| 151 |
headers = headers.copy() |
| 152 |
headers["Authorization"] = token |
| 153 |
try: |
| 154 |
data_fmt = self.request_json( |
| 155 |
url, method="POST", headers=headers) |
| 156 |
except self.exc.HttpError as exc: |
| 157 |
self._require_auth(exc) |
| 158 |
|
| 159 |
self.fmt = self._select_format(data_fmt["data"]) |
| 160 |
data["source"] = data_fmt.get("source") |
| 161 |
|
| 162 |
return data |
| 163 |
|
| 164 |
def images(self, _): |
| 165 |
_, gid, gkey = self.groups |
| 166 |
fmt = self.fmt |
| 167 |
|
| 168 |
url = (f"{self.root_api}/books/data/{gid}/{gkey}" |
| 169 |
f"/{fmt['id']}/{fmt['key']}/{fmt['w']}?crt={self._crt()}") |
| 170 |
headers = self.headers |
| 171 |
|
| 172 |
if self.config("cbz", False): |
| 173 |
headers["Authorization"] = self._token() |
| 174 |
dl = self.request_json( |
| 175 |
url + "&action=dl", method="POST", headers=headers) |
| 176 |
# 'crt' parameter here is necessary for 'hdoujin' downloads |
| 177 |
url = f"{dl['base']}?crt={self._crt()}" |
| 178 |
info = text.nameext_from_url(url) |
| 179 |
if "fallback" in dl: |
| 180 |
info["_fallback"] = (dl["fallback"],) |
| 181 |
if not info["extension"]: |
| 182 |
info["extension"] = "cbz" |
| 183 |
return ((url, info),) |
| 184 |
|
| 185 |
data = self.request_json(url, headers=headers) |
| 186 |
base = data["base"] |
| 187 |
|
| 188 |
results = [] |
| 189 |
for entry in data["entries"]: |
| 190 |
dimensions = entry["dimensions"] |
| 191 |
info = { |
| 192 |
"width" : dimensions[0], |
| 193 |
"height": dimensions[1], |
| 194 |
"_http_headers": headers, |
| 195 |
} |
| 196 |
results.append((base + entry["path"], info)) |
| 197 |
return results |
| 198 |
|
| 199 |
def _select_format(self, formats): |
| 200 |
fmt = self.config("format") |
| 201 |
|
| 202 |
if not fmt or fmt == "best": |
| 203 |
fmtids = ("0", "1600", "1280", "980", "780") |
| 204 |
elif isinstance(fmt, str): |
| 205 |
fmtids = fmt.split(",") |
| 206 |
elif isinstance(fmt, list): |
| 207 |
fmtids = fmt |
| 208 |
else: |
| 209 |
fmtids = (str(fmt),) |
| 210 |
|
| 211 |
for fmtid in fmtids: |
| 212 |
try: |
| 213 |
fmt = formats[fmtid] |
| 214 |
if fmt["id"]: |
| 215 |
break |
| 216 |
except KeyError: |
| 217 |
self.log.debug("%s: Format %s is not available", |
| 218 |
self.groups[1], fmtid) |
| 219 |
else: |
| 220 |
raise self.exc.NotFoundError("format") |
| 221 |
|
| 222 |
self.log.debug("%s: Selected format %s", self.groups[1], fmtid) |
| 223 |
fmt["w"] = fmtid |
| 224 |
return fmt |
| 225 |
|
| 226 |
|
| 227 |
class SchalenetworkSearchExtractor(SchalenetworkExtractor): |
| 228 |
"""Extractor for schale.network search results""" |
| 229 |
subcategory = "search" |
| 230 |
pattern = BASE_PATTERN + r"/(?:tag/([^/?#]+)|browse)?(?:/?\?([^#]*))?$" |
| 231 |
example = "https://niyaniya.moe/browse?s=QUERY" |
| 232 |
|
| 233 |
def items(self): |
| 234 |
_, tag, qs = self.groups |
| 235 |
|
| 236 |
params = text.parse_query(qs) |
| 237 |
params["page"] = text.parse_int(params.get("page"), 1) |
| 238 |
|
| 239 |
if tag is not None: |
| 240 |
ns, sep, tag = text.unquote(tag).partition(":") |
| 241 |
if "+" in tag: |
| 242 |
tag = tag.replace("+", " ") |
| 243 |
q = '"' |
| 244 |
else: |
| 245 |
q = "" |
| 246 |
q = '"' if " " in tag else "" |
| 247 |
params["s"] = f"{ns}{sep}{q}^{tag}${q}" |
| 248 |
|
| 249 |
return self._pagination("/books", params) |
| 250 |
|
| 251 |
|
| 252 |
class SchalenetworkFavoriteExtractor(SchalenetworkExtractor): |
| 253 |
"""Extractor for schale.network favorites""" |
| 254 |
subcategory = "favorite" |
| 255 |
pattern = BASE_PATTERN + r"/favorites(?:\?([^#]*))?" |
| 256 |
example = "https://niyaniya.moe/favorites" |
| 257 |
|
| 258 |
def items(self): |
| 259 |
params = text.parse_query(self.groups[1]) |
| 260 |
params["page"] = text.parse_int(params.get("page"), 1) |
| 261 |
self.headers["Authorization"] = self._token() |
| 262 |
return self._pagination("/books/favorites?crt=" + self._crt(), params) |
| 263 |
|
| 264 |
|
| 265 |
SchalenetworkExtractor.extr_class = SchalenetworkGalleryExtractor |