"use strict"; /** * LNReader-plugin voor de zelfgehoste HFY-Novels-index. * * De catalogus (titels, auteurs, hoofdstuklijsten) komt uit een statische * JSON-index. De verhaaltekst zelf staat niet in die index: parseChapter * probeert eerst de echte Reddit-JSON (www.reddit.com/.../.json, daarna * old.reddit.com) via fetchApi, zodat cookies uit de LNReader-WebView * meegaan na inloggen op reddit.com. Bij een fout, 403 of login-/blokpagina * valt de plugin terug op Arctic Shift. * * Dit bestand is CommonJS, zoals de officiƫle gecompileerde plugins: * require(...) uit de LNReader-allowlist, en `exports.default = instance`. */ Object.defineProperty(exports, "__esModule", { value: true }); const { fetchApi } = require("@libs/fetch"); const { FilterTypes } = require("@libs/filterInputs"); const { defaultCover } = require("@libs/defaultCover"); const { NovelStatus } = require("@libs/novelStatus"); const { storage } = require("@libs/storage"); const DEFAULT_INDEX_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw/public"; const DEFAULT_INDEX_REV = "master"; const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com"; const PAGE_FALLBACK_SIZE = 50; function setting(key, fallback) { try { const value = storage.get(key); if (value === undefined || value === null || value === "") { return fallback; } return value; } catch (err) { return fallback; } } function joinUrl(base, path, query) { const trimmedBase = String(base || "").replace(/\/+$/, ""); const trimmedPath = String(path || "").replace(/^\/+/, ""); let url = trimmedBase + "/" + trimmedPath; const params = []; if (query && typeof query === "object") { for (const [k, v] of Object.entries(query)) { if (v !== undefined && v !== null && v !== "") { params.push(encodeURIComponent(k) + "=" + encodeURIComponent(String(v))); } } } if (params.length) { url += (url.includes("?") ? "&" : "?") + params.join("&"); } return url; } function statusFrom(text) { switch (text) { case "Completed": return NovelStatus.Completed; case "Ongoing": return NovelStatus.Ongoing; case "On Hiatus": return NovelStatus.OnHiatus; default: return NovelStatus.Unknown; } } async function readJson(url, label) { const res = await fetchApi(url); if (!res || res.ok === false) { const status = res && res.status != null ? res.status : "?"; throw new Error("HFY Novels: kon " + label + " niet laden (HTTP " + status + ")"); } if (typeof res.json === "function") { return await res.json(); } const text = await res.text(); return JSON.parse(text); } function toNovelItem(entry, plugin) { return { name: entry.name, path: entry.path, cover: plugin.coverUrl(entry.cover), }; } class HFYNovelsPlugin { constructor() { this.id = "hfyNovels"; this.name = "HFY Novels"; this.version = "0.2.0"; this.site = "https://www.reddit.com/r/HFY/"; this.icon = "icon.png"; // Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's // fetchApi (native fetch) stuurt de WebView-cookies automatisch mee // voor hetzelfde domein; localStorage is daarvoor niet nodig. this.filters = { kind: { value: "all", label: "Type", options: [ { label: "Alles", value: "all" }, { label: "Reeksen", value: "series" }, { label: "Oneshots", value: "oneshot" }, ], type: FilterTypes.Picker, }, nsfw: { value: "hide", label: "NSFW", options: [ { label: "Verbergen", value: "hide" }, { label: "Tonen", value: "show" }, ], type: FilterTypes.Picker, }, }; this.pluginSettings = { indexBaseUrl: { value: DEFAULT_INDEX_BASE, label: "Basis-URL van de index", type: "Text", }, indexRev: { value: DEFAULT_INDEX_REV, label: "Git-revisie van de index (rev=)", type: "Text", }, chapterSource: { value: "auto", label: "Bron voor hoofdstuktekst", type: "Select", options: [ { label: "Automatisch (Reddit, anders Arctic Shift)", value: "auto" }, { label: "Alleen Reddit", value: "reddit" }, { label: "Alleen Arctic Shift", value: "arctic" }, ], }, chapterSourceUrl: { value: DEFAULT_CHAPTER_SOURCE, label: "Arctic Shift-basis-URL (fallback)", type: "Text", }, }; } indexQuery() { const rev = setting("indexRev", DEFAULT_INDEX_REV); return { rev: rev }; } indexUrl(path) { const base = setting("indexBaseUrl", DEFAULT_INDEX_BASE); return joinUrl(base, path, this.indexQuery()); } coverUrl(cover) { if (!cover) { return defaultCover; } if (/^https?:\/\//i.test(cover)) { return cover; } let url = this.indexUrl(cover); // BlueGit serveert SVG pas als afbeelding met ?as=img. if (/\.svg$/i.test(cover) && url.indexOf("as=img") === -1) { url += (url.indexOf("?") === -1 ? "?" : "&") + "as=img"; } return url; } chapterSource() { return String(setting("chapterSourceUrl", DEFAULT_CHAPTER_SOURCE)).replace(/\/+$/, ""); } chapterMode() { const mode = String(setting("chapterSource", "auto") || "auto").toLowerCase(); if (mode === "reddit" || mode === "arctic") { return mode; } return "auto"; } /** * Maakt "Open in WebView" op een reeks of hoofdstuk tot een Reddit-URL, * zodat je daar kunt inloggen. Zonder deze functie zou LNReader * site+path plakken (bijv. /r/HFY/series/id), wat geen geldige Reddit-pagina is. * Het reeks-id is de oudste post (eerste deel). */ resolveUrl(path, isNovel) { const raw = String(path || "").trim(); if (/^https?:\/\//i.test(raw)) { return raw; } const id = chapterIdFromPath(raw) || chapterIdFromPath(raw.replace(/^series\//, "chapter/")); if (id) { return "https://www.reddit.com/r/HFY/comments/" + id + "/"; } return this.site; } matchesFilters(entry, filters) { const kind = filters && filters.kind ? filters.kind.value : "all"; const nsfw = filters && filters.nsfw ? filters.nsfw.value : "hide"; if (kind === "oneshot" && !entry.oneshot) { return false; } if (kind === "series" && entry.oneshot) { return false; } if (nsfw === "hide" && entry.nsfw) { return false; } return true; } async loadMeta() { return await readJson(this.indexUrl("catalog-meta.json"), "catalogus-meta"); } async popularNovels(pageNo, options) { const opts = options || {}; const filters = opts.filters || {}; const showLatest = !!opts.showLatestNovels; const page = Math.max(1, parseInt(pageNo, 10) || 1); // Zonder extra filters is de catalogus al op update-datum gesorteerd. const usePagedCatalog = !showLatest && (!filters.kind || filters.kind.value === "all") && (!filters.nsfw || filters.nsfw.value === "hide"); if (usePagedCatalog) { const meta = await this.loadMeta(); const pages = meta.pages || []; const spec = pages[page - 1]; if (!spec) { return []; } const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page); const novels = (payload.novels || []).filter((n) => !n.nsfw); return novels.map((n) => toNovelItem(n, this)); } const search = await readJson(this.indexUrl("search-index.json"), "zoekindex"); let items = (search.novels || []).filter((n) => this.matchesFilters(n, filters)); const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE; const start = (page - 1) * size; return items.slice(start, start + size).map((n) => toNovelItem(n, this)); } async searchNovels(searchTerm, pageNo) { const term = String(searchTerm || "") .trim() .toLowerCase(); if (!term) { return []; } const page = Math.max(1, parseInt(pageNo, 10) || 1); const search = await readJson(this.indexUrl("search-index.json"), "zoekindex"); const hits = (search.novels || []).filter((n) => { const name = String(n.name || "").toLowerCase(); const author = String(n.author || "").toLowerCase(); return name.includes(term) || author.includes(term); }); const size = PAGE_FALLBACK_SIZE; const start = (page - 1) * size; return hits.slice(start, start + size).map((n) => toNovelItem(n, this)); } seriesFileFor(novelPath) { const id = String(novelPath || "") .replace(/^series\//, "") .replace(/\/+$/, ""); if (!id) { throw new Error("HFY Novels: leeg reeks-pad"); } const prefix = id.charAt(0).toLowerCase() || "x"; return "series/" + prefix + "/" + id + ".json"; } async parseNovel(novelPath) { const data = await readJson(this.indexUrl(this.seriesFileFor(novelPath)), "reeks " + novelPath); return { path: data.path || novelPath, name: data.name || "Untitled", author: data.author || "Anonymous", artist: undefined, cover: this.coverUrl(data.cover), genres: data.genres || "HFY", status: statusFrom(data.status), summary: data.summary || "", chapters: (data.chapterList || []).map((ch) => ({ name: ch.name, path: ch.path, releaseTime: ch.releaseTime || null, chapterNumber: ch.chapterNumber, })), }; } async parseChapter(chapterPath) { const id = chapterIdFromPath(chapterPath); if (!id) { throw new Error("HFY Novels: ongeldig hoofdstuk-id"); } const mode = this.chapterMode(); let redditError = ""; if (mode !== "arctic") { const reddit = await tryRedditChapter(id); if (reddit.ok) { return renderChapter(reddit.post, "Reddit"); } redditError = reddit.reason || "onbekende fout"; if (mode === "reddit") { throw new Error( "HFY Novels: Reddit gaf geen hoofdstuk (" + redditError + "). Log in via Open in WebView op reddit.com en probeer het opnieuw.", ); } } const arctic = await tryArcticChapter(this.chapterSource(), id); if (arctic.ok) { const suffix = mode === "arctic" ? "Arctic Shift" : "Arctic Shift (fallback)"; return renderChapter(arctic.post, suffix); } if (redditError) { throw new Error( "HFY Novels: Reddit (" + redditError + ") en Arctic Shift (" + (arctic.reason || "geen tekst") + ") faalden allebei.", ); } throw new Error("HFY Novels: kon hoofdstuk " + id + " niet laden (" + (arctic.reason || "geen tekst") + ")"); } } function chapterIdFromPath(chapterPath) { const id = String(chapterPath || "") .replace(/^chapter\//, "") .replace(/^series\//, "") .trim() .toLowerCase(); return /^[0-9a-z]{4,10}$/.test(id) ? id : ""; } function redditJsonUrls(id) { const path = "/r/HFY/comments/" + id + "/.json?raw_json=1"; return [ "https://www.reddit.com" + path, "https://old.reddit.com" + path, ]; } function looksLikeHtml(text) { const body = String(text || "").trim(); if (!body) { return false; } return /^\s*<(!DOCTYPE|html|body|head)\b/i.test(body); } function isLoginOrBlockPage(res, body) { const status = res && res.status != null ? Number(res.status) : 0; if (status === 401 || status === 403 || status === 429) { return true; } const finalUrl = String((res && res.url) || ""); if (/[?&]reason=lor2\b/i.test(finalUrl) || /\/login\b/i.test(finalUrl)) { return true; } const type = String( (res && res.headers && typeof res.headers.get === "function" && res.headers.get("content-type")) || "", ).toLowerCase(); if (type.indexOf("text/html") !== -1 && !/json/i.test(type)) { return true; } const text = String(body || ""); if (looksLikeHtml(text)) { return true; } const lower = text.toLowerCase(); if ( lower.indexOf("reason=lor2") !== -1 || lower.indexOf("www.reddit.com/login") !== -1 || lower.indexOf("old.reddit.com/login") !== -1 || lower.indexOf("log in to reddit") !== -1 || (lower.indexOf("shreddit") !== -1 && lower.indexOf(" !c.kind || c.kind === "t3") || children[0]; if (!child || !child.data) { return null; } if (child.kind && child.kind !== "t3") { return null; } return child.data; } function decodeRedditHtml(html) { let text = String(html || ""); if (text.indexOf("<") !== -1 || text.indexOf("&") !== -1) { text = text .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&/g, "&"); } return text; } async function tryRedditChapter(id) { let lastReason = "geen antwoord"; const urls = redditJsonUrls(id); for (let i = 0; i < urls.length; i++) { const url = urls[i]; try { const res = await fetchApi(url, { headers: { Accept: "application/json" } }); const body = typeof res.text === "function" ? await res.text() : ""; if (!res || res.ok === false || isLoginOrBlockPage(res, body)) { const status = res && res.status != null ? res.status : "?"; lastReason = "HTTP " + status + (isLoginOrBlockPage(res, body) ? " (login of blokkade)" : ""); continue; } if (!body || looksLikeHtml(body)) { lastReason = "geen JSON"; continue; } let payload; try { payload = JSON.parse(body); } catch (err) { lastReason = "ongeldige JSON"; continue; } const post = postFromRedditPayload(payload); if (!post) { lastReason = "geen post in de listing"; continue; } return { ok: true, post: post }; } catch (err) { lastReason = err && err.message ? err.message : String(err); } } return { ok: false, reason: lastReason }; } async function tryArcticChapter(base, id) { const url = String(base || "").replace(/\/+$/, "") + "/api/posts/ids?ids=" + encodeURIComponent(id) + "&md2html=true"; try { const payload = await readJson(url, "hoofdstuk " + id); const posts = payload.data || payload; const post = Array.isArray(posts) ? posts[0] : posts; if (!post) { return { ok: false, reason: "leeg antwoord" }; } return { ok: true, post: post }; } catch (err) { return { ok: false, reason: err && err.message ? err.message : String(err) }; } } function sourceFooter(label) { return '
Bron: ' + escapeHtml(label) + "
"; } function renderChapter(post, sourceLabel) { if (!post) { return "Dit hoofdstuk is niet (meer) beschikbaar.
" + sourceFooter(sourceLabel); } const title = post.title ? "by u/" + escapeHtml(post.author) + "
" : ""; const rawHtml = post.selftext_html ? decodeRedditHtml(post.selftext_html) : ""; const html = rawHtml ? sanitizeHtml(rawHtml) : markdownToHtml(post.selftext || ""); if (!html) { return ( title + by + "Deze post heeft geen tekst (verwijderd of een link-post).
" + sourceFooter(sourceLabel) ); } return title + by + html + sourceFooter(sourceLabel); } function escapeHtml(text) { return String(text) .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } function sanitizeHtml(html) { // Reddit en Arctic Shift leveren HTML; we strippen scripts en on-event-attributen. return String(html) .replace(/