BlueGit

timfa hfy-novels

Files

hfy-novels / plugin / hfy-novels.js

hfy-novels.js

hfy-novels.js 16.3 KiB Download Raw
1"use strict";
2
3/**
4 * LNReader-plugin voor de zelfgehoste HFY-Novels-index.
5 *
6 * De catalogus (titels, auteurs, hoofdstuklijsten) komt uit een statische
7 * JSON-index. De verhaaltekst zelf staat niet in die index: parseChapter
8 * probeert eerst de echte Reddit-JSON (www.reddit.com/.../.json, daarna
9 * old.reddit.com) via fetchApi, zodat cookies uit de LNReader-WebView
10 * meegaan na inloggen op reddit.com. Bij een fout, 403 of login-/blokpagina
11 * valt de plugin terug op Arctic Shift.
12 *
13 * Dit bestand is CommonJS, zoals de officiële gecompileerde plugins:
14 * require(...) uit de LNReader-allowlist, en `exports.default = instance`.
15 */
16
17Object.defineProperty(exports, "__esModule", { value: true });
18
19const { fetchApi } = require("@libs/fetch");
20const { FilterTypes } = require("@libs/filterInputs");
21const { defaultCover } = require("@libs/defaultCover");
22const { NovelStatus } = require("@libs/novelStatus");
23const { storage } = require("@libs/storage");
24
25const DEFAULT_INDEX_BASE =
26 "https://git.timfalken.com/timfa/hfy-novels/-/raw/public";
27const DEFAULT_INDEX_REV = "master";
28const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";
29const PAGE_FALLBACK_SIZE = 50;
30
31function setting(key, fallback) {
32 try {
33 const value = storage.get(key);
34 if (value === undefined || value === null || value === "") {
35 return fallback;
36 }
37 return value;
38 } catch (err) {
39 return fallback;
40 }
41}
42
43function joinUrl(base, path, query) {
44 const trimmedBase = String(base || "").replace(/\/+$/, "");
45 const trimmedPath = String(path || "").replace(/^\/+/, "");
46 let url = trimmedBase + "/" + trimmedPath;
47 const params = [];
48 if (query && typeof query === "object") {
49 for (const [k, v] of Object.entries(query)) {
50 if (v !== undefined && v !== null && v !== "") {
51 params.push(encodeURIComponent(k) + "=" + encodeURIComponent(String(v)));
52 }
53 }
54 }
55 if (params.length) {
56 url += (url.includes("?") ? "&" : "?") + params.join("&");
57 }
58 return url;
59}
60
61function statusFrom(text) {
62 switch (text) {
63 case "Completed":
64 return NovelStatus.Completed;
65 case "Ongoing":
66 return NovelStatus.Ongoing;
67 case "On Hiatus":
68 return NovelStatus.OnHiatus;
69 default:
70 return NovelStatus.Unknown;
71 }
72}
73
74async function readJson(url, label) {
75 const res = await fetchApi(url);
76 if (!res || res.ok === false) {
77 const status = res && res.status != null ? res.status : "?";
78 throw new Error("HFY Novels: kon " + label + " niet laden (HTTP " + status + ")");
79 }
80 if (typeof res.json === "function") {
81 return await res.json();
82 }
83 const text = await res.text();
84 return JSON.parse(text);
85}
86
87function toNovelItem(entry, plugin) {
88 return {
89 name: entry.name,
90 path: entry.path,
91 cover: plugin.coverUrl(entry.cover),
92 };
93}
94
95class HFYNovelsPlugin {
96 constructor() {
97 this.id = "hfyNovels";
98 this.name = "HFY Novels";
99 this.version = "0.2.0";
100 this.site = "https://www.reddit.com/r/HFY/";
101 this.icon = "icon.png";
102 // Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's
103 // fetchApi (native fetch) stuurt de WebView-cookies automatisch mee
104 // voor hetzelfde domein; localStorage is daarvoor niet nodig.
105 this.filters = {
106 kind: {
107 value: "all",
108 label: "Type",
109 options: [
110 { label: "Alles", value: "all" },
111 { label: "Reeksen", value: "series" },
112 { label: "Oneshots", value: "oneshot" },
113 ],
114 type: FilterTypes.Picker,
115 },
116 nsfw: {
117 value: "hide",
118 label: "NSFW",
119 options: [
120 { label: "Verbergen", value: "hide" },
121 { label: "Tonen", value: "show" },
122 ],
123 type: FilterTypes.Picker,
124 },
125 };
126 this.pluginSettings = {
127 indexBaseUrl: {
128 value: DEFAULT_INDEX_BASE,
129 label: "Basis-URL van de index",
130 type: "Text",
131 },
132 indexRev: {
133 value: DEFAULT_INDEX_REV,
134 label: "Git-revisie van de index (rev=)",
135 type: "Text",
136 },
137 chapterSource: {
138 value: "auto",
139 label: "Bron voor hoofdstuktekst",
140 type: "Select",
141 options: [
142 { label: "Automatisch (Reddit, anders Arctic Shift)", value: "auto" },
143 { label: "Alleen Reddit", value: "reddit" },
144 { label: "Alleen Arctic Shift", value: "arctic" },
145 ],
146 },
147 chapterSourceUrl: {
148 value: DEFAULT_CHAPTER_SOURCE,
149 label: "Arctic Shift-basis-URL (fallback)",
150 type: "Text",
151 },
152 };
153 }
154
155 indexQuery() {
156 const rev = setting("indexRev", DEFAULT_INDEX_REV);
157 return { rev: rev };
158 }
159
160 indexUrl(path) {
161 const base = setting("indexBaseUrl", DEFAULT_INDEX_BASE);
162 return joinUrl(base, path, this.indexQuery());
163 }
164
165 coverUrl(cover) {
166 if (!cover) {
167 return defaultCover;
168 }
169 if (/^https?:\/\//i.test(cover)) {
170 return cover;
171 }
172 let url = this.indexUrl(cover);
173 // BlueGit serveert SVG pas als afbeelding met ?as=img.
174 if (/\.svg$/i.test(cover) && url.indexOf("as=img") === -1) {
175 url += (url.indexOf("?") === -1 ? "?" : "&") + "as=img";
176 }
177 return url;
178 }
179
180 chapterSource() {
181 return String(setting("chapterSourceUrl", DEFAULT_CHAPTER_SOURCE)).replace(/\/+$/, "");
182 }
183
184 chapterMode() {
185 const mode = String(setting("chapterSource", "auto") || "auto").toLowerCase();
186 if (mode === "reddit" || mode === "arctic") {
187 return mode;
188 }
189 return "auto";
190 }
191
192 /**
193 * Maakt "Open in WebView" op een reeks of hoofdstuk tot een Reddit-URL,
194 * zodat je daar kunt inloggen. Zonder deze functie zou LNReader
195 * site+path plakken (bijv. /r/HFY/series/id), wat geen geldige Reddit-pagina is.
196 * Het reeks-id is de oudste post (eerste deel).
197 */
198 resolveUrl(path, isNovel) {
199 const raw = String(path || "").trim();
200 if (/^https?:\/\//i.test(raw)) {
201 return raw;
202 }
203 const id = chapterIdFromPath(raw) || chapterIdFromPath(raw.replace(/^series\//, "chapter/"));
204 if (id) {
205 return "https://www.reddit.com/r/HFY/comments/" + id + "/";
206 }
207 return this.site;
208 }
209
210 matchesFilters(entry, filters) {
211 const kind = filters && filters.kind ? filters.kind.value : "all";
212 const nsfw = filters && filters.nsfw ? filters.nsfw.value : "hide";
213 if (kind === "oneshot" && !entry.oneshot) {
214 return false;
215 }
216 if (kind === "series" && entry.oneshot) {
217 return false;
218 }
219 if (nsfw === "hide" && entry.nsfw) {
220 return false;
221 }
222 return true;
223 }
224
225 async loadMeta() {
226 return await readJson(this.indexUrl("catalog-meta.json"), "catalogus-meta");
227 }
228
229 async popularNovels(pageNo, options) {
230 const opts = options || {};
231 const filters = opts.filters || {};
232 const showLatest = !!opts.showLatestNovels;
233 const page = Math.max(1, parseInt(pageNo, 10) || 1);
234
235 // Zonder extra filters is de catalogus al op update-datum gesorteerd.
236 const usePagedCatalog =
237 !showLatest &&
238 (!filters.kind || filters.kind.value === "all") &&
239 (!filters.nsfw || filters.nsfw.value === "hide");
240
241 if (usePagedCatalog) {
242 const meta = await this.loadMeta();
243 const pages = meta.pages || [];
244 const spec = pages[page - 1];
245 if (!spec) {
246 return [];
247 }
248 const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);
249 const novels = (payload.novels || []).filter((n) => !n.nsfw);
250 return novels.map((n) => toNovelItem(n, this));
251 }
252
253 const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
254 let items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));
255 const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;
256 const start = (page - 1) * size;
257 return items.slice(start, start + size).map((n) => toNovelItem(n, this));
258 }
259
260 async searchNovels(searchTerm, pageNo) {
261 const term = String(searchTerm || "")
262 .trim()
263 .toLowerCase();
264 if (!term) {
265 return [];
266 }
267 const page = Math.max(1, parseInt(pageNo, 10) || 1);
268 const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
269 const hits = (search.novels || []).filter((n) => {
270 const name = String(n.name || "").toLowerCase();
271 const author = String(n.author || "").toLowerCase();
272 return name.includes(term) || author.includes(term);
273 });
274 const size = PAGE_FALLBACK_SIZE;
275 const start = (page - 1) * size;
276 return hits.slice(start, start + size).map((n) => toNovelItem(n, this));
277 }
278
279 seriesFileFor(novelPath) {
280 const id = String(novelPath || "")
281 .replace(/^series\//, "")
282 .replace(/\/+$/, "");
283 if (!id) {
284 throw new Error("HFY Novels: leeg reeks-pad");
285 }
286 const prefix = id.charAt(0).toLowerCase() || "x";
287 return "series/" + prefix + "/" + id + ".json";
288 }
289
290 async parseNovel(novelPath) {
291 const data = await readJson(this.indexUrl(this.seriesFileFor(novelPath)), "reeks " + novelPath);
292 return {
293 path: data.path || novelPath,
294 name: data.name || "Untitled",
295 author: data.author || "Anonymous",
296 artist: undefined,
297 cover: this.coverUrl(data.cover),
298 genres: data.genres || "HFY",
299 status: statusFrom(data.status),
300 summary: data.summary || "",
301 chapters: (data.chapterList || []).map((ch) => ({
302 name: ch.name,
303 path: ch.path,
304 releaseTime: ch.releaseTime || null,
305 chapterNumber: ch.chapterNumber,
306 })),
307 };
308 }
309
310
311 async parseChapter(chapterPath) {
312 const id = chapterIdFromPath(chapterPath);
313 if (!id) {
314 throw new Error("HFY Novels: ongeldig hoofdstuk-id");
315 }
316 const mode = this.chapterMode();
317 let redditError = "";
318 if (mode !== "arctic") {
319 const reddit = await tryRedditChapter(id);
320 if (reddit.ok) {
321 return renderChapter(reddit.post, "Reddit");
322 }
323 redditError = reddit.reason || "onbekende fout";
324 if (mode === "reddit") {
325 throw new Error(
326 "HFY Novels: Reddit gaf geen hoofdstuk (" +
327 redditError +
328 "). Log in via Open in WebView op reddit.com en probeer het opnieuw.",
329 );
330 }
331 }
332 const arctic = await tryArcticChapter(this.chapterSource(), id);
333 if (arctic.ok) {
334 const suffix = mode === "arctic" ? "Arctic Shift" : "Arctic Shift (fallback)";
335 return renderChapter(arctic.post, suffix);
336 }
337 if (redditError) {
338 throw new Error(
339 "HFY Novels: Reddit (" +
340 redditError +
341 ") en Arctic Shift (" +
342 (arctic.reason || "geen tekst") +
343 ") faalden allebei.",
344 );
345 }
346 throw new Error("HFY Novels: kon hoofdstuk " + id + " niet laden (" + (arctic.reason || "geen tekst") + ")");
347 }
348}
349
350function chapterIdFromPath(chapterPath) {
351 const id = String(chapterPath || "")
352 .replace(/^chapter\//, "")
353 .replace(/^series\//, "")
354 .trim()
355 .toLowerCase();
356 return /^[0-9a-z]{4,10}$/.test(id) ? id : "";
357}
358
359function redditJsonUrls(id) {
360 const path = "/r/HFY/comments/" + id + "/.json?raw_json=1";
361 return [
362 "https://www.reddit.com" + path,
363 "https://old.reddit.com" + path,
364 ];
365}
366
367function looksLikeHtml(text) {
368 const body = String(text || "").trim();
369 if (!body) {
370 return false;
371 }
372 return /^\s*<(!DOCTYPE|html|body|head)\b/i.test(body);
373}
374
375function isLoginOrBlockPage(res, body) {
376 const status = res && res.status != null ? Number(res.status) : 0;
377 if (status === 401 || status === 403 || status === 429) {
378 return true;
379 }
380 const finalUrl = String((res && res.url) || "");
381 if (/[?&]reason=lor2\b/i.test(finalUrl) || /\/login\b/i.test(finalUrl)) {
382 return true;
383 }
384 const type = String(
385 (res && res.headers && typeof res.headers.get === "function" && res.headers.get("content-type")) || "",
386 ).toLowerCase();
387 if (type.indexOf("text/html") !== -1 && !/json/i.test(type)) {
388 return true;
389 }
390 const text = String(body || "");
391 if (looksLikeHtml(text)) {
392 return true;
393 }
394 const lower = text.toLowerCase();
395 if (
396 lower.indexOf("reason=lor2") !== -1 ||
397 lower.indexOf("www.reddit.com/login") !== -1 ||
398 lower.indexOf("old.reddit.com/login") !== -1 ||
399 lower.indexOf("log in to reddit") !== -1 ||
400 (lower.indexOf("shreddit") !== -1 && lower.indexOf("<!doctype html") !== -1)
401 ) {
402 return true;
403 }
404 return false;
405}
406
407function postFromRedditPayload(payload) {
408 if (!payload) {
409 return null;
410 }
411 const listing = Array.isArray(payload) ? payload[0] : payload;
412 const children =
413 listing && listing.data && Array.isArray(listing.data.children) ? listing.data.children : [];
414 const child = children.find((c) => !c.kind || c.kind === "t3") || children[0];
415 if (!child || !child.data) {
416 return null;
417 }
418 if (child.kind && child.kind !== "t3") {
419 return null;
420 }
421 return child.data;
422}
423
424function decodeRedditHtml(html) {
425 let text = String(html || "");
426 if (text.indexOf("&lt;") !== -1 || text.indexOf("&amp;") !== -1) {
427 text = text
428 .replace(/&lt;/g, "<")
429 .replace(/&gt;/g, ">")
430 .replace(/&quot;/g, '"')
431 .replace(/&#39;/g, "'")
432 .replace(/&amp;/g, "&");
433 }
434 return text;
435}
436
437async function tryRedditChapter(id) {
438 let lastReason = "geen antwoord";
439 const urls = redditJsonUrls(id);
440 for (let i = 0; i < urls.length; i++) {
441 const url = urls[i];
442 try {
443 const res = await fetchApi(url, { headers: { Accept: "application/json" } });
444 const body = typeof res.text === "function" ? await res.text() : "";
445 if (!res || res.ok === false || isLoginOrBlockPage(res, body)) {
446 const status = res && res.status != null ? res.status : "?";
447 lastReason = "HTTP " + status + (isLoginOrBlockPage(res, body) ? " (login of blokkade)" : "");
448 continue;
449 }
450 if (!body || looksLikeHtml(body)) {
451 lastReason = "geen JSON";
452 continue;
453 }
454 let payload;
455 try {
456 payload = JSON.parse(body);
457 } catch (err) {
458 lastReason = "ongeldige JSON";
459 continue;
460 }
461 const post = postFromRedditPayload(payload);
462 if (!post) {
463 lastReason = "geen post in de listing";
464 continue;
465 }
466 return { ok: true, post: post };
467 } catch (err) {
468 lastReason = err && err.message ? err.message : String(err);
469 }
470 }
471 return { ok: false, reason: lastReason };
472}
473
474async function tryArcticChapter(base, id) {
475 const url = String(base || "").replace(/\/+$/, "") + "/api/posts/ids?ids=" + encodeURIComponent(id) + "&md2html=true";
476 try {
477 const payload = await readJson(url, "hoofdstuk " + id);
478 const posts = payload.data || payload;
479 const post = Array.isArray(posts) ? posts[0] : posts;
480 if (!post) {
481 return { ok: false, reason: "leeg antwoord" };
482 }
483 return { ok: true, post: post };
484 } catch (err) {
485 return { ok: false, reason: err && err.message ? err.message : String(err) };
486 }
487}
488
489function sourceFooter(label) {
490 return '<p class="hfy-source"><em>Bron: ' + escapeHtml(label) + "</em></p>";
491}
492
493function renderChapter(post, sourceLabel) {
494 if (!post) {
495 return "<p><em>Dit hoofdstuk is niet (meer) beschikbaar.</em></p>" + sourceFooter(sourceLabel);
496 }
497 const title = post.title ? "<h1>" + escapeHtml(post.title) + "</h1>" : "";
498 const by = post.author ? "<p><em>by u/" + escapeHtml(post.author) + "</em></p>" : "";
499 const rawHtml = post.selftext_html ? decodeRedditHtml(post.selftext_html) : "";
500 const html = rawHtml ? sanitizeHtml(rawHtml) : markdownToHtml(post.selftext || "");
501 if (!html) {
502 return (
503 title +
504 by +
505 "<p><em>Deze post heeft geen tekst (verwijderd of een link-post).</em></p>" +
506 sourceFooter(sourceLabel)
507 );
508 }
509 return title + by + html + sourceFooter(sourceLabel);
510}
511
512function escapeHtml(text) {
513 return String(text)
514 .replace(/&/g, "&amp;")
515 .replace(/</g, "&lt;")
516 .replace(/>/g, "&gt;")
517 .replace(/"/g, "&quot;");
518}
519
520function sanitizeHtml(html) {
521 // Reddit en Arctic Shift leveren HTML; we strippen scripts en on-event-attributen.
522 return String(html)
523 .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "")
524 .replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "");
525}
526
527function markdownToHtml(md) {
528 if (!md) {
529 return "";
530 }
531 const escaped = escapeHtml(md);
532 const withLinks = escaped.replace(
533 /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,
534 '<a href="$2">$1</a>',
535 );
536 const paragraphs = withLinks
537 .split(/\n{2,}/)
538 .map((block) => "<p>" + block.replace(/\n/g, "<br>") + "</p>");
539 return paragraphs.join("");
540}
541
542const instance = new HFYNovelsPlugin();
543exports.default = instance;