BlueGit

timfa hfy-novels

Files

hfy-novels / plugin / hfy-novels.js

hfy-novels.js

hfy-novels.js 49.4 KiB Download Raw
1"use strict";
2
3/**
4 * LNReader-plugin voor r/HFY.
5 *
6 * De catalogus wordt live opgebouwd op de telefoon, met de Reddit-sessie
7 * uit de LNReader-WebView (elk account heeft zijn eigen cookies):
8 * - popularNovels: de wiki-serie-index, plus 'Nieuw' / Latest met recente OC-posts
9 * - searchNovels: r/HFY/search.json (restrict_sr=1), plus hits uit de wiki,
10 * waarbij series en losse Part-1-posts tot één novel worden gegroepeerd
11 * - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis
12 *
13 * Verhalen zonder vooraf gemaakte cover krijgen een deterministische
14 * titel-cover als data:image/png;base64 (zelfde hash en stijl als de index).
15 *
16 * Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,
17 * en daarna op de statische metadata-index (ook bruikbaar zonder login).
18 * parseChapter probeert eerst Reddit-JSON, daarna Arctic Shift.
19 *
20 * Dit bestand is CommonJS, zoals de officiële gecompileerde plugins:
21 * require(...) uit de LNReader-allowlist, en `exports.default = instance`.
22 */
23
24Object.defineProperty(exports, "__esModule", { value: true });
25
26const { fetchApi } = require("@libs/fetch");
27const { FilterTypes } = require("@libs/filterInputs");
28const { defaultCover } = require("@libs/defaultCover");
29const { NovelStatus } = require("@libs/novelStatus");
30const { storage } = require("@libs/storage");
31
32const DEFAULT_INDEX_BASE =
33 "https://git.timfalken.com/timfa/hfy-novels/-/raw/public";
34const DEFAULT_INDEX_REV = "master";
35const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";
36const PAGE_FALLBACK_SIZE = 50;
37const WIKI_CACHE_KEY = "wikiSeriesIndex";
38const WIKI_CACHE_MS = 6 * 60 * 60 * 1000;
39const REDDIT_WWW = "https://www.reddit.com";
40const REDDIT_OLD = "https://old.reddit.com";
41const WIKI_INDEX_PATH = "/r/HFY/wiki/series";
42
43function setting(key, fallback) {
44 try {
45 const value = storage.get(key);
46 if (value === undefined || value === null || value === "") {
47 return fallback;
48 }
49 return value;
50 } catch (err) {
51 return fallback;
52 }
53}
54
55function joinUrl(base, path, query) {
56 const trimmedBase = String(base || "").replace(/\/+$/, "");
57 const trimmedPath = String(path || "").replace(/^\/+/, "");
58 let url = trimmedBase + "/" + trimmedPath;
59 const params = [];
60 if (query && typeof query === "object") {
61 for (const [k, v] of Object.entries(query)) {
62 if (v !== undefined && v !== null && v !== "") {
63 params.push(encodeURIComponent(k) + "=" + encodeURIComponent(String(v)));
64 }
65 }
66 }
67 if (params.length) {
68 url += (url.includes("?") ? "&" : "?") + params.join("&");
69 }
70 return url;
71}
72
73function statusFrom(text) {
74 switch (text) {
75 case "Completed":
76 return NovelStatus.Completed;
77 case "Ongoing":
78 return NovelStatus.Ongoing;
79 case "On Hiatus":
80 return NovelStatus.OnHiatus;
81 default:
82 return NovelStatus.Unknown;
83 }
84}
85
86async function readJson(url, label) {
87 const res = await fetchApi(url);
88 if (!res || res.ok === false) {
89 const status = res && res.status != null ? res.status : "?";
90 throw new Error("HFY Novels: kon " + label + " niet laden (HTTP " + status + ")");
91 }
92 if (typeof res.json === "function") {
93 return await res.json();
94 }
95 const text = await res.text();
96 return JSON.parse(text);
97}
98
99function toNovelItem(entry, plugin) {
100 return {
101 name: entry.name,
102 path: entry.path,
103 cover: plugin.coverFor(entry),
104 };
105}
106
107class HFYNovelsPlugin {
108 constructor() {
109 this.id = "hfyNovels";
110 this.name = "HFY Novels";
111 this.version = "0.3.1";
112 this.site = "https://www.reddit.com/r/HFY/";
113 this.icon = "icon.png";
114 if (typeof CoverUtils !== "undefined") {
115 this.coverUtils = CoverUtils;
116 }
117 // Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's
118 // fetchApi (native fetch) stuurt de WebView-cookies automatisch mee
119 // voor hetzelfde domein; localStorage is daarvoor niet nodig.
120 this.filters = {
121 catalog: {
122 value: "wiki",
123 label: "Overzicht",
124 options: [
125 { label: "Wiki-series", value: "wiki" },
126 { label: "Nieuw", value: "new" },
127 ],
128 type: FilterTypes.Picker,
129 },
130 kind: {
131 value: "all",
132 label: "Type",
133 options: [
134 { label: "Alles", value: "all" },
135 { label: "Reeksen", value: "series" },
136 { label: "Oneshots", value: "oneshot" },
137 ],
138 type: FilterTypes.Picker,
139 },
140 nsfw: {
141 value: "hide",
142 label: "NSFW",
143 options: [
144 { label: "Verbergen", value: "hide" },
145 { label: "Tonen", value: "show" },
146 ],
147 type: FilterTypes.Picker,
148 },
149 };
150 this.pluginSettings = {
151 indexBaseUrl: {
152 value: DEFAULT_INDEX_BASE,
153 label: "Basis-URL van de statische index (laatste fallback)",
154 type: "Text",
155 },
156 indexRev: {
157 value: DEFAULT_INDEX_REV,
158 label: "Git-revisie van de index (rev=)",
159 type: "Text",
160 },
161 chapterSource: {
162 value: "auto",
163 label: "Bron voor catalogus en hoofdstukken",
164 type: "Select",
165 options: [
166 { label: "Automatisch (Reddit, anders Arctic Shift, anders index)", value: "auto" },
167 { label: "Alleen Reddit", value: "reddit" },
168 { label: "Alleen Arctic Shift (daarna index)", value: "arctic" },
169 ],
170 },
171 chapterSourceUrl: {
172 value: DEFAULT_CHAPTER_SOURCE,
173 label: "Arctic Shift-basis-URL (fallback)",
174 type: "Text",
175 },
176 };
177 }
178
179 indexQuery() {
180 const rev = setting("indexRev", DEFAULT_INDEX_REV);
181 return { rev: rev };
182 }
183
184 indexUrl(path) {
185 const base = setting("indexBaseUrl", DEFAULT_INDEX_BASE);
186 return joinUrl(base, path, this.indexQuery());
187 }
188
189 coverFor(entry) {
190 if (entry && entry.cover) {
191 return this.coverUrl(entry.cover);
192 }
193 const name = entry && entry.name;
194 if (name && typeof coverDataUri === "function") {
195 return coverDataUri(name);
196 }
197 return defaultCover;
198 }
199
200 coverUrl(cover) {
201 if (!cover) {
202 return defaultCover;
203 }
204 if (/^data:image\//i.test(cover)) {
205 return cover;
206 }
207 if (/^https?:\/\//i.test(cover)) {
208 return cover;
209 }
210 let url = this.indexUrl(cover);
211 // BlueGit serveert SVG pas als afbeelding met ?as=img.
212 if (/\.svg$/i.test(cover) && url.indexOf("as=img") === -1) {
213 url += (url.indexOf("?") === -1 ? "?" : "&") + "as=img";
214 }
215 return url;
216 }
217
218 chapterSource() {
219 return String(setting("chapterSourceUrl", DEFAULT_CHAPTER_SOURCE)).replace(/\/+$/, "");
220 }
221
222 chapterMode() {
223 const mode = String(setting("chapterSource", "auto") || "auto").toLowerCase();
224 if (mode === "reddit" || mode === "arctic") {
225 return mode;
226 }
227 return "auto";
228 }
229
230 /**
231 * Maakt "Open in WebView" op een reeks of hoofdstuk tot een Reddit-URL,
232 * zodat je daar kunt inloggen. Zonder deze functie zou LNReader
233 * site+path plakken (bijv. /r/HFY/series/id), wat geen geldige Reddit-pagina is.
234 * Het reeks-id is de oudste post (eerste deel), of een wiki-slug.
235 */
236 resolveUrl(path, isNovel) {
237 const raw = String(path || "").trim();
238 if (/^https?:\/\//i.test(raw)) {
239 return raw;
240 }
241 const wikiSlug = wikiSlugFromPath(raw);
242 if (wikiSlug) {
243 return REDDIT_WWW + "/r/HFY/wiki/series/" + wikiSlug + "/";
244 }
245 const id = chapterIdFromPath(raw) || chapterIdFromPath(raw.replace(/^series\//, "chapter/"));
246 if (id) {
247 return REDDIT_WWW + "/r/HFY/comments/" + id + "/";
248 }
249 return this.site;
250 }
251
252 matchesFilters(entry, filters) {
253 const kind = filters && filters.kind ? filters.kind.value : "all";
254 const nsfw = filters && filters.nsfw ? filters.nsfw.value : "hide";
255 if (kind === "oneshot" && !entry.oneshot) {
256 return false;
257 }
258 if (kind === "series" && entry.oneshot) {
259 return false;
260 }
261 if (nsfw === "hide" && entry.nsfw) {
262 return false;
263 }
264 return true;
265 }
266
267 async loadMeta() {
268 return await readJson(this.indexUrl("catalog-meta.json"), "catalogus-meta");
269 }
270
271 async popularNovels(pageNo, options) {
272 const opts = options || {};
273 const filters = opts.filters || {};
274 const showLatest = !!opts.showLatestNovels || (filters.catalog && filters.catalog.value === "new");
275 const page = Math.max(1, parseInt(pageNo, 10) || 1);
276 const mode = this.chapterMode();
277
278 if (showLatest) {
279 const live = await this.liveLatestNovels(page, filters, mode);
280 if (live && live.ok) {
281 return live.items;
282 }
283 if (mode === "reddit") {
284 throw new Error(
285 "HFY Novels: Reddit gaf geen nieuwe posts (" +
286 ((live && live.reason) || "onbekende fout") +
287 "). Log in via Open in WebView op reddit.com en probeer het opnieuw.",
288 );
289 }
290 return await this.staticPopular(page, opts);
291 }
292
293 const live = await this.liveWikiNovels(page, filters, mode);
294 if (live && live.ok) {
295 return live.items;
296 }
297 if (mode === "reddit") {
298 throw new Error(
299 "HFY Novels: Reddit gaf de wiki-index niet (" +
300 ((live && live.reason) || "onbekende fout") +
301 "). Log in via Open in WebView op reddit.com en probeer het opnieuw.",
302 );
303 }
304 return await this.staticPopular(page, opts);
305 }
306
307 async searchNovels(searchTerm, pageNo) {
308 const term = String(searchTerm || "").trim();
309 if (!term) {
310 return [];
311 }
312 const page = Math.max(1, parseInt(pageNo, 10) || 1);
313 const mode = this.chapterMode();
314 const live = await this.liveSearchNovels(term, page, mode);
315 if (live && live.ok) {
316 return live.items;
317 }
318 if (mode === "reddit") {
319 throw new Error(
320 "HFY Novels: Reddit-zoeken mislukte (" +
321 ((live && live.reason) || "onbekende fout") +
322 "). Log in via Open in WebView op reddit.com en probeer het opnieuw.",
323 );
324 }
325 return await this.staticSearch(term, page);
326 }
327
328 seriesFileFor(novelPath) {
329 const id = String(novelPath || "")
330 .replace(/^series\//, "")
331 .replace(/\/+$/, "");
332 if (!id) {
333 throw new Error("HFY Novels: leeg reeks-pad");
334 }
335 const prefix = id.charAt(0).toLowerCase() || "x";
336 return "series/" + prefix + "/" + id + ".json";
337 }
338
339 async parseNovel(novelPath) {
340 const mode = this.chapterMode();
341 const live = await this.liveParseNovel(novelPath, mode);
342 if (mode === "reddit" && (!live || !live.ok)) {
343 throw new Error(
344 "HFY Novels: Reddit gaf de hoofdstuklijst niet (" +
345 ((live && live.reason) || "onbekende fout") +
346 "). Log in via Open in WebView op reddit.com en probeer het opnieuw.",
347 );
348 }
349 let novel = live && live.ok ? live.novel : null;
350 if (!wikiSlugFromPath(novelPath)) {
351 try {
352 const fallback = await this.staticParseNovel(novelPath);
353 if (!novel) {
354 return fallback;
355 }
356 // De statische index kan een langere inhoudsopgave hebben dan een
357 // enkele live-post zonder werkende next-link; neem dan die lijst.
358 if ((fallback.chapters || []).length > (novel.chapters || []).length) {
359 novel.chapters = fallback.chapters;
360 if (fallback.cover) {
361 novel.cover = fallback.cover;
362 }
363 if (!novel.summary && fallback.summary) {
364 novel.summary = fallback.summary;
365 }
366 }
367 return novel;
368 } catch (err) {
369 if (novel) {
370 return novel;
371 }
372 throw err;
373 }
374 }
375 if (novel) {
376 return novel;
377 }
378 throw new Error(
379 "HFY Novels: kon de reeks " +
380 novelPath +
381 " niet live bepalen (" +
382 ((live && live.reason) || "geen bron") +
383 ").",
384 );
385 }
386
387 async parseChapter(chapterPath) {
388 const id = chapterIdFromPath(chapterPath);
389 if (!id) {
390 throw new Error("HFY Novels: ongeldig hoofdstuk-id");
391 }
392 const mode = this.chapterMode();
393 let redditError = "";
394 if (mode !== "arctic") {
395 const reddit = await tryRedditChapter(id);
396 if (reddit.ok) {
397 return renderChapter(reddit.post, "Reddit");
398 }
399 redditError = reddit.reason || "onbekende fout";
400 if (mode === "reddit") {
401 throw new Error(
402 "HFY Novels: Reddit gaf geen hoofdstuk (" +
403 redditError +
404 "). Log in via Open in WebView op reddit.com en probeer het opnieuw.",
405 );
406 }
407 }
408 const arctic = await tryArcticChapter(this.chapterSource(), id);
409 if (arctic.ok) {
410 const suffix = mode === "arctic" ? "Arctic Shift" : "Arctic Shift (fallback)";
411 return renderChapter(arctic.post, suffix);
412 }
413 if (redditError) {
414 throw new Error(
415 "HFY Novels: Reddit (" +
416 redditError +
417 ") en Arctic Shift (" +
418 (arctic.reason || "geen tekst") +
419 ") faalden allebei.",
420 );
421 }
422 throw new Error("HFY Novels: kon hoofdstuk " + id + " niet laden (" + (arctic.reason || "geen tekst") + ")");
423 }
424
425 async staticPopular(pageNo, options) {
426 const opts = options || {};
427 const filters = opts.filters || {};
428 const showLatest = !!opts.showLatestNovels || (filters.catalog && filters.catalog.value === "new");
429 const page = Math.max(1, parseInt(pageNo, 10) || 1);
430 const usePagedCatalog =
431 !showLatest &&
432 (!filters.kind || filters.kind.value === "all") &&
433 (!filters.nsfw || filters.nsfw.value === "hide");
434
435 if (usePagedCatalog) {
436 const meta = await this.loadMeta();
437 const pages = meta.pages || [];
438 const spec = pages[page - 1];
439 if (!spec) {
440 return [];
441 }
442 const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);
443 const novels = (payload.novels || []).filter((n) => !n.nsfw);
444 return novels.map((n) => toNovelItem(n, this));
445 }
446
447 const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
448 const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));
449 const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;
450 const start = (page - 1) * size;
451 return items.slice(start, start + size).map((n) => toNovelItem(n, this));
452 }
453
454 async staticSearch(searchTerm, pageNo) {
455 const term = String(searchTerm || "").trim().toLowerCase();
456 if (!term) {
457 return [];
458 }
459 const page = Math.max(1, parseInt(pageNo, 10) || 1);
460 const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
461 const hits = (search.novels || []).filter((n) => {
462 const name = String(n.name || "").toLowerCase();
463 const author = String(n.author || "").toLowerCase();
464 return name.includes(term) || author.includes(term);
465 });
466 const start = (page - 1) * PAGE_FALLBACK_SIZE;
467 return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(n, this));
468 }
469
470 async staticParseNovel(novelPath) {
471 const data = await readJson(this.indexUrl(this.seriesFileFor(novelPath)), "reeks " + novelPath);
472 return {
473 path: data.path || novelPath,
474 name: data.name || "Untitled",
475 author: data.author || "Anonymous",
476 artist: undefined,
477 cover: this.coverFor({ name: data.name, cover: data.cover }),
478 genres: data.genres || "HFY",
479 status: statusFrom(data.status),
480 summary: data.summary || "",
481 chapters: (data.chapterList || []).map((ch) => ({
482 name: ch.name,
483 path: ch.path,
484 releaseTime: ch.releaseTime || null,
485 chapterNumber: ch.chapterNumber,
486 })),
487 };
488 }
489
490 async liveWikiNovels(page, filters, mode) {
491 const fetched = await this.loadWikiIndex(mode);
492 if (!fetched.ok) {
493 return fetched;
494 }
495 let items = fetched.entries.map((entry) => wikiEntryToItem(entry, this));
496 items = items.filter((entry) => this.matchesFilters(entry, filters));
497 const start = (page - 1) * PAGE_FALLBACK_SIZE;
498 return { ok: true, items: items.slice(start, start + PAGE_FALLBACK_SIZE), source: fetched.source };
499 }
500
501 async liveLatestNovels(page, filters, mode) {
502 const fetched = await this.loadRecentOcPosts(page, mode);
503 if (!fetched.ok) {
504 return fetched;
505 }
506 const grouped = groupPostsIntoNovels(fetched.posts, fetched.wikiEntries || []);
507 const items = grouped
508 .filter((entry) => this.matchesFilters(entry, filters))
509 .map((entry) => toNovelItem(entry, this));
510 return { ok: true, items: items, source: fetched.source };
511 }
512
513 async liveSearchNovels(term, page, mode) {
514 const wiki = await this.loadWikiIndex(mode === "reddit" ? "reddit" : "auto");
515 const wikiHits = (wiki.ok ? wiki.entries : []).filter((entry) => wikiEntryMatches(entry, term));
516 const postsRes = await this.loadSearchPosts(term, page, mode);
517 if (!postsRes.ok && !wiki.ok) {
518 return postsRes.ok === false ? postsRes : wiki;
519 }
520 const grouped = groupPostsIntoNovels(postsRes.ok ? postsRes.posts : [], wiki.ok ? wiki.entries : []);
521 const byKey = {};
522 const items = [];
523 function addItem(entry) {
524 const key = (entry.path || "") + "|" + normalizeTitle(entry.name);
525 if (byKey[key]) {
526 return;
527 }
528 byKey[key] = true;
529 items.push(toNovelItem(entry, this));
530 }
531 const add = addItem.bind(this);
532 wikiHits.forEach((entry) => add(wikiEntryToItem(entry, this)));
533 grouped.forEach((entry) => add(entry));
534 if (!items.length && !postsRes.ok) {
535 return { ok: false, reason: postsRes.reason || (wiki.ok ? "geen treffers" : wiki.reason) };
536 }
537 const start = (page - 1) * PAGE_FALLBACK_SIZE;
538 return { ok: true, items: items.slice(start, start + PAGE_FALLBACK_SIZE) };
539 }
540
541 async liveParseNovel(novelPath, mode) {
542 const wikiSlug = wikiSlugFromPath(novelPath);
543 const startId = chapterIdFromPath(novelPath) || chapterIdFromPath(String(novelPath).replace(/^series\//, "chapter/"));
544 let entry = null;
545 let reason = "";
546
547 if (wikiSlug) {
548 const page = await this.loadWikiPage(wikiSlug, mode);
549 if (page.ok) {
550 entry = page.entry;
551 } else {
552 reason = page.reason || "wiki-subpagina ontbreekt";
553 if (mode === "reddit") {
554 return { ok: false, reason: reason };
555 }
556 }
557 }
558
559 const seedId = (entry && (entry.firstId || (entry.chapterIds && entry.chapterIds[0]))) || startId;
560 const wanted = uniqueIds([].concat((entry && entry.chapterIds) || [], seedId ? [seedId] : []));
561 const fetched = await this.loadPostsByIds(wanted, mode);
562 if (!fetched.ok && !fetched.posts.length) {
563 return { ok: false, reason: reason || fetched.reason || "geen posts" };
564 }
565 const byId = {};
566 fetched.posts.forEach((post) => {
567 const id = postId(post);
568 if (id) {
569 byId[id] = post;
570 }
571 });
572 const toc = wanted.map((id) => byId[id]).filter(Boolean);
573 let members = toc.slice();
574 const startPost = toc.length ? toc[toc.length - 1] : byId[seedId];
575 if (startPost) {
576 const tail = await this.followChain(startPost, byId, mode);
577 const seen = {};
578 members.forEach((p) => {
579 seen[postId(p)] = true;
580 });
581 tail.forEach((p) => {
582 const id = postId(p);
583 if (id && !seen[id]) {
584 seen[id] = true;
585 members.push(p);
586 }
587 });
588 }
589 if (!members.length) {
590 return { ok: false, reason: reason || fetched.reason || "geen hoofdstukken" };
591 }
592 members = members.slice().sort(comparePosts);
593 const first = members[0];
594 const name = (entry && entry.title) || guessTitle(members.map((p) => p.title)) || first.title || "Untitled";
595 const author = (entry && entry.author) || first.author || "Anonymous";
596 const path = startId ? "series/" + postId(first) : wikiSlug ? "wiki/" + wikiSlug : "series/" + postId(first);
597 const nsfw = members.some((p) => p.over_18 || p.over18);
598 const oneshot = members.length <= 1;
599 return {
600 ok: true,
601 novel: {
602 path: path,
603 name: name,
604 author: author,
605 artist: undefined,
606 cover: this.coverFor({ name: name, cover: null }),
607 genres: nsfw ? "HFY, NSFW" : "HFY",
608 status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,
609 summary: author ? "HFY-serie van u/" + author + "." : "",
610 chapters: members.map((p, i) => ({
611 name: p.title || "Chapter " + (i + 1),
612 path: "chapter/" + postId(p),
613 releaseTime: releaseTimeOf(p),
614 chapterNumber: i + 1,
615 })),
616 },
617 };
618 }
619
620 async loadWikiIndex(mode) {
621 const cached = readWikiCache();
622 if (cached && cached.entries && cached.entries.length) {
623 return { ok: true, entries: cached.entries, source: "cache" };
624 }
625 if (mode !== "arctic") {
626 const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);
627 if (reddit.ok) {
628 const entries = parseSeriesIndex(reddit.markdown);
629 if (entries.length) {
630 writeWikiCache(entries);
631 return { ok: true, entries: entries, source: "reddit" };
632 }
633 }
634 if (mode === "reddit") {
635 return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };
636 }
637 }
638 const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);
639 if (arctic.ok) {
640 const entries = parseSeriesIndex(arctic.markdown);
641 if (entries.length) {
642 writeWikiCache(entries);
643 return { ok: true, entries: entries, source: "arctic" };
644 }
645 }
646 return { ok: false, reason: (arctic && arctic.reason) || "wiki-index niet beschikbaar" };
647 }
648
649 async loadWikiPage(slug, mode) {
650 const path = WIKI_INDEX_PATH + "/" + slug;
651 if (mode !== "arctic") {
652 const reddit = await fetchRedditWikiMarkdown(path);
653 if (reddit.ok) {
654 return { ok: true, entry: parseSeriesPage(reddit.markdown, path), source: "reddit" };
655 }
656 if (mode === "reddit") {
657 return reddit;
658 }
659 }
660 const arctic = await fetchArcticWikiPage(this.chapterSource(), path);
661 if (arctic.ok) {
662 return { ok: true, entry: parseSeriesPage(arctic.markdown, path), source: "arctic" };
663 }
664 return { ok: false, reason: (arctic && arctic.reason) || "wiki-subpagina niet beschikbaar" };
665 }
666
667 async loadSearchPosts(term, page, mode) {
668 if (mode !== "arctic") {
669 const reddit = await fetchRedditSearch(term, page);
670 if (reddit.ok) {
671 return reddit;
672 }
673 if (mode === "reddit") {
674 return reddit;
675 }
676 }
677 return await fetchArcticSearch(this.chapterSource(), term);
678 }
679
680 async loadRecentOcPosts(page, mode) {
681 const wiki = await this.loadWikiIndex(mode === "reddit" ? "reddit" : "auto");
682 if (mode !== "arctic") {
683 const reddit = await fetchRedditListing("/r/HFY/new.json", page);
684 if (reddit.ok) {
685 return {
686 ok: true,
687 posts: reddit.posts.filter(isStoryPost),
688 wikiEntries: wiki.ok ? wiki.entries : [],
689 source: "reddit",
690 };
691 }
692 if (mode === "reddit") {
693 return reddit;
694 }
695 }
696 const arctic = await fetchArcticRecent(this.chapterSource());
697 if (arctic.ok) {
698 return {
699 ok: true,
700 posts: (arctic.posts || []).filter(isStoryPost),
701 wikiEntries: wiki.ok ? wiki.entries : [],
702 source: "arctic",
703 };
704 }
705 return arctic;
706 }
707
708 async loadPostsByIds(ids, mode) {
709 const wanted = uniqueIds(ids);
710 if (!wanted.length) {
711 return { ok: true, posts: [], source: "none" };
712 }
713 if (mode !== "arctic") {
714 const reddit = await fetchRedditPostsByIds(wanted);
715 if (reddit.ok) {
716 return reddit;
717 }
718 if (mode === "reddit") {
719 return reddit;
720 }
721 }
722 return await fetchArcticPostsByIds(this.chapterSource(), wanted);
723 }
724
725 async followChain(seed, byId, mode) {
726 const chain = [];
727 const visited = {};
728 let current = seed;
729 let guard = 0;
730 while (current && guard < 400) {
731 const id = postId(current);
732 if (!id || visited[id]) {
733 break;
734 }
735 visited[id] = true;
736 chain.push(current);
737 const nxt = pickNextLink(current);
738 if (!nxt || visited[nxt]) {
739 break;
740 }
741 if (!byId[nxt]) {
742 const fetched = await this.loadPostsByIds([nxt], mode);
743 (fetched.posts || []).forEach((p) => {
744 const pid = postId(p);
745 if (pid) {
746 byId[pid] = p;
747 }
748 });
749 }
750 const candidate = byId[nxt];
751 if (!candidate) {
752 break;
753 }
754 if (!titlesBelongTogether(current.title, candidate.title, current.author, candidate.author, nxt === pickNextLink(current))) {
755 // Expliciete next van dezelfde auteur mag iets lager scoren; anders stoppen.
756 if (!sameAuthor(current, candidate) || titleSimilarity(current.title, candidate.title) < 0.4) {
757 break;
758 }
759 }
760 current = candidate;
761 guard += 1;
762 }
763 return chain;
764 }
765}
766
767function wikiSlugFromPath(novelPath) {
768 const raw = String(novelPath || "").trim();
769 const m = raw.match(/^(?:wiki\/|series\/wiki\/)?(?:r\/hfy\/wiki\/series\/)?([a-z0-9][a-z0-9_-]{1,80})$/i);
770 if (!m) {
771 return "";
772 }
773 const slug = m[1];
774 if (/^[0-9a-z]{4,10}$/i.test(slug) && raw.indexOf("wiki/") === -1) {
775 return "";
776 }
777 if (raw.indexOf("wiki/") === 0 || raw.indexOf("/wiki/series/") !== -1) {
778 return slug;
779 }
780 return "";
781}
782
783function wikiEntryToItem(entry, plugin) {
784 const first = entry.firstId || (entry.chapterIds && entry.chapterIds[0]) || "";
785 const path = first ? "series/" + first : "wiki/" + entry.slug;
786 return {
787 name: entry.title,
788 path: path,
789 cover: plugin.coverFor({ name: entry.title, cover: null }),
790 author: entry.author || "",
791 oneshot: false,
792 nsfw: false,
793 };
794}
795
796function wikiEntryMatches(entry, term) {
797 const q = String(term || "").trim().toLowerCase();
798 if (!q) {
799 return false;
800 }
801 const title = String(entry.title || "").toLowerCase();
802 const author = String(entry.author || "").toLowerCase();
803 const slug = String(entry.slug || "").toLowerCase().replace(/_/g, " ");
804 return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
805}
806
807function readWikiCache() {
808 try {
809 const value = storage.get(WIKI_CACHE_KEY);
810 if (!value) {
811 return null;
812 }
813 if (Array.isArray(value)) {
814 return { entries: value };
815 }
816 if (value.entries && Array.isArray(value.entries)) {
817 return value;
818 }
819 } catch (err) {
820 return null;
821 }
822 return null;
823}
824
825function writeWikiCache(entries) {
826 try {
827 const expires = Date.now() + WIKI_CACHE_MS;
828 storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries }, expires);
829 } catch (err) {
830 // cache is optioneel
831 }
832}
833
834function parseSeriesIndex(markdown) {
835 const text = String(markdown || "");
836 const out = [];
837 const seen = {};
838 const re = /^\s*[\*\-]\s*\[([^\]]+)\]\(([^)]+)\)(.*)$/gm;
839 let m;
840 while ((m = re.exec(text))) {
841 const title = cleanHeading(m[1]);
842 const path = normalizeWikiPath(m[2]);
843 if (!path || path.toLowerCase().indexOf("/wiki/series/") === -1) {
844 continue;
845 }
846 const key = path.toLowerCase();
847 if (seen[key]) {
848 continue;
849 }
850 seen[key] = true;
851 const slug = path.split("/").filter(Boolean).pop();
852 out.push({
853 title: title || slug.replace(/_/g, " "),
854 wikiPath: path,
855 slug: slug,
856 author: authorFromRest(m[3] || ""),
857 chapterIds: [],
858 firstId: "",
859 });
860 }
861 return out;
862}
863
864function parseSeriesPage(markdown, wikiPath) {
865 const text = String(markdown || "");
866 const path = normalizeWikiPath(wikiPath) || String(wikiPath || "");
867 const slug = path.split("/").filter(Boolean).pop() || "";
868 const heading = text.match(/^#{1,4}\s*(.+)$/m);
869 let title = heading ? cleanHeading(heading[1]) : slug.replace(/_/g, " ");
870 if (title && /^(all series|series|one shots|oneshots)$/i.test(title)) {
871 title = slug.replace(/_/g, " ");
872 }
873 const ids = [];
874 const seen = {};
875 extractLabeledLinks(text).forEach((link) => {
876 if (!seen[link.id]) {
877 seen[link.id] = true;
878 ids.push(link.id);
879 }
880 });
881 extractIds(text).forEach((id) => {
882 if (!seen[id]) {
883 seen[id] = true;
884 ids.push(id);
885 }
886 });
887 return {
888 title: title,
889 wikiPath: path,
890 slug: slug,
891 author: authorFromPage(text),
892 chapterIds: ids,
893 firstId: ids[0] || "",
894 };
895}
896
897function normalizeWikiPath(href) {
898 if (!href) {
899 return "";
900 }
901 let raw = String(href).trim().split(")")[0].split(/\s+/)[0];
902 raw = raw.replace(/\/wiki\/settings\/series\//i, "/wiki/series/");
903 const m = raw.match(/(?:https?:\/\/(?:www\.)?reddit\.com)?(\/r\/[^/]+\/wiki\/(?:series)\/[^)#\s]+)/i);
904 if (!m) {
905 return "";
906 }
907 const parts = m[1].split("/");
908 if (parts.length >= 3 && parts[1].toLowerCase() === "r") {
909 parts[2] = "hfy";
910 }
911 return parts.join("/").replace(/\/+$/, "").replace(/\/r\/HFY\//i, "/r/hfy/");
912}
913
914function cleanHeading(raw) {
915 let text = String(raw || "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1");
916 text = text.replace(/[*_`]+/g, "");
917 return text.replace(/\s+/g, " ").trim();
918}
919
920function authorFromRest(rest) {
921 const m = String(rest || "").match(/\[\s*\*([^*]+)\*\s*\]/);
922 if (!m) {
923 return "";
924 }
925 return m[1].replace(/^u\//, "").trim();
926}
927
928function authorFromPage(markdown) {
929 const wiki = String(markdown || "").match(
930 /\[(?:\*\*)?([^\]*]+)(?:\*\*)?\]\((?:https?:\/\/(?:www\.)?reddit\.com)?\/r\/[^/]+\/wiki\/authors\/([^)\s/]+)/i,
931 );
932 if (wiki) {
933 return (wiki[1] || wiki[2] || "").trim();
934 }
935 const by = String(markdown || "").match(/(?:a\s+story\s+by|author)\s*[:.\-–—]?\s*\[(?:\*\*)?([^\]*]+)(?:\*\*)?\]/i);
936 if (by) {
937 return by[1].trim();
938 }
939 const user = String(markdown || "").slice(0, 2000).match(/(?:https?:\/\/(?:www\.)?reddit\.com)?\/u(?:ser)?\/([A-Za-z0-9_-]+)|(?<![/\w])u\/([A-Za-z0-9_-]+)/i);
940 if (user) {
941 return (user[1] || user[2] || "").trim();
942 }
943 return "";
944}
945
946function extractIds(text) {
947 const ids = [];
948 const re = /(?:redd\.it\/|\/(?:r\/[^/]+\/)?comments\/)([0-9a-z]{4,10})\b/gi;
949 let m;
950 while ((m = re.exec(String(text || "")))) {
951 ids.push(m[1].toLowerCase());
952 }
953 return ids;
954}
955
956function extractLabeledLinks(text) {
957 const links = [];
958 const re = /\[([^\]]+)\]\(([^)]+)\)/g;
959 let m;
960 while ((m = re.exec(String(text || "")))) {
961 const id = extractIds(m[2])[0];
962 if (!id) {
963 continue;
964 }
965 const label = String(m[1] || "").toLowerCase();
966 let kind = "other";
967 if (/\b(next|nxt|continue|volgende)\b/.test(label)) {
968 kind = "next";
969 } else if (/\b(prev|previous|vorige)\b/.test(label)) {
970 kind = "prev";
971 } else if (/\b(first|index|eerste)\b/.test(label)) {
972 kind = "first";
973 }
974 links.push({ id: id, kind: kind, label: m[1] });
975 }
976 return links;
977}
978
979function postId(post) {
980 if (!post) {
981 return "";
982 }
983 let id = String(post.id || "").replace(/^t3_/, "").toLowerCase();
984 if (/^[0-9a-z]{4,10}$/.test(id)) {
985 return id;
986 }
987 const fromUrl = extractIds(post.permalink || post.url || "")[0];
988 return fromUrl || "";
989}
990
991function comparePosts(a, b) {
992 const ua = Number(a.created_utc || a.createdUtc || 0);
993 const ub = Number(b.created_utc || b.createdUtc || 0);
994 if (ua !== ub) {
995 return ua - ub;
996 }
997 return postId(a) < postId(b) ? -1 : 1;
998}
999
1000function releaseTimeOf(post) {
1001 const utc = Number(post && (post.created_utc || post.createdUtc) || 0);
1002 if (!utc) {
1003 return null;
1004 }
1005 return new Date(utc * 1000).toISOString();
1006}
1007
1008function sameAuthor(a, b) {
1009 return String((a && a.author) || "").toLowerCase() === String((b && b.author) || "").toLowerCase();
1010}
1011
1012function pickNextLink(post) {
1013 const text = String((post && (post.selftext || post.selftext_html || post.body)) || "");
1014 const links = extractLabeledLinks(text);
1015 const next = links.find((l) => l.kind === "next");
1016 if (next) {
1017 return next.id;
1018 }
1019 const other = links.find((l) => l.kind === "other");
1020 return other ? other.id : "";
1021}
1022
1023function isStoryPost(post) {
1024 if (!post) {
1025 return false;
1026 }
1027 const isSelf = post.is_self !== false && post.isSelf !== false;
1028 if (!isSelf && !(post.selftext || post.selftext_html)) {
1029 return false;
1030 }
1031 const flair = String(post.link_flair_text || post.flair || "")
1032 .trim()
1033 .toLowerCase()
1034 .replace(/\s+/g, "");
1035 if (["meta", "mod", "media", "art", "video", "misc"].indexOf(flair) !== -1) {
1036 return false;
1037 }
1038 const title = String(post.title || "").toLowerCase();
1039 if (title.indexOf("[meta]") === 0 || title.indexOf("[mod]") === 0) {
1040 return false;
1041 }
1042 return true;
1043}
1044
1045function isSeedPost(post) {
1046 const flair = String(post.link_flair_text || post.flair || "")
1047 .trim()
1048 .toLowerCase()
1049 .replace(/\s+/g, "");
1050 if (flair.indexOf("firstofseries") !== -1) {
1051 return true;
1052 }
1053 if (flair.indexOf("oneshot") !== -1) {
1054 return true;
1055 }
1056 return isStartTitle(post.title);
1057}
1058
1059function isStartTitle(title) {
1060 return /(?:^|[\s:\-–—|\[\(])(?:(?:part|chapter|ch|pt|episode|ep)\.?\s*(?:1|i|one|first)\b|#\s*1\b|\(\s*1\s*(?:\/\s*(?:\d+|\?))?\s*\)|prologue)\b/i.test(
1061 String(title || ""),
1062 );
1063}
1064
1065function normalizeTitle(title) {
1066 let text = String(title || "");
1067 try {
1068 text = text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
1069 } catch (err) {
1070 // oudere JS zonder normalize
1071 }
1072 text = text.replace(
1073 /\[\s*(?:oc|pi|hfy|ff|fic|meta|chapter|ch|part|pt|oneshot|one[-\s]?shot)(?:[^\]]*)\]/gi,
1074 " ",
1075 );
1076 text = text.replace(/^\s*(?:oc|pi|hfy|ff)\s*[:|\-–—]\s*/i, " ");
1077 text = text.replace(
1078 /(?:^|[\s,;:\-–—|\[\(])(?:part|chapter|chapters|ch|pt|episode|ep|update|book|vol|volume)\.?\s*(?:[0-9]+(?:\s*[./]\s*[0-9]+)?)|#\s*[0-9]+[\]\)]?/gi,
1079 " ",
1080 );
1081 text = text.replace(/[\s:\-–—|]*\(\s*[0-9]{1,4}\s*(?:\/\s*(?:[0-9]{1,4}|\?)\s*)?\)/g, " ");
1082 text = text.replace(/[\s:\-–—|]+(?:[0-9]{1,4})(?:\s*[./]\s*[0-9]{1,4})?\s*$/g, " ");
1083 return text.toLowerCase().replace(/["“”‘’`]+/g, "").replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim();
1084}
1085
1086function titleSimilarity(a, b) {
1087 const ta = normalizeTitle(a).split(" ").filter(Boolean);
1088 const tb = normalizeTitle(b).split(" ").filter(Boolean);
1089 if (!ta.length || !tb.length) {
1090 return 0;
1091 }
1092 const setB = {};
1093 tb.forEach((w) => {
1094 setB[w] = true;
1095 });
1096 let inter = 0;
1097 ta.forEach((w) => {
1098 if (setB[w]) {
1099 inter += 1;
1100 }
1101 });
1102 return inter / Math.sqrt(ta.length * tb.length);
1103}
1104
1105function titlesBelongTogether(aTitle, bTitle, aAuthor, bAuthor, explicitNext) {
1106 if (aAuthor && bAuthor && String(aAuthor).toLowerCase() !== String(bAuthor).toLowerCase()) {
1107 return explicitNext && titleSimilarity(aTitle, bTitle) >= 0.4;
1108 }
1109 const score = titleSimilarity(aTitle, bTitle);
1110 return explicitNext ? score >= 0.3 : score >= 0.5;
1111}
1112
1113function guessTitle(titles) {
1114 if (!titles || !titles.length) {
1115 return "";
1116 }
1117 const norms = titles.map(normalizeTitle).filter(Boolean);
1118 if (!norms.length) {
1119 return String(titles[0] || "").replace(/\s+/g, " ").trim();
1120 }
1121 const first = norms[0].split(" ");
1122 let end = first.length;
1123 for (let i = 1; i < norms.length; i++) {
1124 const parts = norms[i].split(" ");
1125 let j = 0;
1126 while (j < end && j < parts.length && parts[j] === first[j]) {
1127 j += 1;
1128 }
1129 end = j;
1130 }
1131 const shared = first.slice(0, end).join(" ");
1132 if (shared.length >= 4) {
1133 return shared.replace(/\b\w/g, (c) => c.toUpperCase());
1134 }
1135 return String(titles[0] || "").replace(/\s+/g, " ").trim();
1136}
1137
1138function groupPostsIntoNovels(posts, wikiEntries) {
1139 const stories = (posts || []).filter(isStoryPost);
1140 const groups = [];
1141 const claimed = {};
1142 const wiki = wikiEntries || [];
1143
1144 function matchWiki(post) {
1145 const key = normalizeTitle(post.title);
1146 const author = String(post.author || "").toLowerCase();
1147 let best = null;
1148 let bestScore = 0;
1149 wiki.forEach((entry) => {
1150 if (entry.author && author && entry.author.toLowerCase() !== author) {
1151 return;
1152 }
1153 const score = titleSimilarity(entry.title, post.title);
1154 if (score > bestScore) {
1155 bestScore = score;
1156 best = entry;
1157 }
1158 });
1159 if (best && bestScore >= 0.55) {
1160 return best;
1161 }
1162 if (best && key && normalizeTitle(best.title) === key) {
1163 return best;
1164 }
1165 return null;
1166 }
1167
1168 const byWiki = {};
1169 const byKey = {};
1170 stories.forEach((post) => {
1171 const wikiHit = matchWiki(post);
1172 if (wikiHit) {
1173 const k = "wiki:" + (wikiHit.slug || wikiHit.wikiPath);
1174 if (!byWiki[k]) {
1175 byWiki[k] = { entry: wikiHit, posts: [] };
1176 }
1177 byWiki[k].posts.push(post);
1178 claimed[postId(post)] = true;
1179 return;
1180 }
1181 const key = String(post.author || "").toLowerCase() + "|" + normalizeTitle(post.title);
1182 if (!byKey[key]) {
1183 byKey[key] = [];
1184 }
1185 byKey[key].push(post);
1186 });
1187
1188 Object.keys(byWiki).forEach((k) => {
1189 const g = byWiki[k];
1190 const members = g.posts.slice().sort(comparePosts);
1191 const first = members[0];
1192 groups.push({
1193 name: g.entry.title,
1194 path: postId(first) ? "series/" + postId(first) : "wiki/" + g.entry.slug,
1195 author: g.entry.author || first.author || "",
1196 oneshot: members.length <= 1,
1197 nsfw: members.some((p) => p.over_18 || p.over18),
1198 cover: null,
1199 });
1200 });
1201
1202 Object.keys(byKey).forEach((k) => {
1203 const members = byKey[k].filter((p) => !claimed[postId(p)]).sort(comparePosts);
1204 if (!members.length) {
1205 return;
1206 }
1207 // Alleen een nieuwe reeks starten als er een zaad is, of precies één post.
1208 const seeds = members.filter(isSeedPost);
1209 const use = seeds.length ? [seeds[0]].concat(members.filter((p) => p !== seeds[0])) : members;
1210 const ordered = use.slice().sort(comparePosts);
1211 const first = ordered[0];
1212 groups.push({
1213 name: guessTitle(ordered.map((p) => p.title)) || first.title,
1214 path: "series/" + postId(first),
1215 author: first.author || "",
1216 oneshot: ordered.length <= 1,
1217 nsfw: ordered.some((p) => p.over_18 || p.over18),
1218 cover: null,
1219 });
1220 });
1221
1222 return groups;
1223}
1224
1225function uniqueIds(ids) {
1226 const seen = {};
1227 const out = [];
1228 (ids || []).forEach((id) => {
1229 const key = String(id || "")
1230 .replace(/^t3_/, "")
1231 .toLowerCase();
1232 if (!/^[0-9a-z]{4,10}$/.test(key) || seen[key]) {
1233 return;
1234 }
1235 seen[key] = true;
1236 out.push(key);
1237 });
1238 return out;
1239}
1240
1241async function fetchRedditBody(url) {
1242 const res = await fetchApi(url, { headers: { Accept: "application/json" } });
1243 const body = res && typeof res.text === "function" ? await res.text() : "";
1244 const status = res && res.status != null ? res.status : "?";
1245 if (!res || res.ok === false || isLoginOrBlockPage(res, body)) {
1246 return {
1247 ok: false,
1248 blocked: !res || res.ok === false || isLoginOrBlockPage(res, body),
1249 reason: "HTTP " + status + (isLoginOrBlockPage(res, body) ? " (login of blokkade)" : ""),
1250 body: body,
1251 res: res,
1252 };
1253 }
1254 if (!body || looksLikeHtml(body)) {
1255 return { ok: false, reason: "geen JSON", body: body, res: res };
1256 }
1257 return { ok: true, body: body, res: res };
1258}
1259
1260async function fetchRedditJson(pathAndQuery) {
1261 const path = pathAndQuery.indexOf("/") === 0 ? pathAndQuery : "/" + pathAndQuery;
1262 const urls = [REDDIT_WWW + path, REDDIT_OLD + path];
1263 let last = { ok: false, reason: "geen antwoord" };
1264 for (let i = 0; i < urls.length; i++) {
1265 try {
1266 const got = await fetchRedditBody(urls[i]);
1267 if (!got.ok) {
1268 last = got;
1269 continue;
1270 }
1271 try {
1272 return { ok: true, data: JSON.parse(got.body), source: "reddit" };
1273 } catch (err) {
1274 last = { ok: false, reason: "ongeldige JSON" };
1275 }
1276 } catch (err) {
1277 last = { ok: false, reason: err && err.message ? err.message : String(err) };
1278 }
1279 }
1280 return last;
1281}
1282
1283async function fetchRedditWikiMarkdown(wikiPath) {
1284 const path = String(wikiPath || "").replace(/\/+$/, "");
1285 const result = await fetchRedditJson(path + ".json?raw_json=1");
1286 if (!result.ok) {
1287 return result;
1288 }
1289 const data = result.data && result.data.data ? result.data.data : result.data;
1290 const markdown = data && (data.content_md || data.content_html || data.content);
1291 if (!markdown || !String(markdown).trim()) {
1292 return { ok: false, reason: "lege wikipagina" };
1293 }
1294 return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };
1295}
1296
1297async function fetchRedditSearch(term, page) {
1298 const params =
1299 "q=" +
1300 encodeURIComponent(term) +
1301 "&restrict_sr=1&sort=relevance&limit=25&raw_json=1&type=link&count=" +
1302 ((Math.max(1, page) - 1) * 25);
1303 const result = await fetchRedditJson("/r/HFY/search.json?" + params);
1304 if (!result.ok) {
1305 return result;
1306 }
1307 return { ok: true, posts: listingPosts(result.data), source: "reddit" };
1308}
1309
1310async function fetchRedditListing(path, page) {
1311 const count = (Math.max(1, page) - 1) * 25;
1312 const qs = "limit=25&raw_json=1" + (count ? "&count=" + count : "");
1313 const result = await fetchRedditJson(path + (path.indexOf("?") === -1 ? "?" : "&") + qs);
1314 if (!result.ok) {
1315 return result;
1316 }
1317 return { ok: true, posts: listingPosts(result.data), source: "reddit" };
1318}
1319
1320async function fetchRedditPostsByIds(ids) {
1321 const full = uniqueIds(ids).map((id) => "t3_" + id);
1322 const posts = [];
1323 for (let i = 0; i < full.length; i += 100) {
1324 const chunk = full.slice(i, i + 100);
1325 const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");
1326 if (!result.ok) {
1327 if (!posts.length) {
1328 return result;
1329 }
1330 break;
1331 }
1332 listingPosts(result.data).forEach((p) => posts.push(p));
1333 }
1334 return { ok: true, posts: posts, source: "reddit" };
1335}
1336
1337function listingPosts(payload) {
1338 const listing = Array.isArray(payload) ? payload[0] : payload;
1339 const children = listing && listing.data && Array.isArray(listing.data.children) ? listing.data.children : [];
1340 const out = [];
1341 children.forEach((child) => {
1342 if (child && child.data && (!child.kind || child.kind === "t3")) {
1343 out.push(child.data);
1344 }
1345 });
1346 return out;
1347}
1348
1349async function fetchArcticWikiPage(base, wikiPath) {
1350 const url =
1351 String(base || "").replace(/\/+$/, "") +
1352 "/api/subreddits/wikis?paths=" +
1353 encodeURIComponent(wikiPath);
1354 try {
1355 const payload = await readJson(url, "wiki " + wikiPath);
1356 const pages = payload.data || payload;
1357 const page = Array.isArray(pages) ? pages[0] : pages;
1358 const markdown = page && (page.content || page.content_md);
1359 if (!markdown || !String(markdown).trim()) {
1360 return { ok: false, reason: "lege Arctic Shift-wikipagina" };
1361 }
1362 return { ok: true, markdown: String(markdown), source: "arctic" };
1363 } catch (err) {
1364 return { ok: false, reason: err && err.message ? err.message : String(err) };
1365 }
1366}
1367
1368async function fetchArcticSearch(base, term) {
1369 const root = String(base || "").replace(/\/+$/, "");
1370 const tryUrls = [
1371 root + "/api/posts/search?subreddit=HFY&query=" + encodeURIComponent(term) + "&limit=25&sort=desc",
1372 root + "/api/posts/search?subreddit=HFY&title=" + encodeURIComponent(term) + "&limit=25&sort=desc",
1373 ];
1374 let last = { ok: false, reason: "Arctic Shift-zoeken mislukt" };
1375 for (let i = 0; i < tryUrls.length; i++) {
1376 try {
1377 const payload = await readJson(tryUrls[i], "zoeken");
1378 const posts = payload.data || payload;
1379 if (Array.isArray(posts)) {
1380 return { ok: true, posts: posts, source: "arctic" };
1381 }
1382 } catch (err) {
1383 last = { ok: false, reason: err && err.message ? err.message : String(err) };
1384 }
1385 }
1386 return last;
1387}
1388
1389async function fetchArcticRecent(base) {
1390 const url = String(base || "").replace(/\/+$/, "") + "/api/posts/search?subreddit=HFY&limit=50&sort=desc";
1391 try {
1392 const payload = await readJson(url, "recente posts");
1393 const posts = payload.data || payload;
1394 return { ok: true, posts: Array.isArray(posts) ? posts : [], source: "arctic" };
1395 } catch (err) {
1396 return { ok: false, reason: err && err.message ? err.message : String(err) };
1397 }
1398}
1399
1400async function fetchArcticPostsByIds(base, ids) {
1401 const url =
1402 String(base || "").replace(/\/+$/, "") +
1403 "/api/posts/ids?ids=" +
1404 encodeURIComponent(uniqueIds(ids).join(","));
1405 try {
1406 const payload = await readJson(url, "posts");
1407 const posts = payload.data || payload;
1408 return { ok: true, posts: Array.isArray(posts) ? posts : [], source: "arctic" };
1409 } catch (err) {
1410 return { ok: false, reason: err && err.message ? err.message : String(err) };
1411 }
1412}
1413
1414function chapterIdFromPath(chapterPath) {
1415 const id = String(chapterPath || "")
1416 .replace(/^chapter\//, "")
1417 .replace(/^series\//, "")
1418 .trim()
1419 .toLowerCase();
1420 return /^[0-9a-z]{4,10}$/.test(id) ? id : "";
1421}
1422
1423function redditJsonUrls(id) {
1424 const path = "/r/HFY/comments/" + id + "/.json?raw_json=1";
1425 return [REDDIT_WWW + path, REDDIT_OLD + path];
1426}
1427
1428function looksLikeHtml(text) {
1429 const body = String(text || "").trim();
1430 if (!body) {
1431 return false;
1432 }
1433 return /^\s*<(!DOCTYPE|html|body|head)\b/i.test(body);
1434}
1435
1436function isLoginOrBlockPage(res, body) {
1437 const status = res && res.status != null ? Number(res.status) : 0;
1438 if (status === 401 || status === 403 || status === 429) {
1439 return true;
1440 }
1441 const finalUrl = String((res && res.url) || "");
1442 if (/[?&]reason=lor2\b/i.test(finalUrl) || /\/login\b/i.test(finalUrl)) {
1443 return true;
1444 }
1445 const type = String(
1446 (res && res.headers && typeof res.headers.get === "function" && res.headers.get("content-type")) || "",
1447 ).toLowerCase();
1448 if (type.indexOf("text/html") !== -1 && !/json/i.test(type)) {
1449 return true;
1450 }
1451 const text = String(body || "");
1452 if (looksLikeHtml(text)) {
1453 return true;
1454 }
1455 const lower = text.toLowerCase();
1456 if (
1457 lower.indexOf("reason=lor2") !== -1 ||
1458 lower.indexOf("www.reddit.com/login") !== -1 ||
1459 lower.indexOf("old.reddit.com/login") !== -1 ||
1460 lower.indexOf("log in to reddit") !== -1 ||
1461 (lower.indexOf("shreddit") !== -1 && lower.indexOf("<!doctype html") !== -1)
1462 ) {
1463 return true;
1464 }
1465 return false;
1466}
1467
1468function postFromRedditPayload(payload) {
1469 if (!payload) {
1470 return null;
1471 }
1472 const listing = Array.isArray(payload) ? payload[0] : payload;
1473 const children =
1474 listing && listing.data && Array.isArray(listing.data.children) ? listing.data.children : [];
1475 const child = children.find((c) => !c.kind || c.kind === "t3") || children[0];
1476 if (!child || !child.data) {
1477 return null;
1478 }
1479 if (child.kind && child.kind !== "t3") {
1480 return null;
1481 }
1482 return child.data;
1483}
1484
1485function decodeRedditHtml(html) {
1486 let text = String(html || "");
1487 if (text.indexOf("&lt;") !== -1 || text.indexOf("&amp;") !== -1) {
1488 text = text
1489 .replace(/&lt;/g, "<")
1490 .replace(/&gt;/g, ">")
1491 .replace(/&quot;/g, '"')
1492 .replace(/&#39;/g, "'")
1493 .replace(/&amp;/g, "&");
1494 }
1495 return text;
1496}
1497
1498async function tryRedditChapter(id) {
1499 let lastReason = "geen antwoord";
1500 const urls = redditJsonUrls(id);
1501 for (let i = 0; i < urls.length; i++) {
1502 const url = urls[i];
1503 try {
1504 const res = await fetchApi(url, { headers: { Accept: "application/json" } });
1505 const body = typeof res.text === "function" ? await res.text() : "";
1506 if (!res || res.ok === false || isLoginOrBlockPage(res, body)) {
1507 const status = res && res.status != null ? res.status : "?";
1508 lastReason = "HTTP " + status + (isLoginOrBlockPage(res, body) ? " (login of blokkade)" : "");
1509 continue;
1510 }
1511 if (!body || looksLikeHtml(body)) {
1512 lastReason = "geen JSON";
1513 continue;
1514 }
1515 let payload;
1516 try {
1517 payload = JSON.parse(body);
1518 } catch (err) {
1519 lastReason = "ongeldige JSON";
1520 continue;
1521 }
1522 const post = postFromRedditPayload(payload);
1523 if (!post) {
1524 lastReason = "geen post in de listing";
1525 continue;
1526 }
1527 return { ok: true, post: post };
1528 } catch (err) {
1529 lastReason = err && err.message ? err.message : String(err);
1530 }
1531 }
1532 return { ok: false, reason: lastReason };
1533}
1534
1535async function tryArcticChapter(base, id) {
1536 const url = String(base || "").replace(/\/+$/, "") + "/api/posts/ids?ids=" + encodeURIComponent(id) + "&md2html=true";
1537 try {
1538 const payload = await readJson(url, "hoofdstuk " + id);
1539 const posts = payload.data || payload;
1540 const post = Array.isArray(posts) ? posts[0] : posts;
1541 if (!post) {
1542 return { ok: false, reason: "leeg antwoord" };
1543 }
1544 return { ok: true, post: post };
1545 } catch (err) {
1546 return { ok: false, reason: err && err.message ? err.message : String(err) };
1547 }
1548}
1549
1550function sourceFooter(label) {
1551 return '<p class="hfy-source"><em>Bron: ' + escapeHtml(label) + "</em></p>";
1552}
1553
1554function renderChapter(post, sourceLabel) {
1555 if (!post) {
1556 return "<p><em>Dit hoofdstuk is niet (meer) beschikbaar.</em></p>" + sourceFooter(sourceLabel);
1557 }
1558 const title = post.title ? "<h1>" + escapeHtml(post.title) + "</h1>" : "";
1559 const by = post.author ? "<p><em>by u/" + escapeHtml(post.author) + "</em></p>" : "";
1560 const rawHtml = post.selftext_html ? decodeRedditHtml(post.selftext_html) : "";
1561 const html = rawHtml ? sanitizeHtml(rawHtml) : markdownToHtml(post.selftext || "");
1562 if (!html) {
1563 return (
1564 title +
1565 by +
1566 "<p><em>Deze post heeft geen tekst (verwijderd of een link-post).</em></p>" +
1567 sourceFooter(sourceLabel)
1568 );
1569 }
1570 return title + by + html + sourceFooter(sourceLabel);
1571}
1572
1573function escapeHtml(text) {
1574 return String(text)
1575 .replace(/&/g, "&amp;")
1576 .replace(/</g, "&lt;")
1577 .replace(/>/g, "&gt;")
1578 .replace(/"/g, "&quot;");
1579}
1580
1581function sanitizeHtml(html) {
1582 // Reddit en Arctic Shift leveren HTML; we strippen scripts en on-event-attributen.
1583 return String(html)
1584 .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "")
1585 .replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "");
1586}
1587
1588function markdownToHtml(md) {
1589 if (!md) {
1590 return "";
1591 }
1592 const escaped = escapeHtml(md);
1593 const withLinks = escaped.replace(
1594 /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,
1595 '<a href="$2">$1</a>',
1596 );
1597 const paragraphs = withLinks
1598 .split(/\n{2,}/)
1599 .map((block) => "<p>" + block.replace(/\n/g, "<br>") + "</p>");
1600 return paragraphs.join("");
1601}
1602
1603const instance = new HFYNovelsPlugin();
1604exports.default = instance;