Laat de cover de echte bron volgen en gebruik drie vaste PNG's
Catalogus en parseNovel gebruiken andere Reddit-endpoints dan
hoofdstukken (/wiki/series.json, /api/info.json versus
/comments/{id}/.json). Een Arctic-wiki werd zes uur gecachet, waardoor
lijst-covers Arctic bleven terwijl parseChapter "Bron: Reddit" toonde.
De wiki-cache is nu v2: Reddit zes uur, Arctic vijf minuten, en Reddit
wordt altijd opnieuw geprobeerd. parseNovel valt bij een falend
api/info.json terug op dezelfde comments-JSON als de hoofdstukken.
Alle covers zijn drie vaste 240×360-PNG's (r/HFY-logo + bronbadge):
reddit, arctic-shift of index (projects.timfalken.com). Bij twijfel
Reddit. Versie 0.3.4.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -10,10 +10,11 @@
10
10
* waarbij series en losse Part-1-posts tot één novel worden gegroepeerd
11
11
* - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis
12
12
*
13
* Verhalen in de statische index houden hun vooraf gemaakte cover-URL.
14
* Live gevonden verhalen zonder die PNG krijgen één vaste cover per bron:
15
* Reddit (r/HFY-logo) of Arctic Shift (site-logo), als gewone https-URL
16
* in .dist/covers/. Geen data-URI's en geen generatie op het toestel.
13
* Covers zijn drie vaste PNGs in .dist/covers/ (gewone https-URL, geen
14
* data-URI, geen titelgeneratie op het toestel): r/HFY-logo in het midden
15
* en rechtsonder een bronbadge. De badge volgt de bron die de data
16
* leverde: reddit.png, arctic-shift.png, of index.png (statische index).
17
* Bij twijfel gebruiken we de Reddit-cover.
17
18
*
18
19
* Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,
19
20
* en daarna op de statische metadata-index (ook bruikbaar zonder login).
@@ -36,11 +37,15 @@ const DEFAULT_INDEX_BASE =
36
37
const RAW_PLUGIN_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw";
37
38
const LIVE_COVER_REDDIT = RAW_PLUGIN_BASE + "/.dist/covers/reddit.png?rev=master";
38
39
const LIVE_COVER_ARCTIC = RAW_PLUGIN_BASE + "/.dist/covers/arctic-shift.png?rev=master";
40
const LIVE_COVER_INDEX = RAW_PLUGIN_BASE + "/.dist/covers/index.png?rev=master";
39
41
const DEFAULT_INDEX_REV = "master";
40
42
const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";
41
43
const PAGE_FALLBACK_SIZE = 50;
42
const WIKI_CACHE_KEY = "wikiSeriesIndex";
43
const WIKI_CACHE_MS = 6 * 60 * 60 * 1000;
44
// v2: ongeldig verklaart caches uit 0.3.2/0.3.3 die een Arctic-fallback
45
// zes uur vasthielden terwijl hoofdstukken intussen via Reddit werkten.
46
const WIKI_CACHE_KEY = "wikiSeriesIndex.v2";
47
const WIKI_CACHE_MS_REDDIT = 6 * 60 * 60 * 1000;
48
const WIKI_CACHE_MS_ARCTIC = 5 * 60 * 1000;
44
49
const REDDIT_WWW = "https://www.reddit.com";
45
50
const REDDIT_OLD = "https://old.reddit.com";
46
51
const WIKI_INDEX_PATH = "/r/HFY/wiki/series";
@@ -109,11 +114,21 @@ function toNovelItem(entry, plugin) {
109
114
};
110
115
}
111
116
117
function coverSourceOf(postSource, wikiSource) {
118
if (postSource === "reddit" || wikiSource === "reddit") {
119
return "reddit";
120
}
121
if (postSource === "arctic" || wikiSource === "arctic") {
122
return "arctic";
123
}
124
return "reddit";
125
}
126
112
127
class HFYNovelsPlugin {
113
128
constructor() {
114
129
this.id = "hfyNovels";
115
130
this.name = "HFY Novels";
116
this.version = "0.3.3";
131
this.version = "0.3.4";
117
132
this.site = "https://www.reddit.com/r/HFY/";
118
133
this.icon = "icon.png";
119
134
// Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's
@@ -189,17 +204,16 @@ class HFYNovelsPlugin {
189
204
}
190
205
191
206
coverFor(entry) {
192
if (entry && entry.cover) {
193
return this.coverUrl(entry.cover);
194
}
207
// Per-titelcovers uit de statische index worden niet meer gebruikt.
195
208
const source = entry && entry.source;
196
209
if (source === "arctic") {
197
210
return LIVE_COVER_ARCTIC;
198
211
}
199
if (source === "reddit") {
200
return LIVE_COVER_REDDIT;
212
if (source === "index") {
213
return LIVE_COVER_INDEX;
201
214
}
202
return defaultCover;
215
// reddit, of bij twijfel (ontbrekende/onbekende bron).
216
return LIVE_COVER_REDDIT;
203
217
}
204
218
205
219
coverUrl(cover) {
@@ -381,9 +395,8 @@ class HFYNovelsPlugin {
381
395
}
382
396
// Statische indexcovers overschrijven een live broncover, zodat een
383
397
// bibliotheek-refresh een eerdere data-URI of logo kan vervangen.
384
if (fallback.cover) {
385
novel.cover = fallback.cover;
386
}
398
// Live data houdt de live-broncover (reddit/arctic). De indexcover
399
// geldt alleen als de reeks uitsluitend uit de statische index komt.
387
400
return finish(novel);
388
401
} catch (err) {
389
402
if (novel) {
@@ -461,14 +474,14 @@ class HFYNovelsPlugin {
461
474
}
462
475
const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);
463
476
const novels = (payload.novels || []).filter((n) => !n.nsfw);
464
return novels.map((n) => toNovelItem(n, this));
477
return novels.map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));
465
478
}
466
479
467
480
const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
468
481
const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));
469
482
const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;
470
483
const start = (page - 1) * size;
471
return items.slice(start, start + size).map((n) => toNovelItem(n, this));
484
return items.slice(start, start + size).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));
472
485
}
473
486
474
487
async staticSearch(searchTerm, pageNo) {
@@ -484,7 +497,7 @@ class HFYNovelsPlugin {
484
497
return name.includes(term) || author.includes(term);
485
498
});
486
499
const start = (page - 1) * PAGE_FALLBACK_SIZE;
487
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(n, this));
500
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));
488
501
}
489
502
490
503
async staticParseNovel(novelPath) {
@@ -494,7 +507,7 @@ class HFYNovelsPlugin {
494
507
name: data.name || "Untitled",
495
508
author: data.author || "Anonymous",
496
509
artist: undefined,
497
cover: this.coverFor({ name: data.name, cover: data.cover }),
510
cover: this.coverFor({ name: data.name, source: "index" }),
498
511
genres: data.genres || "HFY",
499
512
status: statusFrom(data.status),
500
513
summary: data.summary || "",
@@ -626,7 +639,7 @@ class HFYNovelsPlugin {
626
639
name: name,
627
640
author: author,
628
641
artist: undefined,
629
cover: this.coverFor({ name: name, cover: null, source: (fetched && fetched.source) || source }),
642
cover: this.coverFor({ name: name, source: coverSourceOf(fetched && fetched.source, source) }),
630
643
genres: nsfw ? "HFY, NSFW" : "HFY",
631
644
status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,
632
645
summary: author ? "HFY-serie van u/" + author + "." : "",
@@ -642,8 +655,11 @@ class HFYNovelsPlugin {
642
655
643
656
async loadWikiIndex(mode) {
644
657
const cached = readWikiCache();
645
if (cached && cached.entries && cached.entries.length) {
646
return { ok: true, entries: cached.entries, source: cached.source || "reddit" };
658
const haveCached = cached && cached.entries && cached.entries.length;
659
// Alleen een Reddit-cache is lang geldig. Een Arctic-fallback cachen we
660
// kort, en we proberen Reddit altijd opnieuw (bijv. na WebView-login).
661
if (haveCached && cached.source === "reddit") {
662
return { ok: true, entries: cached.entries, source: "reddit" };
647
663
}
648
664
if (mode !== "arctic") {
649
665
const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);
@@ -658,6 +674,9 @@ class HFYNovelsPlugin {
658
674
return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };
659
675
}
660
676
}
677
if (haveCached) {
678
return { ok: true, entries: cached.entries, source: cached.source || "arctic" };
679
}
661
680
const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);
662
681
if (arctic.ok) {
663
682
const entries = parseSeriesIndex(arctic.markdown);
@@ -827,28 +846,39 @@ function wikiEntryMatches(entry, term) {
827
846
return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
828
847
}
829
848
849
function wikiCacheTtl(source) {
850
return source === "reddit" ? WIKI_CACHE_MS_REDDIT : WIKI_CACHE_MS_ARCTIC;
851
}
852
830
853
function readWikiCache() {
831
854
try {
832
855
const value = storage.get(WIKI_CACHE_KEY);
833
856
if (!value) {
834
857
return null;
835
858
}
859
let parsed = value;
836
860
if (Array.isArray(value)) {
837
return { entries: value };
861
parsed = { entries: value, source: "reddit" };
838
862
}
839
if (value.entries && Array.isArray(value.entries)) {
840
return value;
863
if (!parsed.entries || !Array.isArray(parsed.entries) || !parsed.entries.length) {
864
return null;
841
865
}
866
const source = parsed.source || "reddit";
867
const fetchedAt = Number(parsed.fetchedAt || 0);
868
if (fetchedAt && Date.now() - fetchedAt > wikiCacheTtl(source)) {
869
return null;
870
}
871
return parsed;
842
872
} catch (err) {
843
873
return null;
844
874
}
845
return null;
846
875
}
847
876
848
877
function writeWikiCache(entries, source) {
849
878
try {
850
const expires = Date.now() + WIKI_CACHE_MS;
851
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: source || "reddit" }, expires);
879
const src = source || "arctic";
880
const expires = Date.now() + wikiCacheTtl(src);
881
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: src }, expires);
852
882
} catch (err) {
853
883
// cache is optioneel
854
884
}
@@ -1305,16 +1335,24 @@ async function fetchRedditJson(pathAndQuery) {
1305
1335
1306
1336
async function fetchRedditWikiMarkdown(wikiPath) {
1307
1337
const path = String(wikiPath || "").replace(/\/+$/, "");
1308
const result = await fetchRedditJson(path + ".json?raw_json=1");
1309
if (!result.ok) {
1310
return result;
1311
}
1312
const data = result.data && result.data.data ? result.data.data : result.data;
1313
const markdown = data && (data.content_md || data.content_html || data.content);
1314
if (!markdown || !String(markdown).trim()) {
1315
return { ok: false, reason: "lege wikipagina" };
1338
// Sommige Reddit-clients willen /wiki/series.json, andere /wiki/series/.json.
1339
const variants = [path + ".json?raw_json=1", path + "/.json?raw_json=1"];
1340
let last = { ok: false, reason: "lege wikipagina" };
1341
for (let i = 0; i < variants.length; i++) {
1342
const result = await fetchRedditJson(variants[i]);
1343
if (!result.ok) {
1344
last = result;
1345
continue;
1346
}
1347
const data = result.data && result.data.data ? result.data.data : result.data;
1348
const markdown = data && (data.content_md || data.content_html || data.content);
1349
if (!markdown || !String(markdown).trim()) {
1350
last = { ok: false, reason: "lege wikipagina" };
1351
continue;
1352
}
1353
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };
1316
1354
}
1317
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };
1355
return last;
1318
1356
}
1319
1357
1320
1358
async function fetchRedditSearch(term, page) {
@@ -1341,20 +1379,38 @@ async function fetchRedditListing(path, page) {
1341
1379
}
1342
1380
1343
1381
async function fetchRedditPostsByIds(ids) {
1344
const full = uniqueIds(ids).map((id) => "t3_" + id);
1382
const wanted = uniqueIds(ids);
1383
const full = wanted.map((id) => "t3_" + id);
1345
1384
const posts = [];
1385
let infoFailed = null;
1346
1386
for (let i = 0; i < full.length; i += 100) {
1347
1387
const chunk = full.slice(i, i + 100);
1348
1388
const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");
1349
1389
if (!result.ok) {
1350
1390
if (!posts.length) {
1351
return result;
1391
infoFailed = result;
1392
break;
1352
1393
}
1353
1394
break;
1354
1395
}
1355
1396
listingPosts(result.data).forEach((p) => posts.push(p));
1356
1397
}
1357
return { ok: true, posts: posts, source: "reddit" };
1398
if (posts.length) {
1399
return { ok: true, posts: posts, source: "reddit" };
1400
}
1401
// /api/info.json is een ander endpoint dan de hoofdstukken
1402
// (/comments/{id}/.json) en kan 403 geven terwijl die wel werken.
1403
const fromComments = [];
1404
for (let i = 0; i < wanted.length; i++) {
1405
const chapter = await tryRedditChapter(wanted[i]);
1406
if (chapter && chapter.ok && chapter.post) {
1407
fromComments.push(chapter.post);
1408
}
1409
}
1410
if (fromComments.length) {
1411
return { ok: true, posts: fromComments, source: "reddit" };
1412
}
1413
return infoFailed || { ok: false, reason: "geen posts" };
1358
1414
}
1359
1415
1360
1416
function listingPosts(payload) {
@@ -10,10 +10,11 @@10
* waarbij series en losse Part-1-posts tot één novel worden gegroepeerd10
* waarbij series en losse Part-1-posts tot één novel worden gegroepeerd11
* - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis11
* - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis12
*12
*13
* Verhalen in de statische index houden hun vooraf gemaakte cover-URL.13
* Covers zijn drie vaste PNGs in .dist/covers/ (gewone https-URL, geen14
* Live gevonden verhalen zonder die PNG krijgen één vaste cover per bron:14
* data-URI, geen titelgeneratie op het toestel): r/HFY-logo in het midden15
* Reddit (r/HFY-logo) of Arctic Shift (site-logo), als gewone https-URL15
* en rechtsonder een bronbadge. De badge volgt de bron die de data16
* in .dist/covers/. Geen data-URI's en geen generatie op het toestel.16
* leverde: reddit.png, arctic-shift.png, of index.png (statische index).17
* Bij twijfel gebruiken we de Reddit-cover.17
*18
*18
* Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,19
* Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,19
* en daarna op de statische metadata-index (ook bruikbaar zonder login).20
* en daarna op de statische metadata-index (ook bruikbaar zonder login).@@ -36,11 +37,15 @@ const DEFAULT_INDEX_BASE =36
const RAW_PLUGIN_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw";37
const RAW_PLUGIN_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw";37
const LIVE_COVER_REDDIT = RAW_PLUGIN_BASE + "/.dist/covers/reddit.png?rev=master";38
const LIVE_COVER_REDDIT = RAW_PLUGIN_BASE + "/.dist/covers/reddit.png?rev=master";38
const LIVE_COVER_ARCTIC = RAW_PLUGIN_BASE + "/.dist/covers/arctic-shift.png?rev=master";39
const LIVE_COVER_ARCTIC = RAW_PLUGIN_BASE + "/.dist/covers/arctic-shift.png?rev=master";40
const LIVE_COVER_INDEX = RAW_PLUGIN_BASE + "/.dist/covers/index.png?rev=master";39
const DEFAULT_INDEX_REV = "master";41
const DEFAULT_INDEX_REV = "master";40
const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";42
const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";41
const PAGE_FALLBACK_SIZE = 50;43
const PAGE_FALLBACK_SIZE = 50;42
const WIKI_CACHE_KEY = "wikiSeriesIndex";44
// v2: ongeldig verklaart caches uit 0.3.2/0.3.3 die een Arctic-fallback43
const WIKI_CACHE_MS = 6 * 60 * 60 * 1000;45
// zes uur vasthielden terwijl hoofdstukken intussen via Reddit werkten.46
const WIKI_CACHE_KEY = "wikiSeriesIndex.v2";47
const WIKI_CACHE_MS_REDDIT = 6 * 60 * 60 * 1000;48
const WIKI_CACHE_MS_ARCTIC = 5 * 60 * 1000;44
const REDDIT_WWW = "https://www.reddit.com";49
const REDDIT_WWW = "https://www.reddit.com";45
const REDDIT_OLD = "https://old.reddit.com";50
const REDDIT_OLD = "https://old.reddit.com";46
const WIKI_INDEX_PATH = "/r/HFY/wiki/series";51
const WIKI_INDEX_PATH = "/r/HFY/wiki/series";@@ -109,11 +114,21 @@ function toNovelItem(entry, plugin) {109
};114
};110
}115
}111
116
117
function coverSourceOf(postSource, wikiSource) {118
if (postSource === "reddit" || wikiSource === "reddit") {119
return "reddit";120
}121
if (postSource === "arctic" || wikiSource === "arctic") {122
return "arctic";123
}124
return "reddit";125
}126
112
class HFYNovelsPlugin {127
class HFYNovelsPlugin {113
constructor() {128
constructor() {114
this.id = "hfyNovels";129
this.id = "hfyNovels";115
this.name = "HFY Novels";130
this.name = "HFY Novels";116
this.version = "0.3.3";131
this.version = "0.3.4";117
this.site = "https://www.reddit.com/r/HFY/";132
this.site = "https://www.reddit.com/r/HFY/";118
this.icon = "icon.png";133
this.icon = "icon.png";119
// Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's134
// Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's@@ -189,17 +204,16 @@ class HFYNovelsPlugin {189
}204
}190
205
191
coverFor(entry) {206
coverFor(entry) {192
if (entry && entry.cover) {207
// Per-titelcovers uit de statische index worden niet meer gebruikt.193
return this.coverUrl(entry.cover);194
}195
const source = entry && entry.source;208
const source = entry && entry.source;196
if (source === "arctic") {209
if (source === "arctic") {197
return LIVE_COVER_ARCTIC;210
return LIVE_COVER_ARCTIC;198
}211
}199
if (source === "reddit") {212
if (source === "index") {200
return LIVE_COVER_REDDIT;213
return LIVE_COVER_INDEX;201
}214
}202
return defaultCover;215
// reddit, of bij twijfel (ontbrekende/onbekende bron).216
return LIVE_COVER_REDDIT;203
}217
}204
218
205
coverUrl(cover) {219
coverUrl(cover) {@@ -381,9 +395,8 @@ class HFYNovelsPlugin {381
}395
}382
// Statische indexcovers overschrijven een live broncover, zodat een396
// Statische indexcovers overschrijven een live broncover, zodat een383
// bibliotheek-refresh een eerdere data-URI of logo kan vervangen.397
// bibliotheek-refresh een eerdere data-URI of logo kan vervangen.384
if (fallback.cover) {398
// Live data houdt de live-broncover (reddit/arctic). De indexcover385
novel.cover = fallback.cover;399
// geldt alleen als de reeks uitsluitend uit de statische index komt.386
}387
return finish(novel);400
return finish(novel);388
} catch (err) {401
} catch (err) {389
if (novel) {402
if (novel) {@@ -461,14 +474,14 @@ class HFYNovelsPlugin {461
}474
}462
const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);475
const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);463
const novels = (payload.novels || []).filter((n) => !n.nsfw);476
const novels = (payload.novels || []).filter((n) => !n.nsfw);464
return novels.map((n) => toNovelItem(n, this));477
return novels.map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));465
}478
}466
479
467
const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");480
const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");468
const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));481
const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));469
const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;482
const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;470
const start = (page - 1) * size;483
const start = (page - 1) * size;471
return items.slice(start, start + size).map((n) => toNovelItem(n, this));484
return items.slice(start, start + size).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));472
}485
}473
486
474
async staticSearch(searchTerm, pageNo) {487
async staticSearch(searchTerm, pageNo) {@@ -484,7 +497,7 @@ class HFYNovelsPlugin {484
return name.includes(term) || author.includes(term);497
return name.includes(term) || author.includes(term);485
});498
});486
const start = (page - 1) * PAGE_FALLBACK_SIZE;499
const start = (page - 1) * PAGE_FALLBACK_SIZE;487
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(n, this));500
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));488
}501
}489
502
490
async staticParseNovel(novelPath) {503
async staticParseNovel(novelPath) {@@ -494,7 +507,7 @@ class HFYNovelsPlugin {494
name: data.name || "Untitled",507
name: data.name || "Untitled",495
author: data.author || "Anonymous",508
author: data.author || "Anonymous",496
artist: undefined,509
artist: undefined,497
cover: this.coverFor({ name: data.name, cover: data.cover }),510
cover: this.coverFor({ name: data.name, source: "index" }),498
genres: data.genres || "HFY",511
genres: data.genres || "HFY",499
status: statusFrom(data.status),512
status: statusFrom(data.status),500
summary: data.summary || "",513
summary: data.summary || "",@@ -626,7 +639,7 @@ class HFYNovelsPlugin {626
name: name,639
name: name,627
author: author,640
author: author,628
artist: undefined,641
artist: undefined,629
cover: this.coverFor({ name: name, cover: null, source: (fetched && fetched.source) || source }),642
cover: this.coverFor({ name: name, source: coverSourceOf(fetched && fetched.source, source) }),630
genres: nsfw ? "HFY, NSFW" : "HFY",643
genres: nsfw ? "HFY, NSFW" : "HFY",631
status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,644
status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,632
summary: author ? "HFY-serie van u/" + author + "." : "",645
summary: author ? "HFY-serie van u/" + author + "." : "",@@ -642,8 +655,11 @@ class HFYNovelsPlugin {642
655
643
async loadWikiIndex(mode) {656
async loadWikiIndex(mode) {644
const cached = readWikiCache();657
const cached = readWikiCache();645
if (cached && cached.entries && cached.entries.length) {658
const haveCached = cached && cached.entries && cached.entries.length;646
return { ok: true, entries: cached.entries, source: cached.source || "reddit" };659
// Alleen een Reddit-cache is lang geldig. Een Arctic-fallback cachen we660
// kort, en we proberen Reddit altijd opnieuw (bijv. na WebView-login).661
if (haveCached && cached.source === "reddit") {662
return { ok: true, entries: cached.entries, source: "reddit" };647
}663
}648
if (mode !== "arctic") {664
if (mode !== "arctic") {649
const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);665
const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);@@ -658,6 +674,9 @@ class HFYNovelsPlugin {658
return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };674
return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };659
}675
}660
}676
}677
if (haveCached) {678
return { ok: true, entries: cached.entries, source: cached.source || "arctic" };679
}661
const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);680
const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);662
if (arctic.ok) {681
if (arctic.ok) {663
const entries = parseSeriesIndex(arctic.markdown);682
const entries = parseSeriesIndex(arctic.markdown);@@ -827,28 +846,39 @@ function wikiEntryMatches(entry, term) {827
return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;846
return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;828
}847
}829
848
849
function wikiCacheTtl(source) {850
return source === "reddit" ? WIKI_CACHE_MS_REDDIT : WIKI_CACHE_MS_ARCTIC;851
}852
830
function readWikiCache() {853
function readWikiCache() {831
try {854
try {832
const value = storage.get(WIKI_CACHE_KEY);855
const value = storage.get(WIKI_CACHE_KEY);833
if (!value) {856
if (!value) {834
return null;857
return null;835
}858
}859
let parsed = value;836
if (Array.isArray(value)) {860
if (Array.isArray(value)) {837
return { entries: value };861
parsed = { entries: value, source: "reddit" };838
}862
}839
if (value.entries && Array.isArray(value.entries)) {863
if (!parsed.entries || !Array.isArray(parsed.entries) || !parsed.entries.length) {840
return value;864
return null;841
}865
}866
const source = parsed.source || "reddit";867
const fetchedAt = Number(parsed.fetchedAt || 0);868
if (fetchedAt && Date.now() - fetchedAt > wikiCacheTtl(source)) {869
return null;870
}871
return parsed;842
} catch (err) {872
} catch (err) {843
return null;873
return null;844
}874
}845
return null;846
}875
}847
876
848
function writeWikiCache(entries, source) {877
function writeWikiCache(entries, source) {849
try {878
try {850
const expires = Date.now() + WIKI_CACHE_MS;879
const src = source || "arctic";851
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: source || "reddit" }, expires);880
const expires = Date.now() + wikiCacheTtl(src);881
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: src }, expires);852
} catch (err) {882
} catch (err) {853
// cache is optioneel883
// cache is optioneel854
}884
}@@ -1305,16 +1335,24 @@ async function fetchRedditJson(pathAndQuery) {1305
1335
1306
async function fetchRedditWikiMarkdown(wikiPath) {1336
async function fetchRedditWikiMarkdown(wikiPath) {1307
const path = String(wikiPath || "").replace(/\/+$/, "");1337
const path = String(wikiPath || "").replace(/\/+$/, "");1308
const result = await fetchRedditJson(path + ".json?raw_json=1");1338
// Sommige Reddit-clients willen /wiki/series.json, andere /wiki/series/.json.1309
if (!result.ok) {1339
const variants = [path + ".json?raw_json=1", path + "/.json?raw_json=1"];1310
return result;1340
let last = { ok: false, reason: "lege wikipagina" };1311
}1341
for (let i = 0; i < variants.length; i++) {1312
const data = result.data && result.data.data ? result.data.data : result.data;1342
const result = await fetchRedditJson(variants[i]);1313
const markdown = data && (data.content_md || data.content_html || data.content);1343
if (!result.ok) {1314
if (!markdown || !String(markdown).trim()) {1344
last = result;1315
return { ok: false, reason: "lege wikipagina" };1345
continue;1346
}1347
const data = result.data && result.data.data ? result.data.data : result.data;1348
const markdown = data && (data.content_md || data.content_html || data.content);1349
if (!markdown || !String(markdown).trim()) {1350
last = { ok: false, reason: "lege wikipagina" };1351
continue;1352
}1353
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };1316
}1354
}1317
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };1355
return last;1318
}1356
}1319
1357
1320
async function fetchRedditSearch(term, page) {1358
async function fetchRedditSearch(term, page) {@@ -1341,20 +1379,38 @@ async function fetchRedditListing(path, page) {1341
}1379
}1342
1380
1343
async function fetchRedditPostsByIds(ids) {1381
async function fetchRedditPostsByIds(ids) {1344
const full = uniqueIds(ids).map((id) => "t3_" + id);1382
const wanted = uniqueIds(ids);1383
const full = wanted.map((id) => "t3_" + id);1345
const posts = [];1384
const posts = [];1385
let infoFailed = null;1346
for (let i = 0; i < full.length; i += 100) {1386
for (let i = 0; i < full.length; i += 100) {1347
const chunk = full.slice(i, i + 100);1387
const chunk = full.slice(i, i + 100);1348
const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");1388
const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");1349
if (!result.ok) {1389
if (!result.ok) {1350
if (!posts.length) {1390
if (!posts.length) {1351
return result;1391
infoFailed = result;1392
break;1352
}1393
}1353
break;1394
break;1354
}1395
}1355
listingPosts(result.data).forEach((p) => posts.push(p));1396
listingPosts(result.data).forEach((p) => posts.push(p));1356
}1397
}1357
return { ok: true, posts: posts, source: "reddit" };1398
if (posts.length) {1399
return { ok: true, posts: posts, source: "reddit" };1400
}1401
// /api/info.json is een ander endpoint dan de hoofdstukken1402
// (/comments/{id}/.json) en kan 403 geven terwijl die wel werken.1403
const fromComments = [];1404
for (let i = 0; i < wanted.length; i++) {1405
const chapter = await tryRedditChapter(wanted[i]);1406
if (chapter && chapter.ok && chapter.post) {1407
fromComments.push(chapter.post);1408
}1409
}1410
if (fromComments.length) {1411
return { ok: true, posts: fromComments, source: "reddit" };1412
}1413
return infoFailed || { ok: false, reason: "geen posts" };1358
}1414
}1359
1415
1360
function listingPosts(payload) {1416
function listingPosts(payload) {@@ -4,7 +4,7 @@
4
4
"name": "HFY Novels",
5
5
"site": "https://www.reddit.com/r/HFY/",
6
6
"lang": "English",
7
"version": "0.3.3",
7
"version": "0.3.4",
8
8
"url": "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master",
9
9
"iconUrl": "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master",
10
10
"hasSettings": true
@@ -4,7 +4,7 @@4
"name": "HFY Novels",4
"name": "HFY Novels",5
"site": "https://www.reddit.com/r/HFY/",5
"site": "https://www.reddit.com/r/HFY/",6
"lang": "English",6
"lang": "English",7
"version": "0.3.3",7
"version": "0.3.4",8
"url": "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master",8
"url": "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master",9
"iconUrl": "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master",9
"iconUrl": "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master",10
"hasSettings": true10
"hasSettings": true@@ -1 +1 @@
1
[{"id":"hfyNovels","name":"HFY Novels","site":"https://www.reddit.com/r/HFY/","lang":"English","version":"0.3.3","url":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master","iconUrl":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master","hasSettings":true}]
1
[{"id":"hfyNovels","name":"HFY Novels","site":"https://www.reddit.com/r/HFY/","lang":"English","version":"0.3.4","url":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master","iconUrl":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master","hasSettings":true}]
@@ -1 +1 @@1
[{"id":"hfyNovels","name":"HFY Novels","site":"https://www.reddit.com/r/HFY/","lang":"English","version":"0.3.3","url":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master","iconUrl":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master","hasSettings":true}]1
[{"id":"hfyNovels","name":"HFY Novels","site":"https://www.reddit.com/r/HFY/","lang":"English","version":"0.3.4","url":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/hfy-novels.js?rev=master","iconUrl":"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/icon.png?rev=master","hasSettings":true}]@@ -32,14 +32,13 @@ BlueGit serveert raw-bestanden als `text/plain`. Dat is voor LNReader geen probl
32
32
33
33
Bij een fout, 403 of loginpagina valt zoeken, bladeren en de hoofdstuklijst terug op Arctic Shift, en daarna op de statische index in deze repo.
34
34
35
Verhalen in de **statische index** houden hun vooraf gemaakte cover: de indexer schrijft een PNG (240×360) in `public/covers/` (zonder Pillow een SVG) uit een hash van de titel (kleurverloop of patroon, titel erop). Dezelfde titel geeft altijd dezelfde cover. LNReader laadt covers met expo-image; PNG is daar betrouwbaar, SVG niet altijd.
35
Vanaf **0.3.4** gebruikt de plugin drie vaste, kleine PNG-covers (240×360, gewone https-URL, geen data-URI en geen titelgeneratie op het toestel). Allemaal het r/HFY-community-icoon in het midden, met rechtsonder een bronbadge:
36
36
37
Live gevonden verhalen (via Reddit of Arctic Shift, zonder bestand in de index) krijgen vanaf **0.3.2** één vaste, kleine PNG per bron, als gewone https-URL:
37
- `/.dist/covers/reddit.png` — Reddit-badge, als de data via Reddit kwam
38
- `/.dist/covers/arctic-shift.png` — Arctic Shift-badge, alleen als de Arctic Shift-fallback de data leverde
39
- `/.dist/covers/index.png` — badge van projects.timfalken.com, als de reeks uit de statische index komt
38
40
39
- Reddit: het r/HFY-community-icoon (`/.dist/covers/reddit.png`)
40
- Arctic Shift (fallback): het logo van Arctic Shift (`/.dist/covers/arctic-shift.png`)
41
42
De plugin genereert geen covers meer op het toestel (geen `data:`-URI's). Die data-URI's uit 0.3.1 konden LNReader vastzetten in de bronlijst en de bibliotheek. Bij een bibliotheek-refresh geeft `parseNovel` opnieuw een gewone URL: de indexcover als het verhaal daarin staat, anders de broncover. LNReader overschrijft de opgeslagen cover dan als je de metadata mee ververst. Vanaf **0.3.3** laat een fout of 502 van Reddit/Arctic Shift `parseNovel` niet meer crashen: verhalen in de statische index openen dan gewoon via die fallback (in 0.3.2 gaf dat overal "unable to load novel").
41
De badge volgt de bron die de lijst of de reeks daadwerkelijk leverde. Bij twijfel kiezen we Reddit. De drie bestanden bouw je met `python3 scripts/build-covers.py`. Een bibliotheek-refresh (mét metadata) laat `parseNovel` een oude cover in LNReader overschrijven. Vanaf **0.3.3** laat een fout of 502 van Reddit/Arctic Shift `parseNovel` niet meer crashen: verhalen in de statische index openen dan via die fallback (in 0.3.2 gaf dat overal "unable to load novel").
43
42
44
43
45
44
### Inloggen via de WebView (aanbevolen)
@@ -49,7 +48,7 @@ Anonieme Reddit-JSON is sinds 2026 vaak geblokkeerd. Als je in LNReader op reddi
49
48
1. Werk de plugin bij als LNReader een update naar **0.3.3** toont (bronnen verversen, daarna bijwerken).
50
49
2. Open de plugin **HFY Novels** → **Website** (of in een reeks/hoofdstuk **Open in WebView**). Je komt op r/HFY.
51
50
3. Log in op Reddit met *jouw* account en sluit de WebView daarna af. Iemand anders (bijvoorbeeld op een andere telefoon) logt met een eigen account in; de sessies blijven gescheiden.
52
4. Ga terug naar de plugin: **Popular** toont de wiki-series, **Latest** (of filter **Nieuw**) recente OC-posts. Zoek op een titel. Open een reeks en controleer of de hoofdstuklijst klopt, en open daarna een hoofdstuk. Live gevonden reeksen die niet in de statische index zitten, tonen het r/HFY-logo (of het Arctic Shift-logo als die fallback is gebruikt). Verhalen uit de statische index houden hun eigen titelcover. Als een verhaal tijdens 0.3.1 in je bibliotheek is gezet en de app traag blijft, open het verhaal, ververs het (inclusief metadata) of verwijder het en voeg het opnieuw toe.
51
4. Ga terug naar de plugin: **Popular** toont de wiki-series, **Latest** (of filter **Nieuw**) recente OC-posts. Zoek op een titel. Open een reeks en controleer of de hoofdstuklijst klopt, en open daarna een hoofdstuk. De cover is het r/HFY-logo met rechtsonder een badge van de bron die de data leverde (Reddit, Arctic Shift, of de statische index). Als je eerder een verkeerde badge of een data-URI in je bibliotheek hebt, ververs het verhaal inclusief metadata (of verwijder het en voeg het opnieuw toe).
53
52
5. Onderaan de hoofdstuktekst staat **Bron: Reddit** als het via je sessie lukte, of **Bron: Arctic Shift (fallback)** als Reddit een 403 of loginpagina teruggaf. Zonder login blijven bladeren en lezen werken via Arctic Shift en de statische index.
54
53
55
54
In de plugin-instellingen kun je de bron vastzetten op *Automatisch*, *Alleen Reddit* of *Alleen Arctic Shift*, en zo nodig de index-URL of Arctic Shift-basis-URL aanpassen.
@@ -32,14 +32,13 @@ BlueGit serveert raw-bestanden als `text/plain`. Dat is voor LNReader geen probl32
32
33
Bij een fout, 403 of loginpagina valt zoeken, bladeren en de hoofdstuklijst terug op Arctic Shift, en daarna op de statische index in deze repo.33
Bij een fout, 403 of loginpagina valt zoeken, bladeren en de hoofdstuklijst terug op Arctic Shift, en daarna op de statische index in deze repo.34
34
35
Verhalen in de **statische index** houden hun vooraf gemaakte cover: de indexer schrijft een PNG (240×360) in `public/covers/` (zonder Pillow een SVG) uit een hash van de titel (kleurverloop of patroon, titel erop). Dezelfde titel geeft altijd dezelfde cover. LNReader laadt covers met expo-image; PNG is daar betrouwbaar, SVG niet altijd.35
Vanaf **0.3.4** gebruikt de plugin drie vaste, kleine PNG-covers (240×360, gewone https-URL, geen data-URI en geen titelgeneratie op het toestel). Allemaal het r/HFY-community-icoon in het midden, met rechtsonder een bronbadge:36
36
37
Live gevonden verhalen (via Reddit of Arctic Shift, zonder bestand in de index) krijgen vanaf **0.3.2** één vaste, kleine PNG per bron, als gewone https-URL:37
- `/.dist/covers/reddit.png` — Reddit-badge, als de data via Reddit kwam38
- `/.dist/covers/arctic-shift.png` — Arctic Shift-badge, alleen als de Arctic Shift-fallback de data leverde39
- `/.dist/covers/index.png` — badge van projects.timfalken.com, als de reeks uit de statische index komt38
40
39
- Reddit: het r/HFY-community-icoon (`/.dist/covers/reddit.png`)41
De badge volgt de bron die de lijst of de reeks daadwerkelijk leverde. Bij twijfel kiezen we Reddit. De drie bestanden bouw je met `python3 scripts/build-covers.py`. Een bibliotheek-refresh (mét metadata) laat `parseNovel` een oude cover in LNReader overschrijven. Vanaf **0.3.3** laat een fout of 502 van Reddit/Arctic Shift `parseNovel` niet meer crashen: verhalen in de statische index openen dan via die fallback (in 0.3.2 gaf dat overal "unable to load novel").40
- Arctic Shift (fallback): het logo van Arctic Shift (`/.dist/covers/arctic-shift.png`)41
42
De plugin genereert geen covers meer op het toestel (geen `data:`-URI's). Die data-URI's uit 0.3.1 konden LNReader vastzetten in de bronlijst en de bibliotheek. Bij een bibliotheek-refresh geeft `parseNovel` opnieuw een gewone URL: de indexcover als het verhaal daarin staat, anders de broncover. LNReader overschrijft de opgeslagen cover dan als je de metadata mee ververst. Vanaf **0.3.3** laat een fout of 502 van Reddit/Arctic Shift `parseNovel` niet meer crashen: verhalen in de statische index openen dan gewoon via die fallback (in 0.3.2 gaf dat overal "unable to load novel").43
42
44
43
45
### Inloggen via de WebView (aanbevolen)44
### Inloggen via de WebView (aanbevolen)@@ -49,7 +48,7 @@ Anonieme Reddit-JSON is sinds 2026 vaak geblokkeerd. Als je in LNReader op reddi49
1. Werk de plugin bij als LNReader een update naar **0.3.3** toont (bronnen verversen, daarna bijwerken).48
1. Werk de plugin bij als LNReader een update naar **0.3.3** toont (bronnen verversen, daarna bijwerken).50
2. Open de plugin **HFY Novels** → **Website** (of in een reeks/hoofdstuk **Open in WebView**). Je komt op r/HFY.49
2. Open de plugin **HFY Novels** → **Website** (of in een reeks/hoofdstuk **Open in WebView**). Je komt op r/HFY.51
3. Log in op Reddit met *jouw* account en sluit de WebView daarna af. Iemand anders (bijvoorbeeld op een andere telefoon) logt met een eigen account in; de sessies blijven gescheiden.50
3. Log in op Reddit met *jouw* account en sluit de WebView daarna af. Iemand anders (bijvoorbeeld op een andere telefoon) logt met een eigen account in; de sessies blijven gescheiden.52
4. Ga terug naar de plugin: **Popular** toont de wiki-series, **Latest** (of filter **Nieuw**) recente OC-posts. Zoek op een titel. Open een reeks en controleer of de hoofdstuklijst klopt, en open daarna een hoofdstuk. Live gevonden reeksen die niet in de statische index zitten, tonen het r/HFY-logo (of het Arctic Shift-logo als die fallback is gebruikt). Verhalen uit de statische index houden hun eigen titelcover. Als een verhaal tijdens 0.3.1 in je bibliotheek is gezet en de app traag blijft, open het verhaal, ververs het (inclusief metadata) of verwijder het en voeg het opnieuw toe.51
4. Ga terug naar de plugin: **Popular** toont de wiki-series, **Latest** (of filter **Nieuw**) recente OC-posts. Zoek op een titel. Open een reeks en controleer of de hoofdstuklijst klopt, en open daarna een hoofdstuk. De cover is het r/HFY-logo met rechtsonder een badge van de bron die de data leverde (Reddit, Arctic Shift, of de statische index). Als je eerder een verkeerde badge of een data-URI in je bibliotheek hebt, ververs het verhaal inclusief metadata (of verwijder het en voeg het opnieuw toe).53
5. Onderaan de hoofdstuktekst staat **Bron: Reddit** als het via je sessie lukte, of **Bron: Arctic Shift (fallback)** als Reddit een 403 of loginpagina teruggaf. Zonder login blijven bladeren en lezen werken via Arctic Shift en de statische index.52
5. Onderaan de hoofdstuktekst staat **Bron: Reddit** als het via je sessie lukte, of **Bron: Arctic Shift (fallback)** als Reddit een 403 of loginpagina teruggaf. Zonder login blijven bladeren en lezen werken via Arctic Shift en de statische index.54
53
55
In de plugin-instellingen kun je de bron vastzetten op *Automatisch*, *Alleen Reddit* of *Alleen Arctic Shift*, en zo nodig de index-URL of Arctic Shift-basis-URL aanpassen.54
In de plugin-instellingen kun je de bron vastzetten op *Automatisch*, *Alleen Reddit* of *Alleen Arctic Shift*, en zo nodig de index-URL of Arctic Shift-basis-URL aanpassen.@@ -71,14 +71,30 @@ LNReader eist dat de repository-URL `plugins.min.json` bevat (regex in `Settings
71
71
72
72
## Covers
73
73
74
Verhalen op r/HFY hebben geen officiële omslag. Als een item geen cover heeft, maakt de indexer er een uit de titel: SHA-256 van de getrimde titel bepaalt de kleuren en het patroon, de titel zelf staat (afgebroken indien nodig) op een donkere band. Dat gebeurt tijdens `write_index`, in CI en lokaal, als statisch bestand onder `public/covers/{hash[0:2]}/{hash}.png`. Zonder Pillow wordt het een `.svg`.
74
Vanaf 0.3.4 toont de plugin geen per-titelcovers meer. Alle items krijgen één van drie vaste PNG's (240×360, kleine bestanden, gewone https-URL op `/.dist/covers/…?rev=master`, geen data-URI): het r/HFY-community-icoon groot in het midden, en rechtsonder een bronbadge.
75
75
76
LNReader toont covers met `expo-image` (`NovelCoverImage`, `cachePolicy: 'memory-disk'`). Die component is betrouwbaar voor PNG, niet altijd voor SVG. Daarom staat in de catalogus de PNG-URL. Op BlueGit-raw krijgen PNG's `image/png`. Als de index toch naar een SVG wijst, voegt de plugin `?as=img` toe zodat BlueGit `image/svg+xml` geeft.
76
- `reddit.png` — Reddit-snoo-badge, als de catalogus of `parseNovel` de data via Reddit kreeg
77
- `arctic-shift.png` — logo van Arctic Shift, alleen als de Arctic Shift-fallback de data leverde
78
- `index.png` — favicon van [projects.timfalken.com](https://projects.timfalken.com) (de T), als de reeks uit de statische index in deze repo komt
77
79
78
BlueGit kan geen dynamische afbeeldingen serveren. Live gevonden reeksen (zonder bestand in `public/covers/`) krijgen vanaf 0.3.2 geen gegenereerde cover meer op het toestel. 0.3.1 zette per titel een `data:image/png;base64` in de catalogus; LNReader probeerde die bij toevoegen aan de bibliotheek te downloaden via OkHttp (`downloadFile`), wat voor `data:`-URI's faalt, waarna de (grote) URI in de database bleef staan. Veel van die URI's tegelijk tekenden de bronlijst en de bibliotheek vast. Vanaf 0.3.2 is de live-cover een gewone, kleine https-URL naar één vast bestand per bron: `.dist/covers/reddit.png` (officiële r/HFY-community-icoon) of `.dist/covers/arctic-shift.png` (favicon van arctic-shift.photon-reddit.com), beide 240×360. De wiki-cache bewaart de bron (`reddit` of `arctic`), zodat een gecachte lijst de juiste cover houdt. Items zonder cover én zonder live-bron (bijvoorbeeld de zoekindex, die geen cover-veld heeft) vallen terug op LNReader's `defaultCover`, niet op een bronlogo.
80
Keuze: live Reddit wint boven Arctic (ook als de wiki-pagina via Arctic kwam maar de posts via Reddit); de indexcover geldt alleen als er geen live-data was. Bij een ontbrekende of onbekende bron kiezen we Reddit, niet LNReader's `defaultCover` en niet Arctic.
79
81
80
In 0.3.2 gooide `liveParseNovel` een TypeError (`Cannot read properties of undefined (reading 'length')`) als Reddit 403 gaf en Arctic Shift `/api/posts/ids` (of de wiki) met HTTP 502 antwoordde zonder `posts`-array. `parseNovel` ving die throw niet op, dus de statische index werd nooit als fallback gebruikt en LNReader toonde overal "unable to load novel" — ook bij verhalen die wel in de index staan, en terwijl de catalogus nog Arctic Shift-covers kon tonen (wiki-index of cache). Vanaf 0.3.3 wordt een ontbrekende `posts`-array als lege lijst behandeld, vangt `parseNovel` throws van de live-poging af, en blijft de statische fallback werken. Het teruggegeven `SourceNovel.path` is altijd het aangevraagde pad. Een mislukte cover-download in LNReader zelf hoort `parseNovel` niet te raken; de plugin haalt covers niet op tijdens `parseNovel`, ze zijn alleen URL's in het resultaat.
82
De drie PNG's worden deterministisch gebouwd met `python3 scripts/build-covers.py` uit `scripts/cover-assets/` (bronnen in `SOURCES.txt`). De plugin en `scripts/build-manifest.js` kopiëren ze naar `.dist/covers/`.
81
83
82
`parseNovel` geeft dezelfde gewone URL's terug. Staat de reeks in de statische index, dan wint die indexcover, ook als de live-bron al een logo had meegegeven. In LNReader (`LibraryUpdateQueries.ts`, `updateNovelMetadata`) wordt de cover alleen overschreven als de update-optie *refresh novel metadata* aan staat (of je het verhaal opnieuw toevoegt). Dan downloadt `downloadFile` de nieuwe http(s)-URL naar `cover.png` en zet de database op `file://…`. Lukt de download niet, dan wordt `cover` op `null` gezet. Zonder metadata-refresh blijft een oude data-URI in de bibliotheek staan; verwijderen en opnieuw toevoegen lost dat ook op.
84
De indexer kan nog steeds per-titel-PNG's naar `public/covers/` schrijven (`indexer/covers.py`, voor de bestaande index-tests). De plugin negeert die paden.
85
86
### Endpoints en cache (waarom Reddit-hoofdstukken bij een Arctic-cover voorkwamen)
87
88
Hoofdstukken gaan via `/r/HFY/comments/{id}/.json` (eerst www, dan old.reddit). De catalogus en `parseNovel` gebruikten andere Reddit-endpoints, die met dezelfde WebView-cookies wél 403 kunnen geven:
89
90
- wiki-index en subpagina's: `/r/HFY/wiki/series.json` (en `/wiki/series/.json`)
91
- Latest: `/r/HFY/new.json`
92
- zoeken: `/r/HFY/search.json`
93
- posts voor `parseNovel`: eerst `/api/info.json?id=t3_…`, vanaf 0.3.4 bij falen dezelfde `/comments/{id}/.json` als de hoofdstukken
94
95
Als de wiki-JSON faalde, viel Popular terug op Arctic Shift en bewaarde 0.3.2/0.3.3 die lijst zes uur in `wikiSeriesIndex` met bron `arctic`. Daarna bleven alle lijst-covers Arctic, ook nadat de gebruiker inlogde en `parseChapter` "Bron: Reddit" toonde. Vanaf 0.3.4 is de cachesleutel `wikiSeriesIndex.v2` (oude caches vervallen), blijft een Reddit-hit zes uur geldig, en wordt een Arctic-fallback maar vijf minuten bewaard. Staat er een Arctic-cache, dan probeert `loadWikiIndex` Reddit altijd eerst opnieuw.
96
97
LNReader toont covers met `expo-image` (`NovelCoverImage`, `cachePolicy: 'memory-disk'`), betrouwbaar voor PNG. Op BlueGit-raw krijgen PNG's `image/png`. `parseNovel` haalt covers niet zelf op; het zijn alleen URL's in het resultaat. In LNReader (`updateNovelMetadata`) wordt een opgeslagen cover alleen overschreven als *refresh novel metadata* aan staat, of als je het verhaal opnieuw toevoegt.
98
99
0.3.1 zette per titel een `data:image/png;base64` in de catalogus; die URI's bleven in de bibliotheek-database staan en zetten de app vast. 0.3.2 stapte over op vaste https-covers, maar `liveParseNovel` gooide een TypeError als Arctic Shift zonder `posts`-array 502 gaf, waardoor de statische fallback nooit draaide ("unable to load novel"). 0.3.3 vangt dat af.
83
100
84
De index-PNG's gebruiken DejaVu Sans Bold (Bitstream Vera-licentie, `indexer/fonts/`). Zonder Pillow valt de indexer terug op alleen SVG. Twee verhalen met dezelfde weergavetitel delen dezelfde indexcover; dat is bewust, de hash is alleen de titel.
@@ -71,14 +71,30 @@ LNReader eist dat de repository-URL `plugins.min.json` bevat (regex in `Settings71
71
72
## Covers72
## Covers73
73
74
Verhalen op r/HFY hebben geen officiële omslag. Als een item geen cover heeft, maakt de indexer er een uit de titel: SHA-256 van de getrimde titel bepaalt de kleuren en het patroon, de titel zelf staat (afgebroken indien nodig) op een donkere band. Dat gebeurt tijdens `write_index`, in CI en lokaal, als statisch bestand onder `public/covers/{hash[0:2]}/{hash}.png`. Zonder Pillow wordt het een `.svg`.74
Vanaf 0.3.4 toont de plugin geen per-titelcovers meer. Alle items krijgen één van drie vaste PNG's (240×360, kleine bestanden, gewone https-URL op `/.dist/covers/…?rev=master`, geen data-URI): het r/HFY-community-icoon groot in het midden, en rechtsonder een bronbadge.75
75
76
LNReader toont covers met `expo-image` (`NovelCoverImage`, `cachePolicy: 'memory-disk'`). Die component is betrouwbaar voor PNG, niet altijd voor SVG. Daarom staat in de catalogus de PNG-URL. Op BlueGit-raw krijgen PNG's `image/png`. Als de index toch naar een SVG wijst, voegt de plugin `?as=img` toe zodat BlueGit `image/svg+xml` geeft.76
- `reddit.png` — Reddit-snoo-badge, als de catalogus of `parseNovel` de data via Reddit kreeg77
- `arctic-shift.png` — logo van Arctic Shift, alleen als de Arctic Shift-fallback de data leverde78
- `index.png` — favicon van [projects.timfalken.com](https://projects.timfalken.com) (de T), als de reeks uit de statische index in deze repo komt77
79
78
BlueGit kan geen dynamische afbeeldingen serveren. Live gevonden reeksen (zonder bestand in `public/covers/`) krijgen vanaf 0.3.2 geen gegenereerde cover meer op het toestel. 0.3.1 zette per titel een `data:image/png;base64` in de catalogus; LNReader probeerde die bij toevoegen aan de bibliotheek te downloaden via OkHttp (`downloadFile`), wat voor `data:`-URI's faalt, waarna de (grote) URI in de database bleef staan. Veel van die URI's tegelijk tekenden de bronlijst en de bibliotheek vast. Vanaf 0.3.2 is de live-cover een gewone, kleine https-URL naar één vast bestand per bron: `.dist/covers/reddit.png` (officiële r/HFY-community-icoon) of `.dist/covers/arctic-shift.png` (favicon van arctic-shift.photon-reddit.com), beide 240×360. De wiki-cache bewaart de bron (`reddit` of `arctic`), zodat een gecachte lijst de juiste cover houdt. Items zonder cover én zonder live-bron (bijvoorbeeld de zoekindex, die geen cover-veld heeft) vallen terug op LNReader's `defaultCover`, niet op een bronlogo.80
Keuze: live Reddit wint boven Arctic (ook als de wiki-pagina via Arctic kwam maar de posts via Reddit); de indexcover geldt alleen als er geen live-data was. Bij een ontbrekende of onbekende bron kiezen we Reddit, niet LNReader's `defaultCover` en niet Arctic.79
81
80
In 0.3.2 gooide `liveParseNovel` een TypeError (`Cannot read properties of undefined (reading 'length')`) als Reddit 403 gaf en Arctic Shift `/api/posts/ids` (of de wiki) met HTTP 502 antwoordde zonder `posts`-array. `parseNovel` ving die throw niet op, dus de statische index werd nooit als fallback gebruikt en LNReader toonde overal "unable to load novel" — ook bij verhalen die wel in de index staan, en terwijl de catalogus nog Arctic Shift-covers kon tonen (wiki-index of cache). Vanaf 0.3.3 wordt een ontbrekende `posts`-array als lege lijst behandeld, vangt `parseNovel` throws van de live-poging af, en blijft de statische fallback werken. Het teruggegeven `SourceNovel.path` is altijd het aangevraagde pad. Een mislukte cover-download in LNReader zelf hoort `parseNovel` niet te raken; de plugin haalt covers niet op tijdens `parseNovel`, ze zijn alleen URL's in het resultaat.82
De drie PNG's worden deterministisch gebouwd met `python3 scripts/build-covers.py` uit `scripts/cover-assets/` (bronnen in `SOURCES.txt`). De plugin en `scripts/build-manifest.js` kopiëren ze naar `.dist/covers/`.81
83
82
`parseNovel` geeft dezelfde gewone URL's terug. Staat de reeks in de statische index, dan wint die indexcover, ook als de live-bron al een logo had meegegeven. In LNReader (`LibraryUpdateQueries.ts`, `updateNovelMetadata`) wordt de cover alleen overschreven als de update-optie *refresh novel metadata* aan staat (of je het verhaal opnieuw toevoegt). Dan downloadt `downloadFile` de nieuwe http(s)-URL naar `cover.png` en zet de database op `file://…`. Lukt de download niet, dan wordt `cover` op `null` gezet. Zonder metadata-refresh blijft een oude data-URI in de bibliotheek staan; verwijderen en opnieuw toevoegen lost dat ook op.84
De indexer kan nog steeds per-titel-PNG's naar `public/covers/` schrijven (`indexer/covers.py`, voor de bestaande index-tests). De plugin negeert die paden.85
86
### Endpoints en cache (waarom Reddit-hoofdstukken bij een Arctic-cover voorkwamen)87
88
Hoofdstukken gaan via `/r/HFY/comments/{id}/.json` (eerst www, dan old.reddit). De catalogus en `parseNovel` gebruikten andere Reddit-endpoints, die met dezelfde WebView-cookies wél 403 kunnen geven:89
90
- wiki-index en subpagina's: `/r/HFY/wiki/series.json` (en `/wiki/series/.json`)91
- Latest: `/r/HFY/new.json`92
- zoeken: `/r/HFY/search.json`93
- posts voor `parseNovel`: eerst `/api/info.json?id=t3_…`, vanaf 0.3.4 bij falen dezelfde `/comments/{id}/.json` als de hoofdstukken94
95
Als de wiki-JSON faalde, viel Popular terug op Arctic Shift en bewaarde 0.3.2/0.3.3 die lijst zes uur in `wikiSeriesIndex` met bron `arctic`. Daarna bleven alle lijst-covers Arctic, ook nadat de gebruiker inlogde en `parseChapter` "Bron: Reddit" toonde. Vanaf 0.3.4 is de cachesleutel `wikiSeriesIndex.v2` (oude caches vervallen), blijft een Reddit-hit zes uur geldig, en wordt een Arctic-fallback maar vijf minuten bewaard. Staat er een Arctic-cache, dan probeert `loadWikiIndex` Reddit altijd eerst opnieuw.96
97
LNReader toont covers met `expo-image` (`NovelCoverImage`, `cachePolicy: 'memory-disk'`), betrouwbaar voor PNG. Op BlueGit-raw krijgen PNG's `image/png`. `parseNovel` haalt covers niet zelf op; het zijn alleen URL's in het resultaat. In LNReader (`updateNovelMetadata`) wordt een opgeslagen cover alleen overschreven als *refresh novel metadata* aan staat, of als je het verhaal opnieuw toevoegt.98
99
0.3.1 zette per titel een `data:image/png;base64` in de catalogus; die URI's bleven in de bibliotheek-database staan en zetten de app vast. 0.3.2 stapte over op vaste https-covers, maar `liveParseNovel` gooide een TypeError als Arctic Shift zonder `posts`-array 502 gaf, waardoor de statische fallback nooit draaide ("unable to load novel"). 0.3.3 vangt dat af.83
100
84
De index-PNG's gebruiken DejaVu Sans Bold (Bitstream Vera-licentie, `indexer/fonts/`). Zonder Pillow valt de indexer terug op alleen SVG. Twee verhalen met dezelfde weergavetitel delen dezelfde indexcover; dat is bewust, de hash is alleen de titel.The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -10,10 +10,11 @@
10
10
* waarbij series en losse Part-1-posts tot één novel worden gegroepeerd
11
11
* - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis
12
12
*
13
* Verhalen in de statische index houden hun vooraf gemaakte cover-URL.
14
* Live gevonden verhalen zonder die PNG krijgen één vaste cover per bron:
15
* Reddit (r/HFY-logo) of Arctic Shift (site-logo), als gewone https-URL
16
* in .dist/covers/. Geen data-URI's en geen generatie op het toestel.
13
* Covers zijn drie vaste PNGs in .dist/covers/ (gewone https-URL, geen
14
* data-URI, geen titelgeneratie op het toestel): r/HFY-logo in het midden
15
* en rechtsonder een bronbadge. De badge volgt de bron die de data
16
* leverde: reddit.png, arctic-shift.png, of index.png (statische index).
17
* Bij twijfel gebruiken we de Reddit-cover.
17
18
*
18
19
* Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,
19
20
* en daarna op de statische metadata-index (ook bruikbaar zonder login).
@@ -36,11 +37,15 @@ const DEFAULT_INDEX_BASE =
36
37
const RAW_PLUGIN_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw";
37
38
const LIVE_COVER_REDDIT = RAW_PLUGIN_BASE + "/.dist/covers/reddit.png?rev=master";
38
39
const LIVE_COVER_ARCTIC = RAW_PLUGIN_BASE + "/.dist/covers/arctic-shift.png?rev=master";
40
const LIVE_COVER_INDEX = RAW_PLUGIN_BASE + "/.dist/covers/index.png?rev=master";
39
41
const DEFAULT_INDEX_REV = "master";
40
42
const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";
41
43
const PAGE_FALLBACK_SIZE = 50;
42
const WIKI_CACHE_KEY = "wikiSeriesIndex";
43
const WIKI_CACHE_MS = 6 * 60 * 60 * 1000;
44
// v2: ongeldig verklaart caches uit 0.3.2/0.3.3 die een Arctic-fallback
45
// zes uur vasthielden terwijl hoofdstukken intussen via Reddit werkten.
46
const WIKI_CACHE_KEY = "wikiSeriesIndex.v2";
47
const WIKI_CACHE_MS_REDDIT = 6 * 60 * 60 * 1000;
48
const WIKI_CACHE_MS_ARCTIC = 5 * 60 * 1000;
44
49
const REDDIT_WWW = "https://www.reddit.com";
45
50
const REDDIT_OLD = "https://old.reddit.com";
46
51
const WIKI_INDEX_PATH = "/r/HFY/wiki/series";
@@ -109,11 +114,21 @@ function toNovelItem(entry, plugin) {
109
114
};
110
115
}
111
116
117
function coverSourceOf(postSource, wikiSource) {
118
if (postSource === "reddit" || wikiSource === "reddit") {
119
return "reddit";
120
}
121
if (postSource === "arctic" || wikiSource === "arctic") {
122
return "arctic";
123
}
124
return "reddit";
125
}
126
112
127
class HFYNovelsPlugin {
113
128
constructor() {
114
129
this.id = "hfyNovels";
115
130
this.name = "HFY Novels";
116
this.version = "0.3.3";
131
this.version = "0.3.4";
117
132
this.site = "https://www.reddit.com/r/HFY/";
118
133
this.icon = "icon.png";
119
134
// Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's
@@ -189,17 +204,16 @@ class HFYNovelsPlugin {
189
204
}
190
205
191
206
coverFor(entry) {
192
if (entry && entry.cover) {
193
return this.coverUrl(entry.cover);
194
}
207
// Per-titelcovers uit de statische index worden niet meer gebruikt.
195
208
const source = entry && entry.source;
196
209
if (source === "arctic") {
197
210
return LIVE_COVER_ARCTIC;
198
211
}
199
if (source === "reddit") {
200
return LIVE_COVER_REDDIT;
212
if (source === "index") {
213
return LIVE_COVER_INDEX;
201
214
}
202
return defaultCover;
215
// reddit, of bij twijfel (ontbrekende/onbekende bron).
216
return LIVE_COVER_REDDIT;
203
217
}
204
218
205
219
coverUrl(cover) {
@@ -381,9 +395,8 @@ class HFYNovelsPlugin {
381
395
}
382
396
// Statische indexcovers overschrijven een live broncover, zodat een
383
397
// bibliotheek-refresh een eerdere data-URI of logo kan vervangen.
384
if (fallback.cover) {
385
novel.cover = fallback.cover;
386
}
398
// Live data houdt de live-broncover (reddit/arctic). De indexcover
399
// geldt alleen als de reeks uitsluitend uit de statische index komt.
387
400
return finish(novel);
388
401
} catch (err) {
389
402
if (novel) {
@@ -461,14 +474,14 @@ class HFYNovelsPlugin {
461
474
}
462
475
const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);
463
476
const novels = (payload.novels || []).filter((n) => !n.nsfw);
464
return novels.map((n) => toNovelItem(n, this));
477
return novels.map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));
465
478
}
466
479
467
480
const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");
468
481
const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));
469
482
const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;
470
483
const start = (page - 1) * size;
471
return items.slice(start, start + size).map((n) => toNovelItem(n, this));
484
return items.slice(start, start + size).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));
472
485
}
473
486
474
487
async staticSearch(searchTerm, pageNo) {
@@ -484,7 +497,7 @@ class HFYNovelsPlugin {
484
497
return name.includes(term) || author.includes(term);
485
498
});
486
499
const start = (page - 1) * PAGE_FALLBACK_SIZE;
487
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(n, this));
500
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));
488
501
}
489
502
490
503
async staticParseNovel(novelPath) {
@@ -494,7 +507,7 @@ class HFYNovelsPlugin {
494
507
name: data.name || "Untitled",
495
508
author: data.author || "Anonymous",
496
509
artist: undefined,
497
cover: this.coverFor({ name: data.name, cover: data.cover }),
510
cover: this.coverFor({ name: data.name, source: "index" }),
498
511
genres: data.genres || "HFY",
499
512
status: statusFrom(data.status),
500
513
summary: data.summary || "",
@@ -626,7 +639,7 @@ class HFYNovelsPlugin {
626
639
name: name,
627
640
author: author,
628
641
artist: undefined,
629
cover: this.coverFor({ name: name, cover: null, source: (fetched && fetched.source) || source }),
642
cover: this.coverFor({ name: name, source: coverSourceOf(fetched && fetched.source, source) }),
630
643
genres: nsfw ? "HFY, NSFW" : "HFY",
631
644
status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,
632
645
summary: author ? "HFY-serie van u/" + author + "." : "",
@@ -642,8 +655,11 @@ class HFYNovelsPlugin {
642
655
643
656
async loadWikiIndex(mode) {
644
657
const cached = readWikiCache();
645
if (cached && cached.entries && cached.entries.length) {
646
return { ok: true, entries: cached.entries, source: cached.source || "reddit" };
658
const haveCached = cached && cached.entries && cached.entries.length;
659
// Alleen een Reddit-cache is lang geldig. Een Arctic-fallback cachen we
660
// kort, en we proberen Reddit altijd opnieuw (bijv. na WebView-login).
661
if (haveCached && cached.source === "reddit") {
662
return { ok: true, entries: cached.entries, source: "reddit" };
647
663
}
648
664
if (mode !== "arctic") {
649
665
const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);
@@ -658,6 +674,9 @@ class HFYNovelsPlugin {
658
674
return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };
659
675
}
660
676
}
677
if (haveCached) {
678
return { ok: true, entries: cached.entries, source: cached.source || "arctic" };
679
}
661
680
const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);
662
681
if (arctic.ok) {
663
682
const entries = parseSeriesIndex(arctic.markdown);
@@ -827,28 +846,39 @@ function wikiEntryMatches(entry, term) {
827
846
return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
828
847
}
829
848
849
function wikiCacheTtl(source) {
850
return source === "reddit" ? WIKI_CACHE_MS_REDDIT : WIKI_CACHE_MS_ARCTIC;
851
}
852
830
853
function readWikiCache() {
831
854
try {
832
855
const value = storage.get(WIKI_CACHE_KEY);
833
856
if (!value) {
834
857
return null;
835
858
}
859
let parsed = value;
836
860
if (Array.isArray(value)) {
837
return { entries: value };
861
parsed = { entries: value, source: "reddit" };
838
862
}
839
if (value.entries && Array.isArray(value.entries)) {
840
return value;
863
if (!parsed.entries || !Array.isArray(parsed.entries) || !parsed.entries.length) {
864
return null;
841
865
}
866
const source = parsed.source || "reddit";
867
const fetchedAt = Number(parsed.fetchedAt || 0);
868
if (fetchedAt && Date.now() - fetchedAt > wikiCacheTtl(source)) {
869
return null;
870
}
871
return parsed;
842
872
} catch (err) {
843
873
return null;
844
874
}
845
return null;
846
875
}
847
876
848
877
function writeWikiCache(entries, source) {
849
878
try {
850
const expires = Date.now() + WIKI_CACHE_MS;
851
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: source || "reddit" }, expires);
879
const src = source || "arctic";
880
const expires = Date.now() + wikiCacheTtl(src);
881
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: src }, expires);
852
882
} catch (err) {
853
883
// cache is optioneel
854
884
}
@@ -1305,16 +1335,24 @@ async function fetchRedditJson(pathAndQuery) {
1305
1335
1306
1336
async function fetchRedditWikiMarkdown(wikiPath) {
1307
1337
const path = String(wikiPath || "").replace(/\/+$/, "");
1308
const result = await fetchRedditJson(path + ".json?raw_json=1");
1309
if (!result.ok) {
1310
return result;
1311
}
1312
const data = result.data && result.data.data ? result.data.data : result.data;
1313
const markdown = data && (data.content_md || data.content_html || data.content);
1314
if (!markdown || !String(markdown).trim()) {
1315
return { ok: false, reason: "lege wikipagina" };
1338
// Sommige Reddit-clients willen /wiki/series.json, andere /wiki/series/.json.
1339
const variants = [path + ".json?raw_json=1", path + "/.json?raw_json=1"];
1340
let last = { ok: false, reason: "lege wikipagina" };
1341
for (let i = 0; i < variants.length; i++) {
1342
const result = await fetchRedditJson(variants[i]);
1343
if (!result.ok) {
1344
last = result;
1345
continue;
1346
}
1347
const data = result.data && result.data.data ? result.data.data : result.data;
1348
const markdown = data && (data.content_md || data.content_html || data.content);
1349
if (!markdown || !String(markdown).trim()) {
1350
last = { ok: false, reason: "lege wikipagina" };
1351
continue;
1352
}
1353
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };
1316
1354
}
1317
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };
1355
return last;
1318
1356
}
1319
1357
1320
1358
async function fetchRedditSearch(term, page) {
@@ -1341,20 +1379,38 @@ async function fetchRedditListing(path, page) {
1341
1379
}
1342
1380
1343
1381
async function fetchRedditPostsByIds(ids) {
1344
const full = uniqueIds(ids).map((id) => "t3_" + id);
1382
const wanted = uniqueIds(ids);
1383
const full = wanted.map((id) => "t3_" + id);
1345
1384
const posts = [];
1385
let infoFailed = null;
1346
1386
for (let i = 0; i < full.length; i += 100) {
1347
1387
const chunk = full.slice(i, i + 100);
1348
1388
const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");
1349
1389
if (!result.ok) {
1350
1390
if (!posts.length) {
1351
return result;
1391
infoFailed = result;
1392
break;
1352
1393
}
1353
1394
break;
1354
1395
}
1355
1396
listingPosts(result.data).forEach((p) => posts.push(p));
1356
1397
}
1357
return { ok: true, posts: posts, source: "reddit" };
1398
if (posts.length) {
1399
return { ok: true, posts: posts, source: "reddit" };
1400
}
1401
// /api/info.json is een ander endpoint dan de hoofdstukken
1402
// (/comments/{id}/.json) en kan 403 geven terwijl die wel werken.
1403
const fromComments = [];
1404
for (let i = 0; i < wanted.length; i++) {
1405
const chapter = await tryRedditChapter(wanted[i]);
1406
if (chapter && chapter.ok && chapter.post) {
1407
fromComments.push(chapter.post);
1408
}
1409
}
1410
if (fromComments.length) {
1411
return { ok: true, posts: fromComments, source: "reddit" };
1412
}
1413
return infoFailed || { ok: false, reason: "geen posts" };
1358
1414
}
1359
1415
1360
1416
function listingPosts(payload) {
@@ -10,10 +10,11 @@10
* waarbij series en losse Part-1-posts tot één novel worden gegroepeerd10
* waarbij series en losse Part-1-posts tot één novel worden gegroepeerd11
* - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis11
* - parseNovel: wiki-inhoudsopgave, anders next-links met titelgelijkenis12
*12
*13
* Verhalen in de statische index houden hun vooraf gemaakte cover-URL.13
* Covers zijn drie vaste PNGs in .dist/covers/ (gewone https-URL, geen14
* Live gevonden verhalen zonder die PNG krijgen één vaste cover per bron:14
* data-URI, geen titelgeneratie op het toestel): r/HFY-logo in het midden15
* Reddit (r/HFY-logo) of Arctic Shift (site-logo), als gewone https-URL15
* en rechtsonder een bronbadge. De badge volgt de bron die de data16
* in .dist/covers/. Geen data-URI's en geen generatie op het toestel.16
* leverde: reddit.png, arctic-shift.png, of index.png (statische index).17
* Bij twijfel gebruiken we de Reddit-cover.17
*18
*18
* Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,19
* Bij een fout, 403 of login-/blokpagina valt alles terug op Arctic Shift,19
* en daarna op de statische metadata-index (ook bruikbaar zonder login).20
* en daarna op de statische metadata-index (ook bruikbaar zonder login).@@ -36,11 +37,15 @@ const DEFAULT_INDEX_BASE =36
const RAW_PLUGIN_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw";37
const RAW_PLUGIN_BASE = "https://git.timfalken.com/timfa/hfy-novels/-/raw";37
const LIVE_COVER_REDDIT = RAW_PLUGIN_BASE + "/.dist/covers/reddit.png?rev=master";38
const LIVE_COVER_REDDIT = RAW_PLUGIN_BASE + "/.dist/covers/reddit.png?rev=master";38
const LIVE_COVER_ARCTIC = RAW_PLUGIN_BASE + "/.dist/covers/arctic-shift.png?rev=master";39
const LIVE_COVER_ARCTIC = RAW_PLUGIN_BASE + "/.dist/covers/arctic-shift.png?rev=master";40
const LIVE_COVER_INDEX = RAW_PLUGIN_BASE + "/.dist/covers/index.png?rev=master";39
const DEFAULT_INDEX_REV = "master";41
const DEFAULT_INDEX_REV = "master";40
const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";42
const DEFAULT_CHAPTER_SOURCE = "https://arctic-shift.photon-reddit.com";41
const PAGE_FALLBACK_SIZE = 50;43
const PAGE_FALLBACK_SIZE = 50;42
const WIKI_CACHE_KEY = "wikiSeriesIndex";44
// v2: ongeldig verklaart caches uit 0.3.2/0.3.3 die een Arctic-fallback43
const WIKI_CACHE_MS = 6 * 60 * 60 * 1000;45
// zes uur vasthielden terwijl hoofdstukken intussen via Reddit werkten.46
const WIKI_CACHE_KEY = "wikiSeriesIndex.v2";47
const WIKI_CACHE_MS_REDDIT = 6 * 60 * 60 * 1000;48
const WIKI_CACHE_MS_ARCTIC = 5 * 60 * 1000;44
const REDDIT_WWW = "https://www.reddit.com";49
const REDDIT_WWW = "https://www.reddit.com";45
const REDDIT_OLD = "https://old.reddit.com";50
const REDDIT_OLD = "https://old.reddit.com";46
const WIKI_INDEX_PATH = "/r/HFY/wiki/series";51
const WIKI_INDEX_PATH = "/r/HFY/wiki/series";@@ -109,11 +114,21 @@ function toNovelItem(entry, plugin) {109
};114
};110
}115
}111
116
117
function coverSourceOf(postSource, wikiSource) {118
if (postSource === "reddit" || wikiSource === "reddit") {119
return "reddit";120
}121
if (postSource === "arctic" || wikiSource === "arctic") {122
return "arctic";123
}124
return "reddit";125
}126
112
class HFYNovelsPlugin {127
class HFYNovelsPlugin {113
constructor() {128
constructor() {114
this.id = "hfyNovels";129
this.id = "hfyNovels";115
this.name = "HFY Novels";130
this.name = "HFY Novels";116
this.version = "0.3.3";131
this.version = "0.3.4";117
this.site = "https://www.reddit.com/r/HFY/";132
this.site = "https://www.reddit.com/r/HFY/";118
this.icon = "icon.png";133
this.icon = "icon.png";119
// Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's134
// Geen webStorageUtilized: Reddit-login zit in cookies. LNReader's@@ -189,17 +204,16 @@ class HFYNovelsPlugin {189
}204
}190
205
191
coverFor(entry) {206
coverFor(entry) {192
if (entry && entry.cover) {207
// Per-titelcovers uit de statische index worden niet meer gebruikt.193
return this.coverUrl(entry.cover);194
}195
const source = entry && entry.source;208
const source = entry && entry.source;196
if (source === "arctic") {209
if (source === "arctic") {197
return LIVE_COVER_ARCTIC;210
return LIVE_COVER_ARCTIC;198
}211
}199
if (source === "reddit") {212
if (source === "index") {200
return LIVE_COVER_REDDIT;213
return LIVE_COVER_INDEX;201
}214
}202
return defaultCover;215
// reddit, of bij twijfel (ontbrekende/onbekende bron).216
return LIVE_COVER_REDDIT;203
}217
}204
218
205
coverUrl(cover) {219
coverUrl(cover) {@@ -381,9 +395,8 @@ class HFYNovelsPlugin {381
}395
}382
// Statische indexcovers overschrijven een live broncover, zodat een396
// Statische indexcovers overschrijven een live broncover, zodat een383
// bibliotheek-refresh een eerdere data-URI of logo kan vervangen.397
// bibliotheek-refresh een eerdere data-URI of logo kan vervangen.384
if (fallback.cover) {398
// Live data houdt de live-broncover (reddit/arctic). De indexcover385
novel.cover = fallback.cover;399
// geldt alleen als de reeks uitsluitend uit de statische index komt.386
}387
return finish(novel);400
return finish(novel);388
} catch (err) {401
} catch (err) {389
if (novel) {402
if (novel) {@@ -461,14 +474,14 @@ class HFYNovelsPlugin {461
}474
}462
const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);475
const payload = await readJson(this.indexUrl(spec.path), "cataloguspagina " + page);463
const novels = (payload.novels || []).filter((n) => !n.nsfw);476
const novels = (payload.novels || []).filter((n) => !n.nsfw);464
return novels.map((n) => toNovelItem(n, this));477
return novels.map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));465
}478
}466
479
467
const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");480
const search = await readJson(this.indexUrl("search-index.json"), "zoekindex");468
const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));481
const items = (search.novels || []).filter((n) => this.matchesFilters(n, filters));469
const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;482
const size = (await this.loadMeta()).pageSize || PAGE_FALLBACK_SIZE;470
const start = (page - 1) * size;483
const start = (page - 1) * size;471
return items.slice(start, start + size).map((n) => toNovelItem(n, this));484
return items.slice(start, start + size).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));472
}485
}473
486
474
async staticSearch(searchTerm, pageNo) {487
async staticSearch(searchTerm, pageNo) {@@ -484,7 +497,7 @@ class HFYNovelsPlugin {484
return name.includes(term) || author.includes(term);497
return name.includes(term) || author.includes(term);485
});498
});486
const start = (page - 1) * PAGE_FALLBACK_SIZE;499
const start = (page - 1) * PAGE_FALLBACK_SIZE;487
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(n, this));500
return hits.slice(start, start + PAGE_FALLBACK_SIZE).map((n) => toNovelItem(Object.assign({}, n, { source: "index" }), this));488
}501
}489
502
490
async staticParseNovel(novelPath) {503
async staticParseNovel(novelPath) {@@ -494,7 +507,7 @@ class HFYNovelsPlugin {494
name: data.name || "Untitled",507
name: data.name || "Untitled",495
author: data.author || "Anonymous",508
author: data.author || "Anonymous",496
artist: undefined,509
artist: undefined,497
cover: this.coverFor({ name: data.name, cover: data.cover }),510
cover: this.coverFor({ name: data.name, source: "index" }),498
genres: data.genres || "HFY",511
genres: data.genres || "HFY",499
status: statusFrom(data.status),512
status: statusFrom(data.status),500
summary: data.summary || "",513
summary: data.summary || "",@@ -626,7 +639,7 @@ class HFYNovelsPlugin {626
name: name,639
name: name,627
author: author,640
author: author,628
artist: undefined,641
artist: undefined,629
cover: this.coverFor({ name: name, cover: null, source: (fetched && fetched.source) || source }),642
cover: this.coverFor({ name: name, source: coverSourceOf(fetched && fetched.source, source) }),630
genres: nsfw ? "HFY, NSFW" : "HFY",643
genres: nsfw ? "HFY, NSFW" : "HFY",631
status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,644
status: oneshot ? NovelStatus.Completed : NovelStatus.Unknown,632
summary: author ? "HFY-serie van u/" + author + "." : "",645
summary: author ? "HFY-serie van u/" + author + "." : "",@@ -642,8 +655,11 @@ class HFYNovelsPlugin {642
655
643
async loadWikiIndex(mode) {656
async loadWikiIndex(mode) {644
const cached = readWikiCache();657
const cached = readWikiCache();645
if (cached && cached.entries && cached.entries.length) {658
const haveCached = cached && cached.entries && cached.entries.length;646
return { ok: true, entries: cached.entries, source: cached.source || "reddit" };659
// Alleen een Reddit-cache is lang geldig. Een Arctic-fallback cachen we660
// kort, en we proberen Reddit altijd opnieuw (bijv. na WebView-login).661
if (haveCached && cached.source === "reddit") {662
return { ok: true, entries: cached.entries, source: "reddit" };647
}663
}648
if (mode !== "arctic") {664
if (mode !== "arctic") {649
const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);665
const reddit = await fetchRedditWikiMarkdown(WIKI_INDEX_PATH);@@ -658,6 +674,9 @@ class HFYNovelsPlugin {658
return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };674
return { ok: false, reason: (reddit && reddit.reason) || "lege wiki-index" };659
}675
}660
}676
}677
if (haveCached) {678
return { ok: true, entries: cached.entries, source: cached.source || "arctic" };679
}661
const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);680
const arctic = await fetchArcticWikiPage(this.chapterSource(), WIKI_INDEX_PATH);662
if (arctic.ok) {681
if (arctic.ok) {663
const entries = parseSeriesIndex(arctic.markdown);682
const entries = parseSeriesIndex(arctic.markdown);@@ -827,28 +846,39 @@ function wikiEntryMatches(entry, term) {827
return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;846
return title.indexOf(q) !== -1 || author.indexOf(q) !== -1 || slug.indexOf(q) !== -1;828
}847
}829
848
849
function wikiCacheTtl(source) {850
return source === "reddit" ? WIKI_CACHE_MS_REDDIT : WIKI_CACHE_MS_ARCTIC;851
}852
830
function readWikiCache() {853
function readWikiCache() {831
try {854
try {832
const value = storage.get(WIKI_CACHE_KEY);855
const value = storage.get(WIKI_CACHE_KEY);833
if (!value) {856
if (!value) {834
return null;857
return null;835
}858
}859
let parsed = value;836
if (Array.isArray(value)) {860
if (Array.isArray(value)) {837
return { entries: value };861
parsed = { entries: value, source: "reddit" };838
}862
}839
if (value.entries && Array.isArray(value.entries)) {863
if (!parsed.entries || !Array.isArray(parsed.entries) || !parsed.entries.length) {840
return value;864
return null;841
}865
}866
const source = parsed.source || "reddit";867
const fetchedAt = Number(parsed.fetchedAt || 0);868
if (fetchedAt && Date.now() - fetchedAt > wikiCacheTtl(source)) {869
return null;870
}871
return parsed;842
} catch (err) {872
} catch (err) {843
return null;873
return null;844
}874
}845
return null;846
}875
}847
876
848
function writeWikiCache(entries, source) {877
function writeWikiCache(entries, source) {849
try {878
try {850
const expires = Date.now() + WIKI_CACHE_MS;879
const src = source || "arctic";851
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: source || "reddit" }, expires);880
const expires = Date.now() + wikiCacheTtl(src);881
storage.set(WIKI_CACHE_KEY, { fetchedAt: Date.now(), entries: entries, source: src }, expires);852
} catch (err) {882
} catch (err) {853
// cache is optioneel883
// cache is optioneel854
}884
}@@ -1305,16 +1335,24 @@ async function fetchRedditJson(pathAndQuery) {1305
1335
1306
async function fetchRedditWikiMarkdown(wikiPath) {1336
async function fetchRedditWikiMarkdown(wikiPath) {1307
const path = String(wikiPath || "").replace(/\/+$/, "");1337
const path = String(wikiPath || "").replace(/\/+$/, "");1308
const result = await fetchRedditJson(path + ".json?raw_json=1");1338
// Sommige Reddit-clients willen /wiki/series.json, andere /wiki/series/.json.1309
if (!result.ok) {1339
const variants = [path + ".json?raw_json=1", path + "/.json?raw_json=1"];1310
return result;1340
let last = { ok: false, reason: "lege wikipagina" };1311
}1341
for (let i = 0; i < variants.length; i++) {1312
const data = result.data && result.data.data ? result.data.data : result.data;1342
const result = await fetchRedditJson(variants[i]);1313
const markdown = data && (data.content_md || data.content_html || data.content);1343
if (!result.ok) {1314
if (!markdown || !String(markdown).trim()) {1344
last = result;1315
return { ok: false, reason: "lege wikipagina" };1345
continue;1346
}1347
const data = result.data && result.data.data ? result.data.data : result.data;1348
const markdown = data && (data.content_md || data.content_html || data.content);1349
if (!markdown || !String(markdown).trim()) {1350
last = { ok: false, reason: "lege wikipagina" };1351
continue;1352
}1353
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };1316
}1354
}1317
return { ok: true, markdown: String(data.content_md || markdown), source: "reddit" };1355
return last;1318
}1356
}1319
1357
1320
async function fetchRedditSearch(term, page) {1358
async function fetchRedditSearch(term, page) {@@ -1341,20 +1379,38 @@ async function fetchRedditListing(path, page) {1341
}1379
}1342
1380
1343
async function fetchRedditPostsByIds(ids) {1381
async function fetchRedditPostsByIds(ids) {1344
const full = uniqueIds(ids).map((id) => "t3_" + id);1382
const wanted = uniqueIds(ids);1383
const full = wanted.map((id) => "t3_" + id);1345
const posts = [];1384
const posts = [];1385
let infoFailed = null;1346
for (let i = 0; i < full.length; i += 100) {1386
for (let i = 0; i < full.length; i += 100) {1347
const chunk = full.slice(i, i + 100);1387
const chunk = full.slice(i, i + 100);1348
const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");1388
const result = await fetchRedditJson("/api/info.json?id=" + encodeURIComponent(chunk.join(",")) + "&raw_json=1");1349
if (!result.ok) {1389
if (!result.ok) {1350
if (!posts.length) {1390
if (!posts.length) {1351
return result;1391
infoFailed = result;1392
break;1352
}1393
}1353
break;1394
break;1354
}1395
}1355
listingPosts(result.data).forEach((p) => posts.push(p));1396
listingPosts(result.data).forEach((p) => posts.push(p));1356
}1397
}1357
return { ok: true, posts: posts, source: "reddit" };1398
if (posts.length) {1399
return { ok: true, posts: posts, source: "reddit" };1400
}1401
// /api/info.json is een ander endpoint dan de hoofdstukken1402
// (/comments/{id}/.json) en kan 403 geven terwijl die wel werken.1403
const fromComments = [];1404
for (let i = 0; i < wanted.length; i++) {1405
const chapter = await tryRedditChapter(wanted[i]);1406
if (chapter && chapter.ok && chapter.post) {1407
fromComments.push(chapter.post);1408
}1409
}1410
if (fromComments.length) {1411
return { ok: true, posts: fromComments, source: "reddit" };1412
}1413
return infoFailed || { ok: false, reason: "geen posts" };1358
}1414
}1359
1415
1360
function listingPosts(payload) {1416
function listingPosts(payload) {@@ -0,0 +1,126 @@
1
#!/usr/bin/env python3
2
"""Bouw de drie vaste HFY-Novels-covers (240×360 PNG).
3
4
Grote r/HFY-icoon in het midden, klein bron-badge rechtsonder.
5
Bronbestanden staan in scripts/cover-assets/; uitvoer in plugin/covers/.
6
7
python3 scripts/build-covers.py
8
"""
9
from __future__ import annotations
10
11
from pathlib import Path
12
13
from PIL import Image, ImageDraw, ImageFilter
14
15
ROOT = Path(__file__).resolve().parent.parent
16
ASSETS = Path(__file__).resolve().parent / "cover-assets"
17
OUT = ROOT / "plugin" / "covers"
18
19
WIDTH, HEIGHT = 240, 360
20
BACKGROUND = (10, 12, 16, 255)
21
HFY_SIZE = 176
22
BADGE_SIZE = 52
23
BADGE_MARGIN = 16
24
BADGE_PAD = 5
25
26
27
def fit(im: Image.Image, size: int) -> Image.Image:
28
im = im.convert("RGBA")
29
box = im.getbbox()
30
if box:
31
im = im.crop(box)
32
im.thumbnail((size, size), Image.Resampling.LANCZOS)
33
return im
34
35
36
def paste_center(canvas: Image.Image, logo: Image.Image, cy: int) -> None:
37
x = (WIDTH - logo.width) // 2
38
y = int(cy - logo.height / 2)
39
canvas.alpha_composite(logo, (x, y))
40
41
42
def rounded_rect(size: int, fill: tuple[int, int, int, int], radius: int) -> Image.Image:
43
im = Image.new("RGBA", (size, size), (0, 0, 0, 0))
44
draw = ImageDraw.Draw(im)
45
draw.rounded_rectangle((0, 0, size - 1, size - 1), radius=radius, fill=fill)
46
return im
47
48
49
def badge_on_plate(icon: Image.Image, plate: Image.Image) -> Image.Image:
50
"""Schaal het icoon in een afgerond plaatje, gecentreerd."""
51
inner = BADGE_SIZE - 2 * BADGE_PAD
52
fitted = fit(icon, inner)
53
x = (plate.width - fitted.width) // 2
54
y = (plate.height - fitted.height) // 2
55
plate.alpha_composite(fitted, (x, y))
56
return plate
57
58
59
def compose(badge: Image.Image) -> Image.Image:
60
canvas = Image.new("RGBA", (WIDTH, HEIGHT), BACKGROUND)
61
hfy = fit(Image.open(ASSETS / "hfy-icon.png"), HFY_SIZE)
62
paste_center(canvas, hfy, 150)
63
bx = WIDTH - BADGE_MARGIN - badge.width
64
by = HEIGHT - BADGE_MARGIN - badge.height
65
# lichte schaduw zodat het badge loskomt van de achtergrond
66
shadow = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
67
sh = Image.new("RGBA", (badge.width, badge.height), (0, 0, 0, 140))
68
shadow.paste(sh, (bx + 2, by + 2), sh)
69
shadow = shadow.filter(ImageFilter.GaussianBlur(2))
70
canvas.alpha_composite(shadow)
71
canvas.alpha_composite(badge, (bx, by))
72
return canvas
73
74
75
def save(canvas: Image.Image, dest: Path, colors: int = 128) -> None:
76
rgb = canvas.convert("RGB")
77
pal = rgb.quantize(colors=colors, method=Image.Quantize.MAXCOVERAGE, dither=Image.Dither.NONE)
78
dest.parent.mkdir(parents=True, exist_ok=True)
79
pal.save(dest, format="PNG", optimize=True, compress_level=9)
80
print(f" {dest.relative_to(ROOT)} {dest.stat().st_size} bytes")
81
82
83
def reddit_badge() -> Image.Image:
84
# Het officiële icoon is al een ronde oranje badge.
85
return fit(Image.open(ASSETS / "reddit-badge.png"), BADGE_SIZE)
86
87
88
def arctic_badge() -> Image.Image:
89
plate = rounded_rect(BADGE_SIZE, (20, 40, 62, 255), radius=12)
90
# dunne rand
91
draw = ImageDraw.Draw(plate)
92
draw.rounded_rectangle((0, 0, BADGE_SIZE - 1, BADGE_SIZE - 1), radius=12, outline=(140, 200, 230, 220), width=2)
93
icon = Image.open(ASSETS / "arctic-shift-badge.png")
94
return badge_on_plate(icon, plate)
95
96
97
def index_badge() -> Image.Image:
98
# Zwart plaatje met witte rand, zodat de T zichtbaar blijft op de donkere cover.
99
plate = rounded_rect(BADGE_SIZE, (0, 0, 0, 255), radius=10)
100
draw = ImageDraw.Draw(plate)
101
draw.rounded_rectangle((0, 0, BADGE_SIZE - 1, BADGE_SIZE - 1), radius=10, outline=(230, 230, 230, 255), width=2)
102
icon = Image.open(ASSETS / "projects-badge.png").convert("RGBA")
103
# Pixel-T: integer-scale om scherp te blijven.
104
box = icon.getbbox() or icon.getbbox()
105
if box:
106
icon = icon.crop(box)
107
inner = BADGE_SIZE - 2 * BADGE_PAD - 2
108
scale = max(1, min(inner // icon.width, inner // icon.height))
109
icon = icon.resize((icon.width * scale, icon.height * scale), Image.Resampling.NEAREST)
110
x = (plate.width - icon.width) // 2
111
y = (plate.height - icon.height) // 2
112
plate.alpha_composite(icon, (x, y))
113
return plate
114
115
116
def main() -> None:
117
OUT.mkdir(parents=True, exist_ok=True)
118
print("covers:")
119
# Reddit-badge heeft meer oranje tinten; geef die cover iets meer kleuren.
120
save(compose(reddit_badge()), OUT / "reddit.png", colors=128)
121
save(compose(arctic_badge()), OUT / "arctic-shift.png", colors=64)
122
save(compose(index_badge()), OUT / "index.png", colors=64)
123
124
125
if __name__ == "__main__":
126
main()
@@ -0,0 +1,126 @@1
#!/usr/bin/env python32
"""Bouw de drie vaste HFY-Novels-covers (240×360 PNG).3
4
Grote r/HFY-icoon in het midden, klein bron-badge rechtsonder.5
Bronbestanden staan in scripts/cover-assets/; uitvoer in plugin/covers/.6
7
python3 scripts/build-covers.py8
"""9
from __future__ import annotations10
11
from pathlib import Path12
13
from PIL import Image, ImageDraw, ImageFilter14
15
ROOT = Path(__file__).resolve().parent.parent16
ASSETS = Path(__file__).resolve().parent / "cover-assets"17
OUT = ROOT / "plugin" / "covers"18
19
WIDTH, HEIGHT = 240, 36020
BACKGROUND = (10, 12, 16, 255)21
HFY_SIZE = 17622
BADGE_SIZE = 5223
BADGE_MARGIN = 1624
BADGE_PAD = 525
26
27
def fit(im: Image.Image, size: int) -> Image.Image:28
im = im.convert("RGBA")29
box = im.getbbox()30
if box:31
im = im.crop(box)32
im.thumbnail((size, size), Image.Resampling.LANCZOS)33
return im34
35
36
def paste_center(canvas: Image.Image, logo: Image.Image, cy: int) -> None:37
x = (WIDTH - logo.width) // 238
y = int(cy - logo.height / 2)39
canvas.alpha_composite(logo, (x, y))40
41
42
def rounded_rect(size: int, fill: tuple[int, int, int, int], radius: int) -> Image.Image:43
im = Image.new("RGBA", (size, size), (0, 0, 0, 0))44
draw = ImageDraw.Draw(im)45
draw.rounded_rectangle((0, 0, size - 1, size - 1), radius=radius, fill=fill)46
return im47
48
49
def badge_on_plate(icon: Image.Image, plate: Image.Image) -> Image.Image:50
"""Schaal het icoon in een afgerond plaatje, gecentreerd."""51
inner = BADGE_SIZE - 2 * BADGE_PAD52
fitted = fit(icon, inner)53
x = (plate.width - fitted.width) // 254
y = (plate.height - fitted.height) // 255
plate.alpha_composite(fitted, (x, y))56
return plate57
58
59
def compose(badge: Image.Image) -> Image.Image:60
canvas = Image.new("RGBA", (WIDTH, HEIGHT), BACKGROUND)61
hfy = fit(Image.open(ASSETS / "hfy-icon.png"), HFY_SIZE)62
paste_center(canvas, hfy, 150)63
bx = WIDTH - BADGE_MARGIN - badge.width64
by = HEIGHT - BADGE_MARGIN - badge.height65
# lichte schaduw zodat het badge loskomt van de achtergrond66
shadow = Image.new("RGBA", canvas.size, (0, 0, 0, 0))67
sh = Image.new("RGBA", (badge.width, badge.height), (0, 0, 0, 140))68
shadow.paste(sh, (bx + 2, by + 2), sh)69
shadow = shadow.filter(ImageFilter.GaussianBlur(2))70
canvas.alpha_composite(shadow)71
canvas.alpha_composite(badge, (bx, by))72
return canvas73
74
75
def save(canvas: Image.Image, dest: Path, colors: int = 128) -> None:76
rgb = canvas.convert("RGB")77
pal = rgb.quantize(colors=colors, method=Image.Quantize.MAXCOVERAGE, dither=Image.Dither.NONE)78
dest.parent.mkdir(parents=True, exist_ok=True)79
pal.save(dest, format="PNG", optimize=True, compress_level=9)80
print(f" {dest.relative_to(ROOT)} {dest.stat().st_size} bytes")81
82
83
def reddit_badge() -> Image.Image:84
# Het officiële icoon is al een ronde oranje badge.85
return fit(Image.open(ASSETS / "reddit-badge.png"), BADGE_SIZE)86
87
88
def arctic_badge() -> Image.Image:89
plate = rounded_rect(BADGE_SIZE, (20, 40, 62, 255), radius=12)90
# dunne rand91
draw = ImageDraw.Draw(plate)92
draw.rounded_rectangle((0, 0, BADGE_SIZE - 1, BADGE_SIZE - 1), radius=12, outline=(140, 200, 230, 220), width=2)93
icon = Image.open(ASSETS / "arctic-shift-badge.png")94
return badge_on_plate(icon, plate)95
96
97
def index_badge() -> Image.Image:98
# Zwart plaatje met witte rand, zodat de T zichtbaar blijft op de donkere cover.99
plate = rounded_rect(BADGE_SIZE, (0, 0, 0, 255), radius=10)100
draw = ImageDraw.Draw(plate)101
draw.rounded_rectangle((0, 0, BADGE_SIZE - 1, BADGE_SIZE - 1), radius=10, outline=(230, 230, 230, 255), width=2)102
icon = Image.open(ASSETS / "projects-badge.png").convert("RGBA")103
# Pixel-T: integer-scale om scherp te blijven.104
box = icon.getbbox() or icon.getbbox()105
if box:106
icon = icon.crop(box)107
inner = BADGE_SIZE - 2 * BADGE_PAD - 2108
scale = max(1, min(inner // icon.width, inner // icon.height))109
icon = icon.resize((icon.width * scale, icon.height * scale), Image.Resampling.NEAREST)110
x = (plate.width - icon.width) // 2111
y = (plate.height - icon.height) // 2112
plate.alpha_composite(icon, (x, y))113
return plate114
115
116
def main() -> None:117
OUT.mkdir(parents=True, exist_ok=True)118
print("covers:")119
# Reddit-badge heeft meer oranje tinten; geef die cover iets meer kleuren.120
save(compose(reddit_badge()), OUT / "reddit.png", colors=128)121
save(compose(arctic_badge()), OUT / "arctic-shift.png", colors=64)122
save(compose(index_badge()), OUT / "index.png", colors=64)123
124
125
if __name__ == "__main__":126
main()@@ -28,7 +28,7 @@ if (fs.existsSync(iconSrc)) {
28
28
const coversSrcDir = path.join(ROOT, "plugin", "covers");
29
29
const coversDestDir = path.join(distDir, "covers");
30
30
fs.mkdirSync(coversDestDir, { recursive: true });
31
for (const name of ["reddit.png", "arctic-shift.png"]) {
31
for (const name of ["reddit.png", "arctic-shift.png", "index.png"]) {
32
32
const src = path.join(coversSrcDir, name);
33
33
if (!fs.existsSync(src)) {
34
34
throw new Error("ontbrekende broncover: " + name);
@@ -28,7 +28,7 @@ if (fs.existsSync(iconSrc)) {28
const coversSrcDir = path.join(ROOT, "plugin", "covers");28
const coversSrcDir = path.join(ROOT, "plugin", "covers");29
const coversDestDir = path.join(distDir, "covers");29
const coversDestDir = path.join(distDir, "covers");30
fs.mkdirSync(coversDestDir, { recursive: true });30
fs.mkdirSync(coversDestDir, { recursive: true });31
for (const name of ["reddit.png", "arctic-shift.png"]) {31
for (const name of ["reddit.png", "arctic-shift.png", "index.png"]) {32
const src = path.join(coversSrcDir, name);32
const src = path.join(coversSrcDir, name);33
if (!fs.existsSync(src)) {33
if (!fs.existsSync(src)) {34
throw new Error("ontbrekende broncover: " + name);34
throw new Error("ontbrekende broncover: " + name);@@ -0,0 +1,17 @@
1
Bronbestanden voor de drie vaste LNReader-covers (scripts/build-covers.py).
2
3
hfy-icon.png
4
r/HFY-community-icoon (handen rond de aarde).
5
https://styles.redditmedia.com/t5_2y95n/styles/communityIcon_or09gmyen4l21.png?width=256
6
7
reddit-badge.png
8
Officieel Reddit-app-icoon (snoo).
9
https://www.redditstatic.com/desktop2x/img/favicon/android-icon-192x192.png
10
11
arctic-shift-badge.png
12
Favicon van Arctic Shift.
13
https://arctic-shift.photon-reddit.com/favicon.png
14
15
projects-badge.png
16
Favicon van projects.timfalken.com (de T).
17
https://projects.timfalken.com/favicon.png
@@ -0,0 +1,17 @@1
Bronbestanden voor de drie vaste LNReader-covers (scripts/build-covers.py).2
3
hfy-icon.png4
r/HFY-community-icoon (handen rond de aarde).5
https://styles.redditmedia.com/t5_2y95n/styles/communityIcon_or09gmyen4l21.png?width=2566
7
reddit-badge.png8
Officieel Reddit-app-icoon (snoo).9
https://www.redditstatic.com/desktop2x/img/favicon/android-icon-192x192.png10
11
arctic-shift-badge.png12
Favicon van Arctic Shift.13
https://arctic-shift.photon-reddit.com/favicon.png14
15
projects-badge.png16
Favicon van projects.timfalken.com (de T).17
https://projects.timfalken.com/favicon.pngThe contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -22,6 +22,8 @@ const LIVE_COVER_REDDIT =
22
22
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/reddit.png?rev=master";
23
23
const LIVE_COVER_ARCTIC =
24
24
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/arctic-shift.png?rev=master";
25
const LIVE_COVER_INDEX =
26
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/index.png?rev=master";
25
27
26
28
const NovelStatus = {
27
29
Completed: "Completed",
@@ -480,10 +482,9 @@ async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {
480
482
assert(novel.chapters[2].path === "chapter/aaa333", "laatste TOC-hoofdstuk");
481
483
assertLiveCover(novel.cover, "reddit", "parseNovel live-cover (wiki, geen statische PNG)");
482
484
const indexed = await plugin.parseNovel("series/aaa111");
483
assert(indexed.cover && indexed.cover.indexOf("/covers/") !== -1, "parseNovel van een indexreeks houdt de statische cover");
484
assert(indexed.cover.indexOf("data:") === -1, "indexcover is geen data-URI");
485
assertLiveCover(indexed.cover, "reddit", "parseNovel van een indexreeks gebruikt Reddit-cover als live Reddit slaagt");
485
486
486
delete storageMap.wikiSeriesIndex;
487
clearWikiCache(storageMap);
487
488
state.redditMode = "403";
488
489
state.arcticMode = "ok";
489
490
state.arcticWikiHits = 0;
@@ -504,14 +505,14 @@ async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {
504
505
const novel403 = await plugin403.parseNovel("wiki/the_last_terran");
505
506
assertLiveCover(novel403.cover, "arctic", "parseNovel 403-cover");
506
507
507
delete storageMap.wikiSeriesIndex;
508
clearWikiCache(storageMap);
508
509
state.redditMode = "403";
509
510
state.arcticMode = "fail";
510
511
const pluginStatic = loadPlugin(storageMap, liveFetch);
511
512
const popularStatic = await pluginStatic.popularNovels(1, { filters: {} });
512
513
assert(popularStatic.some((n) => n.path === "series/aaa111"), "na Reddit+Arctic Shift volgt de statische index");
513
514
const staticItem = popularStatic.find((n) => n.path === "series/aaa111");
514
assert(staticItem.cover && staticItem.cover.indexOf("/covers/") !== -1, "statische catalogus houdt eigen covers");
515
assertLiveCover(staticItem.cover, "index", "statische catalogus na live-fout gebruikt index.png");
515
516
const searchStatic = await pluginStatic.searchNovels("terran", 1);
516
517
assert(searchStatic.length === 1 && searchStatic[0].path === "series/aaa111", "zoeken valt terug op de statische index");
517
518
@@ -523,8 +524,16 @@ async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {
523
524
524
525
525
526
527
function clearWikiCache(storageMap) {
528
delete storageMap.wikiSeriesIndex;
529
delete storageMap["wikiSeriesIndex.v2"];
530
delete storageMap.wikiSeriesIndex__expires;
531
delete storageMap["wikiSeriesIndex.v2__expires"];
532
}
533
526
534
function assertLiveCover(uri, source, label) {
527
const expected = source === "arctic" ? LIVE_COVER_ARCTIC : LIVE_COVER_REDDIT;
535
const expected =
536
source === "arctic" ? LIVE_COVER_ARCTIC : source === "index" ? LIVE_COVER_INDEX : LIVE_COVER_REDDIT;
528
537
assert(typeof uri === "string" && uri === expected, label + " is de vaste " + source + "-cover-URL");
529
538
assert(/^https:\/\//.test(uri), label + " is een https-URL");
530
539
assert(uri.indexOf("data:") === -1, label + " is geen data-URI");
@@ -541,7 +550,7 @@ function assertPngFile(file, label) {
541
550
}
542
551
543
552
function testLiveCoverFiles() {
544
for (const name of ["reddit.png", "arctic-shift.png"]) {
553
for (const name of ["reddit.png", "arctic-shift.png", "index.png"]) {
545
554
const src = path.join(ROOT, "plugin", "covers", name);
546
555
const dist = path.join(ROOT, ".dist", "covers", name);
547
556
assert(fs.existsSync(src), name + " staat in plugin/covers");
@@ -550,11 +559,131 @@ function testLiveCoverFiles() {
550
559
assertPngFile(dist, "dist " + name);
551
560
assert(Buffer.compare(fs.readFileSync(src), fs.readFileSync(dist)) === 0, name + " is gelijk gekopieerd");
552
561
}
553
console.log("✔️ vaste broncovers: reddit.png en arctic-shift.png (240x360, klein PNG)");
562
console.log("✔️ vaste broncovers: reddit.png, arctic-shift.png en index.png (240x360, klein PNG)");
554
563
}
555
564
556
565
557
566
567
568
async function testCoverSourceAfterLoginAndCommentsFallback(origin, fixtureRoot, assert) {
569
// 1) Wiki via Arctic cachen, daarna Reddit weer beschikbaar: geen 6-uur-wacht.
570
// 2) /api/info.json 403, /comments/{id}/.json 200: parseNovel moet Reddit-cover geven.
571
const wikiIndex = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "index.md"), "utf8");
572
const wikiTerran = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "pages", "the_last_terran.md"), "utf8");
573
const state = { redditMode: "403", blockInfo: false, wikiHits: 0, infoHits: 0, commentHits: 0, arcticWikiHits: 0 };
574
575
function redditHandler(url, res) {
576
const isInfo = url.pathname.startsWith("/api/info");
577
const isComments = /\/comments\/[0-9a-z]+\//i.test(url.pathname);
578
const isWiki = /\/wiki\//i.test(url.pathname);
579
if (state.redditMode === "403" || (state.blockInfo && (isInfo || isWiki) && !isComments)) {
580
if (isComments && state.redditMode !== "403") {
581
// comments blijven doorgaan in blockInfo-modus
582
} else {
583
if (isWiki) state.wikiHits += 1;
584
if (isInfo) state.infoHits += 1;
585
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
586
res.end(blockHtml());
587
return;
588
}
589
}
590
if (isWiki) {
591
state.wikiHits += 1;
592
const md = /the_last_terran/.test(url.pathname) ? wikiTerran : wikiIndex;
593
res.writeHead(200, { "Content-Type": "application/json" });
594
res.end(JSON.stringify(wikiIndexPayload(md)));
595
return;
596
}
597
if (isInfo) {
598
state.infoHits += 1;
599
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
600
res.end(blockHtml());
601
return;
602
}
603
if (isComments) {
604
state.commentHits += 1;
605
const m = url.pathname.match(/\/comments\/([0-9a-z]+)\//i);
606
const id = m ? m[1].toLowerCase() : "aaa111";
607
res.writeHead(200, { "Content-Type": "application/json" });
608
res.end(JSON.stringify(redditListingFor(id)));
609
return;
610
}
611
res.writeHead(404, { "Content-Type": "text/plain" });
612
res.end("no mock for " + url.pathname);
613
}
614
615
function arcticHandler(url, res) {
616
if (url.pathname.startsWith("/api/subreddits/wikis")) {
617
state.arcticWikiHits += 1;
618
const paths = url.searchParams.get("paths") || "";
619
const content = /the_last_terran/.test(paths) ? wikiTerran : wikiIndex;
620
res.writeHead(200, { "Content-Type": "application/json" });
621
res.end(JSON.stringify({ data: [{ path: paths, content }] }));
622
return;
623
}
624
if (url.pathname.startsWith("/api/posts/ids")) {
625
res.writeHead(200, { "Content-Type": "application/json" });
626
res.end(JSON.stringify({ data: [samplePost("aaa111", "[OC] The Last Terran - Part 1", "WriterOne")] }));
627
return;
628
}
629
res.writeHead(404);
630
res.end("no arctic mock");
631
}
632
633
const started = await startServer(fixtureRoot, arcticHandler, redditHandler);
634
const fetchApi = makeFetchApi(started.url);
635
try {
636
const storageMap = {
637
indexBaseUrl: origin,
638
indexRev: "",
639
chapterSourceUrl: started.url,
640
chapterSource: "auto",
641
};
642
const plugin = loadPlugin(storageMap, fetchApi);
643
644
const popularArctic = await plugin.popularNovels(1, { filters: {} });
645
assertLiveCover(
646
popularArctic.find((n) => n.name === "The Last Terran").cover,
647
"arctic",
648
"eerst Arctic-wiki-cover",
649
);
650
assert(state.arcticWikiHits >= 1, "Arctic-wiki is gebruikt");
651
const hitsBeforeRetry = state.wikiHits;
652
653
state.redditMode = "ok";
654
const popularRetry = await plugin.popularNovels(1, { filters: {} });
655
assert(state.wikiHits > hitsBeforeRetry, "Arctic-cache triggert een nieuwe Reddit-poging (geen 6 uur wachten)");
656
assertLiveCover(
657
popularRetry.find((n) => n.name === "The Last Terran").cover,
658
"reddit",
659
"na inloggen Reddit-cover op de wiki-lijst",
660
);
661
662
// Nieuwe plugin, geen cache: wiki 403, api/info 403, comments 200.
663
clearWikiCache(storageMap);
664
state.redditMode = "ok";
665
state.blockInfo = true;
666
state.infoHits = 0;
667
state.commentHits = 0;
668
const pluginComments = loadPlugin(storageMap, fetchApi);
669
const novel = await pluginComments.parseNovel("series/aaa111");
670
assert(state.commentHits >= 1, "parseNovel valt terug op comments/.json");
671
assertLiveCover(novel.cover, "reddit", "comments-fallback geeft Reddit-cover, niet Arctic");
672
// Hoofdstuk uit Reddit: dezelfde cookies/endpoint.
673
const html = await pluginComments.parseChapter("chapter/aaa111");
674
assert(/Bron: Reddit/.test(html), "parseChapter toont Bron: Reddit");
675
676
// Zonder bron → Reddit-cover (bij twijfel).
677
assertLiveCover(plugin.coverFor({ name: "X" }), "reddit", "ontbrekende bron prefereert Reddit");
678
assertLiveCover(plugin.coverFor({ name: "X", source: "index" }), "index", "index-bron");
679
assertLiveCover(plugin.coverFor({ name: "X", source: "arctic" }), "arctic", "arctic-bron");
680
681
console.log("✔️ covers: bron volgt Reddit na login, comments-fallback, index/reddit/arctic");
682
} finally {
683
started.server.close();
684
}
685
}
686
558
687
async function testParseNovelWhenLiveFails(origin, fixtureRoot, assert) {
559
688
// Reddit 403 + Arctic Shift 502 zonder posts-array: dit is de fout uit 0.3.2
560
689
// ("unable to load novel" overal, ook voor verhalen in de statische index).
@@ -585,8 +714,7 @@ async function testParseNovelWhenLiveFails(origin, fixtureRoot, assert) {
585
714
assert(novel.path === "series/aaa111", "parseNovel houdt het aangevraagde pad");
586
715
assert(novel.name === "The Last Terran", "parseNovel valt terug op de statische index");
587
716
assert(novel.chapters && novel.chapters.length === 3, "statische hoofdstuklijst blijft beschikbaar");
588
assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "indexcover bij live-fout");
589
assert(String(novel.cover).indexOf("data:") === -1, "geen data-URI bij fallback");
717
assertLiveCover(novel.cover, "index", "indexcover bij live-fout");
590
718
591
719
let wikiError = "";
592
720
try {
@@ -628,7 +756,7 @@ async function main() {
628
756
629
757
assert(plugin.id === "hfyNovels", "id");
630
758
assert(plugin.name === "HFY Novels", "name");
631
assert(plugin.version === "0.3.3", "version");
759
assert(plugin.version === "0.3.4", "version");
632
760
assert(plugin.site === "https://www.reddit.com/r/HFY/", "site");
633
761
assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings");
634
762
assert(plugin.filters && plugin.filters.catalog, "filter Nieuw/wiki");
@@ -643,23 +771,8 @@ async function main() {
643
771
const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });
644
772
assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items");
645
773
assert(popular[0].name && popular[0].path, "NovelItem heeft name+path");
646
assert(popular[0].cover && popular[0].cover.indexOf("/covers/") !== -1, "cover-URL wijst naar covers/");
647
const coverIsSvg = /\.svg(\?|$)/i.test(popular[0].cover);
648
if (coverIsSvg) {
649
assert(popular[0].cover.indexOf("as=img") !== -1, "SVG-cover heeft as=img");
650
}
651
const coverRes = await fetch(popular[0].cover);
652
assert(coverRes.ok, "cover is ophaalbaar");
653
const coverBuf = Buffer.from(await coverRes.arrayBuffer());
654
if (coverIsSvg) {
655
const coverBody = coverBuf.toString("utf8");
656
assert(coverBody.indexOf("<svg") === 0, "cover is een SVG");
657
assert(coverBody.indexOf(popular[0].name) !== -1, "cover toont de titel");
658
} else {
659
assert(coverBuf[0] === 0x89 && coverBuf.toString("ascii", 1, 4) === "PNG", "cover is een PNG");
660
}
661
const coverAgain = Buffer.from(await (await fetch(popular[0].cover)).arrayBuffer());
662
assert(Buffer.compare(coverBuf, coverAgain) === 0, "dezelfde titel geeft dezelfde cover");
774
assertLiveCover(popular[0].cover, "index", "statische cataloguscover");
775
assert(popular.every((n) => n.cover === LIVE_COVER_INDEX), "alle index-items delen index.png");
663
776
assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus");
664
777
665
778
const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });
@@ -684,7 +797,7 @@ async function main() {
684
797
const novel = await plugin.parseNovel("series/aaa111");
685
798
assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input");
686
799
assert(novel.author === "WriterOne", "auteur");
687
assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "parseNovel heeft een cover-URL");
800
assertLiveCover(novel.cover, "reddit", "parseNovel gebruikt Reddit-cover via comments/.json");
688
801
assert(novel.chapters.length === 3, "3 hoofdstukken");
689
802
assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad");
690
803
assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer");
@@ -751,6 +864,7 @@ async function main() {
751
864
// --- Live catalogus: wiki, zoeken, parseNovel, met fallbacks ---
752
865
await testLiveCatalog(url, fixtureRoot, fetchApi, assert);
753
866
await testParseNovelWhenLiveFails(url, fixtureRoot, assert);
867
await testCoverSourceAfterLoginAndCommentsFallback(url, fixtureRoot, assert);
754
868
755
869
756
870
// Manifest-vorm controleren.
@@ -22,6 +22,8 @@ const LIVE_COVER_REDDIT =22
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/reddit.png?rev=master";22
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/reddit.png?rev=master";23
const LIVE_COVER_ARCTIC =23
const LIVE_COVER_ARCTIC =24
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/arctic-shift.png?rev=master";24
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/arctic-shift.png?rev=master";25
const LIVE_COVER_INDEX =26
"https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/index.png?rev=master";25
27
26
const NovelStatus = {28
const NovelStatus = {27
Completed: "Completed",29
Completed: "Completed",@@ -480,10 +482,9 @@ async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {480
assert(novel.chapters[2].path === "chapter/aaa333", "laatste TOC-hoofdstuk");482
assert(novel.chapters[2].path === "chapter/aaa333", "laatste TOC-hoofdstuk");481
assertLiveCover(novel.cover, "reddit", "parseNovel live-cover (wiki, geen statische PNG)");483
assertLiveCover(novel.cover, "reddit", "parseNovel live-cover (wiki, geen statische PNG)");482
const indexed = await plugin.parseNovel("series/aaa111");484
const indexed = await plugin.parseNovel("series/aaa111");483
assert(indexed.cover && indexed.cover.indexOf("/covers/") !== -1, "parseNovel van een indexreeks houdt de statische cover");485
assertLiveCover(indexed.cover, "reddit", "parseNovel van een indexreeks gebruikt Reddit-cover als live Reddit slaagt");484
assert(indexed.cover.indexOf("data:") === -1, "indexcover is geen data-URI");485
486
486
delete storageMap.wikiSeriesIndex;487
clearWikiCache(storageMap);487
state.redditMode = "403";488
state.redditMode = "403";488
state.arcticMode = "ok";489
state.arcticMode = "ok";489
state.arcticWikiHits = 0;490
state.arcticWikiHits = 0;@@ -504,14 +505,14 @@ async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {504
const novel403 = await plugin403.parseNovel("wiki/the_last_terran");505
const novel403 = await plugin403.parseNovel("wiki/the_last_terran");505
assertLiveCover(novel403.cover, "arctic", "parseNovel 403-cover");506
assertLiveCover(novel403.cover, "arctic", "parseNovel 403-cover");506
507
507
delete storageMap.wikiSeriesIndex;508
clearWikiCache(storageMap);508
state.redditMode = "403";509
state.redditMode = "403";509
state.arcticMode = "fail";510
state.arcticMode = "fail";510
const pluginStatic = loadPlugin(storageMap, liveFetch);511
const pluginStatic = loadPlugin(storageMap, liveFetch);511
const popularStatic = await pluginStatic.popularNovels(1, { filters: {} });512
const popularStatic = await pluginStatic.popularNovels(1, { filters: {} });512
assert(popularStatic.some((n) => n.path === "series/aaa111"), "na Reddit+Arctic Shift volgt de statische index");513
assert(popularStatic.some((n) => n.path === "series/aaa111"), "na Reddit+Arctic Shift volgt de statische index");513
const staticItem = popularStatic.find((n) => n.path === "series/aaa111");514
const staticItem = popularStatic.find((n) => n.path === "series/aaa111");514
assert(staticItem.cover && staticItem.cover.indexOf("/covers/") !== -1, "statische catalogus houdt eigen covers");515
assertLiveCover(staticItem.cover, "index", "statische catalogus na live-fout gebruikt index.png");515
const searchStatic = await pluginStatic.searchNovels("terran", 1);516
const searchStatic = await pluginStatic.searchNovels("terran", 1);516
assert(searchStatic.length === 1 && searchStatic[0].path === "series/aaa111", "zoeken valt terug op de statische index");517
assert(searchStatic.length === 1 && searchStatic[0].path === "series/aaa111", "zoeken valt terug op de statische index");517
518
@@ -523,8 +524,16 @@ async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {523
524
524
525
525
526
527
function clearWikiCache(storageMap) {528
delete storageMap.wikiSeriesIndex;529
delete storageMap["wikiSeriesIndex.v2"];530
delete storageMap.wikiSeriesIndex__expires;531
delete storageMap["wikiSeriesIndex.v2__expires"];532
}533
526
function assertLiveCover(uri, source, label) {534
function assertLiveCover(uri, source, label) {527
const expected = source === "arctic" ? LIVE_COVER_ARCTIC : LIVE_COVER_REDDIT;535
const expected =536
source === "arctic" ? LIVE_COVER_ARCTIC : source === "index" ? LIVE_COVER_INDEX : LIVE_COVER_REDDIT;528
assert(typeof uri === "string" && uri === expected, label + " is de vaste " + source + "-cover-URL");537
assert(typeof uri === "string" && uri === expected, label + " is de vaste " + source + "-cover-URL");529
assert(/^https:\/\//.test(uri), label + " is een https-URL");538
assert(/^https:\/\//.test(uri), label + " is een https-URL");530
assert(uri.indexOf("data:") === -1, label + " is geen data-URI");539
assert(uri.indexOf("data:") === -1, label + " is geen data-URI");@@ -541,7 +550,7 @@ function assertPngFile(file, label) {541
}550
}542
551
543
function testLiveCoverFiles() {552
function testLiveCoverFiles() {544
for (const name of ["reddit.png", "arctic-shift.png"]) {553
for (const name of ["reddit.png", "arctic-shift.png", "index.png"]) {545
const src = path.join(ROOT, "plugin", "covers", name);554
const src = path.join(ROOT, "plugin", "covers", name);546
const dist = path.join(ROOT, ".dist", "covers", name);555
const dist = path.join(ROOT, ".dist", "covers", name);547
assert(fs.existsSync(src), name + " staat in plugin/covers");556
assert(fs.existsSync(src), name + " staat in plugin/covers");@@ -550,11 +559,131 @@ function testLiveCoverFiles() {550
assertPngFile(dist, "dist " + name);559
assertPngFile(dist, "dist " + name);551
assert(Buffer.compare(fs.readFileSync(src), fs.readFileSync(dist)) === 0, name + " is gelijk gekopieerd");560
assert(Buffer.compare(fs.readFileSync(src), fs.readFileSync(dist)) === 0, name + " is gelijk gekopieerd");552
}561
}553
console.log("✔️ vaste broncovers: reddit.png en arctic-shift.png (240x360, klein PNG)");562
console.log("✔️ vaste broncovers: reddit.png, arctic-shift.png en index.png (240x360, klein PNG)");554
}563
}555
564
556
565
557
566
567
568
async function testCoverSourceAfterLoginAndCommentsFallback(origin, fixtureRoot, assert) {569
// 1) Wiki via Arctic cachen, daarna Reddit weer beschikbaar: geen 6-uur-wacht.570
// 2) /api/info.json 403, /comments/{id}/.json 200: parseNovel moet Reddit-cover geven.571
const wikiIndex = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "index.md"), "utf8");572
const wikiTerran = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "pages", "the_last_terran.md"), "utf8");573
const state = { redditMode: "403", blockInfo: false, wikiHits: 0, infoHits: 0, commentHits: 0, arcticWikiHits: 0 };574
575
function redditHandler(url, res) {576
const isInfo = url.pathname.startsWith("/api/info");577
const isComments = /\/comments\/[0-9a-z]+\//i.test(url.pathname);578
const isWiki = /\/wiki\//i.test(url.pathname);579
if (state.redditMode === "403" || (state.blockInfo && (isInfo || isWiki) && !isComments)) {580
if (isComments && state.redditMode !== "403") {581
// comments blijven doorgaan in blockInfo-modus582
} else {583
if (isWiki) state.wikiHits += 1;584
if (isInfo) state.infoHits += 1;585
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });586
res.end(blockHtml());587
return;588
}589
}590
if (isWiki) {591
state.wikiHits += 1;592
const md = /the_last_terran/.test(url.pathname) ? wikiTerran : wikiIndex;593
res.writeHead(200, { "Content-Type": "application/json" });594
res.end(JSON.stringify(wikiIndexPayload(md)));595
return;596
}597
if (isInfo) {598
state.infoHits += 1;599
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });600
res.end(blockHtml());601
return;602
}603
if (isComments) {604
state.commentHits += 1;605
const m = url.pathname.match(/\/comments\/([0-9a-z]+)\//i);606
const id = m ? m[1].toLowerCase() : "aaa111";607
res.writeHead(200, { "Content-Type": "application/json" });608
res.end(JSON.stringify(redditListingFor(id)));609
return;610
}611
res.writeHead(404, { "Content-Type": "text/plain" });612
res.end("no mock for " + url.pathname);613
}614
615
function arcticHandler(url, res) {616
if (url.pathname.startsWith("/api/subreddits/wikis")) {617
state.arcticWikiHits += 1;618
const paths = url.searchParams.get("paths") || "";619
const content = /the_last_terran/.test(paths) ? wikiTerran : wikiIndex;620
res.writeHead(200, { "Content-Type": "application/json" });621
res.end(JSON.stringify({ data: [{ path: paths, content }] }));622
return;623
}624
if (url.pathname.startsWith("/api/posts/ids")) {625
res.writeHead(200, { "Content-Type": "application/json" });626
res.end(JSON.stringify({ data: [samplePost("aaa111", "[OC] The Last Terran - Part 1", "WriterOne")] }));627
return;628
}629
res.writeHead(404);630
res.end("no arctic mock");631
}632
633
const started = await startServer(fixtureRoot, arcticHandler, redditHandler);634
const fetchApi = makeFetchApi(started.url);635
try {636
const storageMap = {637
indexBaseUrl: origin,638
indexRev: "",639
chapterSourceUrl: started.url,640
chapterSource: "auto",641
};642
const plugin = loadPlugin(storageMap, fetchApi);643
644
const popularArctic = await plugin.popularNovels(1, { filters: {} });645
assertLiveCover(646
popularArctic.find((n) => n.name === "The Last Terran").cover,647
"arctic",648
"eerst Arctic-wiki-cover",649
);650
assert(state.arcticWikiHits >= 1, "Arctic-wiki is gebruikt");651
const hitsBeforeRetry = state.wikiHits;652
653
state.redditMode = "ok";654
const popularRetry = await plugin.popularNovels(1, { filters: {} });655
assert(state.wikiHits > hitsBeforeRetry, "Arctic-cache triggert een nieuwe Reddit-poging (geen 6 uur wachten)");656
assertLiveCover(657
popularRetry.find((n) => n.name === "The Last Terran").cover,658
"reddit",659
"na inloggen Reddit-cover op de wiki-lijst",660
);661
662
// Nieuwe plugin, geen cache: wiki 403, api/info 403, comments 200.663
clearWikiCache(storageMap);664
state.redditMode = "ok";665
state.blockInfo = true;666
state.infoHits = 0;667
state.commentHits = 0;668
const pluginComments = loadPlugin(storageMap, fetchApi);669
const novel = await pluginComments.parseNovel("series/aaa111");670
assert(state.commentHits >= 1, "parseNovel valt terug op comments/.json");671
assertLiveCover(novel.cover, "reddit", "comments-fallback geeft Reddit-cover, niet Arctic");672
// Hoofdstuk uit Reddit: dezelfde cookies/endpoint.673
const html = await pluginComments.parseChapter("chapter/aaa111");674
assert(/Bron: Reddit/.test(html), "parseChapter toont Bron: Reddit");675
676
// Zonder bron → Reddit-cover (bij twijfel).677
assertLiveCover(plugin.coverFor({ name: "X" }), "reddit", "ontbrekende bron prefereert Reddit");678
assertLiveCover(plugin.coverFor({ name: "X", source: "index" }), "index", "index-bron");679
assertLiveCover(plugin.coverFor({ name: "X", source: "arctic" }), "arctic", "arctic-bron");680
681
console.log("✔️ covers: bron volgt Reddit na login, comments-fallback, index/reddit/arctic");682
} finally {683
started.server.close();684
}685
}686
558
async function testParseNovelWhenLiveFails(origin, fixtureRoot, assert) {687
async function testParseNovelWhenLiveFails(origin, fixtureRoot, assert) {559
// Reddit 403 + Arctic Shift 502 zonder posts-array: dit is de fout uit 0.3.2688
// Reddit 403 + Arctic Shift 502 zonder posts-array: dit is de fout uit 0.3.2560
// ("unable to load novel" overal, ook voor verhalen in de statische index).689
// ("unable to load novel" overal, ook voor verhalen in de statische index).@@ -585,8 +714,7 @@ async function testParseNovelWhenLiveFails(origin, fixtureRoot, assert) {585
assert(novel.path === "series/aaa111", "parseNovel houdt het aangevraagde pad");714
assert(novel.path === "series/aaa111", "parseNovel houdt het aangevraagde pad");586
assert(novel.name === "The Last Terran", "parseNovel valt terug op de statische index");715
assert(novel.name === "The Last Terran", "parseNovel valt terug op de statische index");587
assert(novel.chapters && novel.chapters.length === 3, "statische hoofdstuklijst blijft beschikbaar");716
assert(novel.chapters && novel.chapters.length === 3, "statische hoofdstuklijst blijft beschikbaar");588
assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "indexcover bij live-fout");717
assertLiveCover(novel.cover, "index", "indexcover bij live-fout");589
assert(String(novel.cover).indexOf("data:") === -1, "geen data-URI bij fallback");590
718
591
let wikiError = "";719
let wikiError = "";592
try {720
try {@@ -628,7 +756,7 @@ async function main() {628
756
629
assert(plugin.id === "hfyNovels", "id");757
assert(plugin.id === "hfyNovels", "id");630
assert(plugin.name === "HFY Novels", "name");758
assert(plugin.name === "HFY Novels", "name");631
assert(plugin.version === "0.3.3", "version");759
assert(plugin.version === "0.3.4", "version");632
assert(plugin.site === "https://www.reddit.com/r/HFY/", "site");760
assert(plugin.site === "https://www.reddit.com/r/HFY/", "site");633
assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings");761
assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings");634
assert(plugin.filters && plugin.filters.catalog, "filter Nieuw/wiki");762
assert(plugin.filters && plugin.filters.catalog, "filter Nieuw/wiki");@@ -643,23 +771,8 @@ async function main() {643
const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });771
const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });644
assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items");772
assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items");645
assert(popular[0].name && popular[0].path, "NovelItem heeft name+path");773
assert(popular[0].name && popular[0].path, "NovelItem heeft name+path");646
assert(popular[0].cover && popular[0].cover.indexOf("/covers/") !== -1, "cover-URL wijst naar covers/");774
assertLiveCover(popular[0].cover, "index", "statische cataloguscover");647
const coverIsSvg = /\.svg(\?|$)/i.test(popular[0].cover);775
assert(popular.every((n) => n.cover === LIVE_COVER_INDEX), "alle index-items delen index.png");648
if (coverIsSvg) {649
assert(popular[0].cover.indexOf("as=img") !== -1, "SVG-cover heeft as=img");650
}651
const coverRes = await fetch(popular[0].cover);652
assert(coverRes.ok, "cover is ophaalbaar");653
const coverBuf = Buffer.from(await coverRes.arrayBuffer());654
if (coverIsSvg) {655
const coverBody = coverBuf.toString("utf8");656
assert(coverBody.indexOf("<svg") === 0, "cover is een SVG");657
assert(coverBody.indexOf(popular[0].name) !== -1, "cover toont de titel");658
} else {659
assert(coverBuf[0] === 0x89 && coverBuf.toString("ascii", 1, 4) === "PNG", "cover is een PNG");660
}661
const coverAgain = Buffer.from(await (await fetch(popular[0].cover)).arrayBuffer());662
assert(Buffer.compare(coverBuf, coverAgain) === 0, "dezelfde titel geeft dezelfde cover");663
assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus");776
assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus");664
777
665
const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });778
const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });@@ -684,7 +797,7 @@ async function main() {684
const novel = await plugin.parseNovel("series/aaa111");797
const novel = await plugin.parseNovel("series/aaa111");685
assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input");798
assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input");686
assert(novel.author === "WriterOne", "auteur");799
assert(novel.author === "WriterOne", "auteur");687
assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "parseNovel heeft een cover-URL");800
assertLiveCover(novel.cover, "reddit", "parseNovel gebruikt Reddit-cover via comments/.json");688
assert(novel.chapters.length === 3, "3 hoofdstukken");801
assert(novel.chapters.length === 3, "3 hoofdstukken");689
assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad");802
assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad");690
assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer");803
assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer");@@ -751,6 +864,7 @@ async function main() {751
// --- Live catalogus: wiki, zoeken, parseNovel, met fallbacks ---864
// --- Live catalogus: wiki, zoeken, parseNovel, met fallbacks ---752
await testLiveCatalog(url, fixtureRoot, fetchApi, assert);865
await testLiveCatalog(url, fixtureRoot, fetchApi, assert);753
await testParseNovelWhenLiveFails(url, fixtureRoot, assert);866
await testParseNovelWhenLiveFails(url, fixtureRoot, assert);867
await testCoverSourceAfterLoginAndCommentsFallback(url, fixtureRoot, assert);754
868
755
869
756
// Manifest-vorm controleren.870
// Manifest-vorm controleren.