BlueGit

timfa hfy-novels

Files

hfy-novels / plugin / hfy-novels.js

hfy-novels.js

hfy-novels.js 9.7 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 * haalt een hoofdstuk live op via de Arctic Shift-API (optioneel te
9 * overschrijven in de plugin-instellingen).
10 *
11 * Dit bestand is CommonJS, zoals de officiële gecompileerde plugins:
12 * require(...) uit de LNReader-allowlist, en `exports.default = instance`.
13 */
14
15Object.defineProperty(exports, "__esModule", { value: true });
16
17const { fetchApi } = require("@libs/fetch");
18const { FilterTypes } = require("@libs/filterInputs");
19const { defaultCover } = require("@libs/defaultCover");
20const { NovelStatus } = require("@libs/novelStatus");
21const { storage } = require("@libs/storage");
22
23const DEFAULT_INDEX_BASE =
24 "https://git.timfalken.com/timfa/hfy-novels/-/raw/public";
25const DEFAULT_INDEX_REV = "master";
26const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";
27const PAGE_FALLBACK_SIZE = 50;
28
29function setting(key, fallback) {
30 try {
31 const value = storage.get(key);
32 if (value === undefined || value === null || value === "") {
33 return fallback;
34 }
35 return value;
36 } catch (err) {
37 return fallback;
38 }
39}
40
41function joinUrl(base, path, query) {
42 const trimmedBase = String(base || "").replace(/\/+$/, "");
43 const trimmedPath = String(path || "").replace(/^\/+/, "");
44 let url = trimmedBase + "/" + trimmedPath;
45 const params = [];
46 if (query && typeof query === "object") {
47 for (const [k, v] of Object.entries(query)) {
48 if (v !== undefined && v !== null && v !== "") {
49 params.push(encodeURIComponent(k) + "=" + encodeURIComponent(String(v)));
50 }
51 }
52 }
53 if (params.length) {
54 url += (url.includes("?") ? "&" : "?") + params.join("&");
55 }
56 return url;
57}
58
59function statusFrom(text) {
60 switch (text) {
61 case "Completed":
62 return NovelStatus.Completed;
63 case "Ongoing":
64 return NovelStatus.Ongoing;
65 case "On Hiatus":
66 return NovelStatus.OnHiatus;
67 default:
68 return NovelStatus.Unknown;
69 }
70}
71
72async function readJson(url, label) {
73 const res = await fetchApi(url);
74 if (!res || res.ok === false) {
75 const status = res && res.status != null ? res.status : "?";
76 throw new Error("HFY Novels: kon " + label + " niet laden (HTTP " + status + ")");
77 }
78 if (typeof res.json === "function") {
79 return await res.json();
80 }
81 const text = await res.text();
82 return JSON.parse(text);
83}
84
85function toNovelItem(entry, plugin) {
86 return {
87 name: entry.name,
88 path: entry.path,
89 cover: plugin.coverUrl(entry.cover),
90 };
91}
92
93class HFYNovelsPlugin {
94 constructor() {
95 this.id = "hfyNovels";
96 this.name = "HFY Novels";
97 this.version = "0.1.0";
98 this.site = "https://www.reddit.com/r/HFY/";
99 this.icon = "icon.png";
100 this.filters = {
101 kind: {
102 value: "all",
103 label: "Type",
104 options: [
105 { label: "Alles", value: "all" },
106 { label: "Reeksen", value: "series" },
107 { label: "Oneshots", value: "oneshot" },
108 ],
109 type: FilterTypes.Picker,
110 },
111 nsfw: {
112 value: "hide",
113 label: "NSFW",
114 options: [
115 { label: "Verbergen", value: "hide" },
116 { label: "Tonen", value: "show" },
117 ],
118 type: FilterTypes.Picker,
119 },
120 };
121 this.pluginSettings = {
122 indexBaseUrl: {
123 value: DEFAULT_INDEX_BASE,
124 label: "Basis-URL van de index",
125 type: "Text",
126 },
127 indexRev: {
128 value: DEFAULT_INDEX_REV,
129 label: "Git-revisie van de index (rev=)",
130 type: "Text",
131 },
132 chapterSourceUrl: {
133 value: DEFAULT_CHAPTER_SOURCE,
134 label: "Bron voor hoofdstuktekst (Arctic Shift)",
135 type: "Text",
136 },
137 };
138 }
139
140 indexQuery() {
141 const rev = setting("indexRev", DEFAULT_INDEX_REV);
142 return { rev: rev };
143 }
144
145 indexUrl(path) {
146 const base = setting("indexBaseUrl", DEFAULT_INDEX_BASE);
147 return joinUrl(base, path, this.indexQuery());
148 }
149
150 coverUrl(cover) {
151 if (!cover) {
152 return defaultCover;
153 }
154 if (/^https?:\/\//i.test(cover)) {
155 return cover;
156 }
157 let url = this.indexUrl(cover);
158 // BlueGit serveert SVG pas als afbeelding met ?as=img.
159 if (/\.svg$/i.test(cover) && url.indexOf("as=img") === -1) {
160 url += (url.indexOf("?") === -1 ? "?" : "&") + "as=img";
161 }
162 return url;
163 }
164
165 chapterSource() {
166 return String(setting("chapterSourceUrl", DEFAULT_CHAPTER_SOURCE)).replace(/\/+$/, "");
167 }
168
169 matchesFilters(entry, filters) {
170 const kind = filters && filters.kind ? filters.kind.value : "all";
171 const nsfw = filters && filters.nsfw ? filters.nsfw.value : "hide";
172 if (kind === "oneshot" && !entry.oneshot) {
173 return false;
174 }
175 if (kind === "series" && entry.oneshot) {
176 return false;
177 }
178 if (nsfw === "hide" && entry.nsfw) {
179 return false;
180 }
181 return true;
182 }
183
184 async loadMeta() {
185 return await readJson(this.indexUrl("catalog-meta.json"), "catalogus-meta");
186 }
187
188 async popularNovels(pageNo, options) {
189 const opts = options || {};
190 const filters = opts.filters || {};
191 const showLatest = !!opts.showLatestNovels;
192 const page = Math.max(1, parseInt(pageNo, 10) || 1);
193
194 // Zonder extra filters is de catalogus al op update-datum gesorteerd.
195 const usePagedCatalog =
196 !showLatest &&
197 (!filters.kind || filters.kind.value === "all") &&
198 (!filters.nsfw || filters.nsfw.value === "hide");
199
200 if (usePagedCatalog) {
201 const meta = await this.loadMeta();
202 const pages = meta.pages || [];
203 const spec = pages[page - 1];
204 if (!spec) {
205 return [];
206 }
207 const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);
208 const novels = (payload.novels || []).filter((n) => !n.nsfw);
209 return novels.map((n) => toNovelItem(n, this));
210 }
211
212 const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
213 let items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));
214 const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;
215 const start = (page - 1) * size;
216 return items.slice(start, start + size).map((n) => toNovelItem(n, this));
217 }
218
219 async searchNovels(searchTerm, pageNo) {
220 const term = String(searchTerm || "")
221 .trim()
222 .toLowerCase();
223 if (!term) {
224 return [];
225 }
226 const page = Math.max(1, parseInt(pageNo, 10) || 1);
227 const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
228 const hits = (search.novels || []).filter((n) => {
229 const name = String(n.name || "").toLowerCase();
230 const author = String(n.author || "").toLowerCase();
231 return name.includes(term) || author.includes(term);
232 });
233 const size = PAGE_FALLBACK_SIZE;
234 const start = (page - 1) * size;
235 return hits.slice(start, start + size).map((n) => toNovelItem(n, this));
236 }
237
238 seriesFileFor(novelPath) {
239 const id = String(novelPath || "")
240 .replace(/^series\//, "")
241 .replace(/\/+$/, "");
242 if (!id) {
243 throw new Error("HFY Novels: leeg reeks-pad");
244 }
245 const prefix = id.charAt(0).toLowerCase() || "x";
246 return "series/" + prefix + "/" + id + ".json";
247 }
248
249 async parseNovel(novelPath) {
250 const data = await readJson(this.indexUrl(this.seriesFileFor(novelPath)), "reeks " + novelPath);
251 return {
252 path: data.path || novelPath,
253 name: data.name || "Untitled",
254 author: data.author || "Anonymous",
255 artist: undefined,
256 cover: this.coverUrl(data.cover),
257 genres: data.genres || "HFY",
258 status: statusFrom(data.status),
259 summary: data.summary || "",
260 chapters: (data.chapterList || []).map((ch) => ({
261 name: ch.name,
262 path: ch.path,
263 releaseTime: ch.releaseTime || null,
264 chapterNumber: ch.chapterNumber,
265 })),
266 };
267 }
268
269 async parseChapter(chapterPath) {
270 const id = String(chapterPath || "")
271 .replace(/^chapter\//, "")
272 .trim()
273 .toLowerCase();
274 if (!/^[0-9a-z]{4,10}$/.test(id)) {
275 throw new Error("HFY Novels: ongeldig hoofdstuk-id");
276 }
277 const url =
278 this.chapterSource() +
279 "/api/posts/ids?ids=" +
280 encodeURIComponent(id) +
281 "&md2html=true";
282 const payload = await readJson(url, "hoofdstuk " + id);
283 const posts = payload.data || payload;
284 const post = Array.isArray(posts) ? posts[0] : posts;
285 if (!post) {
286 return "<p><em>Dit hoofdstuk is niet (meer) beschikbaar.</em></p>";
287 }
288 const title = post.title ? "<h1>" + escapeHtml(post.title) + "</h1>" : "";
289 const by = post.author
290 ? "<p><em>by u/" + escapeHtml(post.author) + "</em></p>"
291 : "";
292 const html = post.selftext_html
293 ? sanitizeHtml(post.selftext_html)
294 : markdownToHtml(post.selftext || "");
295 if (!html) {
296 return title + by + "<p><em>Deze post heeft geen tekst (verwijderd of een link-post).</em></p>";
297 }
298 return title + by + html;
299 }
300}
301
302function escapeHtml(text) {
303 return String(text)
304 .replace(/&/g, "&amp;")
305 .replace(/</g, "&lt;")
306 .replace(/>/g, "&gt;")
307 .replace(/"/g, "&quot;");
308}
309
310function sanitizeHtml(html) {
311 // Arctic Shift levert al HTML; we strippen scripts en on-event-attributen.
312 return String(html)
313 .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "")
314 .replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "");
315}
316
317function markdownToHtml(md) {
318 if (!md) {
319 return "";
320 }
321 const escaped = escapeHtml(md);
322 const withLinks = escaped.replace(
323 /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,
324 '<a href="$2">$1</a>',
325 );
326 const paragraphs = withLinks
327 .split(/\n{2,}/)
328 .map((block) => "<p>" + block.replace(/\n/g, "<br>") + "</p>");
329 return paragraphs.join("");
330}
331
332const instance = new HFYNovelsPlugin();
333exports.default = instance;