| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2022-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://www.zerochan.net/""" |
| 10 |
|
| 11 |
from .booru import BooruExtractor |
| 12 |
from .. import text, util |
| 13 |
import collections |
| 14 |
|
| 15 |
BASE_PATTERN = r"(?:https?://)?(?:www\.)?zerochan\.net" |
| 16 |
|
| 17 |
|
| 18 |
class ZerochanExtractor(BooruExtractor): |
| 19 |
"""Base class for zerochan extractors""" |
| 20 |
category = "zerochan" |
| 21 |
root = "https://www.zerochan.net" |
| 22 |
filename_fmt = "{id}.{extension}" |
| 23 |
archive_fmt = "{id}" |
| 24 |
page_start = 1 |
| 25 |
per_page = 200 |
| 26 |
cookies_domain = ".zerochan.net" |
| 27 |
cookies_names = ("z_id", "z_hash") |
| 28 |
useragent = util.USERAGENT_GALLERYDL |
| 29 |
request_interval = (0.5, 1.5) |
| 30 |
|
| 31 |
def login(self): |
| 32 |
self._logged_in = True |
| 33 |
if self.cookies_check(self.cookies_names): |
| 34 |
return |
| 35 |
|
| 36 |
username, password = self._get_auth_info() |
| 37 |
if username: |
| 38 |
return self.cookies_update(self.cache( |
| 39 |
self._login_impl, username, password, |
| 40 |
_exp=90*86400, _mem=False)) |
| 41 |
|
| 42 |
self._logged_in = False |
| 43 |
|
| 44 |
def _login_impl(self, username, password): |
| 45 |
self.log.info("Logging in as %s", username) |
| 46 |
|
| 47 |
url = self.root + "/login" |
| 48 |
headers = { |
| 49 |
"Origin" : self.root, |
| 50 |
"Referer" : url, |
| 51 |
} |
| 52 |
data = { |
| 53 |
"ref" : "/", |
| 54 |
"name" : username, |
| 55 |
"password": password, |
| 56 |
"login" : "Login", |
| 57 |
} |
| 58 |
|
| 59 |
response = self.request( |
| 60 |
url, method="POST", headers=headers, data=data, expected=(500,)) |
| 61 |
if not response.history: |
| 62 |
raise self.exc.AuthenticationError() |
| 63 |
|
| 64 |
return response.cookies |
| 65 |
|
| 66 |
def _parse_entry_html(self, entry_id): |
| 67 |
url = f"{self.root}/{entry_id}" |
| 68 |
page = self.request(url, expected=(500,)).text |
| 69 |
|
| 70 |
try: |
| 71 |
jsonld = self._extract_jsonld(page) |
| 72 |
except Exception: |
| 73 |
return {"id": entry_id} |
| 74 |
|
| 75 |
extr = text.extract_from(page) |
| 76 |
data = { |
| 77 |
"id" : text.parse_int(entry_id), |
| 78 |
"file_url": jsonld["contentUrl"], |
| 79 |
"date" : self.parse_datetime_iso(jsonld["datePublished"]), |
| 80 |
"width" : text.parse_int(jsonld["width"][:-3]), |
| 81 |
"height" : text.parse_int(jsonld["height"][:-3]), |
| 82 |
"size" : text.parse_bytes(jsonld["contentSize"][:-1]), |
| 83 |
"path" : text.split_html(extr( |
| 84 |
'class="breadcrumbs', '</nav>'))[2:], |
| 85 |
"uploader": extr('href="/user/', '"'), |
| 86 |
"tags" : extr('<ul id="tags"', '</ul>'), |
| 87 |
"source" : text.unescape(text.remove_html(extr( |
| 88 |
'id="source-url"', '</p>').rpartition("</s>")[2])), |
| 89 |
} |
| 90 |
|
| 91 |
try: |
| 92 |
data["author"] = jsonld["author"]["name"] |
| 93 |
except Exception: |
| 94 |
data["author"] = "" |
| 95 |
|
| 96 |
html = data["tags"] |
| 97 |
tags = data["tags"] = [] |
| 98 |
for tag in html.split("<li class=")[1:]: |
| 99 |
category = text.extr(tag, '"', '"') |
| 100 |
name = text.unescape(text.extr(tag, 'data-tag="', '"')) |
| 101 |
tags.append(category.partition(" ")[0].capitalize() + ":" + name) |
| 102 |
|
| 103 |
return data |
| 104 |
|
| 105 |
def _parse_entry_api(self, entry_id): |
| 106 |
url = f"{self.root}/{entry_id}?json" |
| 107 |
txt = self.request(url).text |
| 108 |
try: |
| 109 |
item = util.json_loads(txt) |
| 110 |
except ValueError: |
| 111 |
item = self._parse_json(txt) |
| 112 |
item["id"] = text.parse_int(entry_id) |
| 113 |
|
| 114 |
data = { |
| 115 |
"id" : item["id"], |
| 116 |
"file_url": item["full"], |
| 117 |
"width" : item["width"], |
| 118 |
"height" : item["height"], |
| 119 |
"size" : item["size"], |
| 120 |
"name" : item["primary"], |
| 121 |
"md5" : item["hash"], |
| 122 |
"source" : item.get("source"), |
| 123 |
} |
| 124 |
|
| 125 |
if not self._logged_in: |
| 126 |
data["tags"] = item["tags"] |
| 127 |
|
| 128 |
return data |
| 129 |
|
| 130 |
def _parse_json(self, txt): |
| 131 |
txt = text.re(r"[\x00-\x1f\x7f]").sub("", txt) |
| 132 |
main, _, tags = txt.partition('tags": [') |
| 133 |
|
| 134 |
item = {} |
| 135 |
for line in main.split(', "')[1:]: |
| 136 |
key, _, value = line.partition('": ') |
| 137 |
if value: |
| 138 |
if value[0] == '"': |
| 139 |
value = value[1:-1] |
| 140 |
else: |
| 141 |
value = text.parse_int(value) |
| 142 |
if key: |
| 143 |
item[key] = value |
| 144 |
|
| 145 |
item["tags"] = tags = tags[5:].split('", "') |
| 146 |
if tags: |
| 147 |
tags[-1] = tags[-1][:-5] |
| 148 |
|
| 149 |
return item |
| 150 |
|
| 151 |
def _tags(self, post, page): |
| 152 |
tags = collections.defaultdict(list) |
| 153 |
for tag in post["tags"]: |
| 154 |
category, _, name = tag.partition(":") |
| 155 |
tags[category].append(name) |
| 156 |
for key, value in tags.items(): |
| 157 |
post["tags_" + key.lower()] = value |
| 158 |
|
| 159 |
|
| 160 |
class ZerochanTagExtractor(ZerochanExtractor): |
| 161 |
subcategory = "tag" |
| 162 |
directory_fmt = ("{category}", "{search_tags}") |
| 163 |
pattern = BASE_PATTERN + r"/(?!\d+$)([^?#]+)/?(?:\?([^#]+))?" |
| 164 |
example = "https://www.zerochan.net/TAG" |
| 165 |
|
| 166 |
def _init(self): |
| 167 |
if self.config("pagination") == "html": |
| 168 |
self.posts = self.posts_html |
| 169 |
self.per_page = 24 |
| 170 |
else: |
| 171 |
self.posts = self.posts_api |
| 172 |
|
| 173 |
if exts := self.config("extensions"): |
| 174 |
if isinstance(exts, str): |
| 175 |
exts = exts.split(",") |
| 176 |
self.exts = exts |
| 177 |
else: |
| 178 |
self.exts = ("jpg", "png", "webp", "gif") |
| 179 |
|
| 180 |
def metadata(self): |
| 181 |
return {"search_tags": text.unquote(self.groups[0].replace("+", " "))} |
| 182 |
|
| 183 |
def posts_html(self): |
| 184 |
tag, qs = self.groups |
| 185 |
url = f"{self.root}/{tag}" |
| 186 |
metadata = self.config("metadata") |
| 187 |
|
| 188 |
params = text.parse_query(qs, empty=True) |
| 189 |
params["p"] = text.parse_int(params.get("p"), self.page_start) |
| 190 |
|
| 191 |
while True: |
| 192 |
try: |
| 193 |
page = self.request( |
| 194 |
url, params=params, expected=(500,)).text |
| 195 |
except self.exc.HttpError as exc: |
| 196 |
if exc.status == 404: |
| 197 |
return |
| 198 |
raise |
| 199 |
thumbs = text.extr(page, '<ul id="thumbs', '</ul>') |
| 200 |
extr = text.extract_from(thumbs) |
| 201 |
|
| 202 |
while True: |
| 203 |
post = extr('<li class="', '>') |
| 204 |
if not post: |
| 205 |
break |
| 206 |
|
| 207 |
if metadata: |
| 208 |
entry_id = extr('href="/', '"') |
| 209 |
post = self._parse_entry_html(entry_id) |
| 210 |
post.update(self._parse_entry_api(entry_id)) |
| 211 |
yield post |
| 212 |
else: |
| 213 |
yield { |
| 214 |
"id" : extr('href="/', '"'), |
| 215 |
"name" : extr('alt="', '"'), |
| 216 |
"width" : extr('title="', '✕'), |
| 217 |
"height": extr('', ' '), |
| 218 |
"size" : extr('', 'b'), |
| 219 |
"file_url": "https://static." + extr( |
| 220 |
'<a href="https://static.', '"'), |
| 221 |
} |
| 222 |
|
| 223 |
if 'rel="next"' not in page: |
| 224 |
break |
| 225 |
params["p"] += 1 |
| 226 |
|
| 227 |
def posts_api(self): |
| 228 |
tag, qs = self.groups |
| 229 |
url = f"{self.root}/{tag}" |
| 230 |
metadata = self.config("metadata") |
| 231 |
|
| 232 |
params = text.parse_query(qs, empty=True) |
| 233 |
params["p"] = text.parse_int(params.get("p"), self.page_start) |
| 234 |
params.setdefault("l", self.per_page) |
| 235 |
params["json"] = "1" |
| 236 |
|
| 237 |
while True: |
| 238 |
try: |
| 239 |
response = self.request( |
| 240 |
url, params=params, allow_redirects=False) |
| 241 |
except self.exc.HttpError as exc: |
| 242 |
if exc.status == 404: |
| 243 |
return |
| 244 |
raise |
| 245 |
|
| 246 |
if response.status_code >= 300: |
| 247 |
url = text.urljoin(self.root, response.headers["location"]) |
| 248 |
self.log.warning("HTTP redirect to %s", url) |
| 249 |
if self.config("redirects"): |
| 250 |
continue |
| 251 |
raise self.exc.AbortExtraction() |
| 252 |
|
| 253 |
try: |
| 254 |
data = response.json() |
| 255 |
except ValueError: |
| 256 |
# strip HTML inserts in JSON data |
| 257 |
if b"window.adsbygoogle" in response.content: |
| 258 |
page = response.text |
| 259 |
data = util.json_loads("{" + page[page.find('"items":'):]) |
| 260 |
|
| 261 |
try: |
| 262 |
posts = data["items"] |
| 263 |
except Exception: |
| 264 |
self.log.debug("Server response: %s", data) |
| 265 |
return |
| 266 |
|
| 267 |
if metadata: |
| 268 |
for post in posts: |
| 269 |
post_id = post["id"] |
| 270 |
post.update(self._parse_entry_html(post_id)) |
| 271 |
post.update(self._parse_entry_api(post_id)) |
| 272 |
yield post |
| 273 |
else: |
| 274 |
for post in posts: |
| 275 |
urls = self._urls(post) |
| 276 |
post["file_url"] = next(urls) |
| 277 |
post["_fallback"] = urls |
| 278 |
yield post |
| 279 |
|
| 280 |
if not data.get("next"): |
| 281 |
return |
| 282 |
params["p"] += 1 |
| 283 |
|
| 284 |
def _urls(self, post, static="https://static.zerochan.net/.full."): |
| 285 |
base = static + str(post["id"]) + "." |
| 286 |
for ext in self.exts: |
| 287 |
yield base + ext |
| 288 |
|
| 289 |
|
| 290 |
class ZerochanImageExtractor(ZerochanExtractor): |
| 291 |
subcategory = "image" |
| 292 |
pattern = BASE_PATTERN + r"/(\d+)" |
| 293 |
example = "https://www.zerochan.net/12345" |
| 294 |
|
| 295 |
def posts(self): |
| 296 |
image_id = self.groups[0] |
| 297 |
|
| 298 |
try: |
| 299 |
post = self._parse_entry_html(image_id) |
| 300 |
except self.exc.HttpError as exc: |
| 301 |
if exc.status in {404, 410}: |
| 302 |
if msg := text.extr(exc.response.text, "<h2>", "<"): |
| 303 |
self.log.warning(f"'{msg}'") |
| 304 |
return () |
| 305 |
raise |
| 306 |
|
| 307 |
if self.config("metadata"): |
| 308 |
post.update(self._parse_entry_api(image_id)) |
| 309 |
return (post,) |