| 1 | #!/usr/bin/env node |
| 2 | "use strict"; |
| 3 | |
| 4 | /** |
| 5 | * Laadt de plugin zoals LNReader dat doet: custom require-allowlist, |
| 6 | * `new Function`, en daarna popularNovels / searchNovels / parseNovel / |
| 7 | * parseChapter. De index komt van een lokale HTTP-server (testdata of |
| 8 | * public/). parseChapter, searchNovels, popularNovels en parseNovel |
| 9 | * gebruiken gemockte Reddit-JSON, vallen terug op Arctic Shift en daarna |
| 10 | * op de statische index; optioneel een live verzoek als HFY_LIVE=1. |
| 11 | */ |
| 12 | |
| 13 | const fs = require("fs"); |
| 14 | const http = require("http"); |
| 15 | const path = require("path"); |
| 16 | |
| 17 | const ROOT = path.resolve(__dirname, ".."); |
| 18 | const PLUGIN = fs.readFileSync(path.join(ROOT, "plugin", "hfy-novels.js"), "utf8"); |
| 19 | |
| 20 | const NovelStatus = { |
| 21 | Completed: "Completed", |
| 22 | Ongoing: "Ongoing", |
| 23 | OnHiatus: "On Hiatus", |
| 24 | Unknown: "Unknown", |
| 25 | }; |
| 26 | const FilterTypes = { Picker: "Picker", Switch: "Switch", CheckboxGroup: "CheckboxGroup" }; |
| 27 | |
| 28 | function mimeFor(file, asImg) { |
| 29 | if (file.endsWith(".svg")) return asImg ? "image/svg+xml" : "text/plain; charset=utf-8"; |
| 30 | if (file.endsWith(".json")) return "text/plain; charset=utf-8"; // BlueGit serveert raw ook als text/plain |
| 31 | if (file.endsWith(".js")) return "text/plain; charset=utf-8"; |
| 32 | if (file.endsWith(".png")) return "image/png"; |
| 33 | return "application/octet-stream"; |
| 34 | } |
| 35 | |
| 36 | function startServer(rootDir, chapterHandler, redditHandler) { |
| 37 | return new Promise((resolve, reject) => { |
| 38 | const server = http.createServer((req, res) => { |
| 39 | const url = new URL(req.url, "http://127.0.0.1"); |
| 40 | if (url.pathname.startsWith("/api/posts/ids") || url.pathname.startsWith("/api/posts/search") || url.pathname.startsWith("/api/subreddits/wikis")) { |
| 41 | return chapterHandler(url, res); |
| 42 | } |
| 43 | if (redditHandler && /\/r\/HFY\//i.test(url.pathname)) { |
| 44 | return redditHandler(url, res, req); |
| 45 | } |
| 46 | if (redditHandler && url.pathname.startsWith("/api/info")) { |
| 47 | return redditHandler(url, res, req); |
| 48 | } |
| 49 | // ?rev=master zoals BlueGit raw-URLs; voor het bestand negeren we de query. |
| 50 | let rel = decodeURIComponent(url.pathname).replace(/^\/+/, ""); |
| 51 | const file = path.join(rootDir, rel); |
| 52 | if (!file.startsWith(path.resolve(rootDir))) { |
| 53 | res.writeHead(403); |
| 54 | res.end("forbidden"); |
| 55 | return; |
| 56 | } |
| 57 | fs.readFile(file, (err, data) => { |
| 58 | if (err) { |
| 59 | res.writeHead(404, { "Content-Type": "text/plain" }); |
| 60 | res.end("404 " + rel); |
| 61 | return; |
| 62 | } |
| 63 | const asImg = url.searchParams.get("as") === "img"; |
| 64 | res.writeHead(200, { "Content-Type": mimeFor(file, asImg) }); |
| 65 | res.end(data); |
| 66 | }); |
| 67 | }); |
| 68 | server.listen(0, "127.0.0.1", () => { |
| 69 | const { port } = server.address(); |
| 70 | resolve({ server, port, url: "http://127.0.0.1:" + port }); |
| 71 | }); |
| 72 | server.on("error", reject); |
| 73 | }); |
| 74 | } |
| 75 | |
| 76 | function redditListingFor(id) { |
| 77 | return [ |
| 78 | { |
| 79 | kind: "Listing", |
| 80 | data: { |
| 81 | children: [ |
| 82 | { |
| 83 | kind: "t3", |
| 84 | data: { |
| 85 | id, |
| 86 | title: "The Last Terran - Part 1", |
| 87 | author: "WriterOne", |
| 88 | selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)", |
| 89 | selftext_html: "<div class=\"md\"><p>It begins.</p></div>", |
| 90 | permalink: "/r/HFY/comments/" + id + "/", |
| 91 | }, |
| 92 | }, |
| 93 | ], |
| 94 | }, |
| 95 | }, |
| 96 | { kind: "Listing", data: { children: [] } }, |
| 97 | ]; |
| 98 | } |
| 99 | |
| 100 | function loginHtml() { |
| 101 | return "<!DOCTYPE html><html><head><title>reddit.com: Log in</title></head><body>Log in to Reddit to continue. <a href=\"https://www.reddit.com/login\">log in</a></body></html>"; |
| 102 | } |
| 103 | |
| 104 | function blockHtml() { |
| 105 | return "<body class=theme-beta><div>Request blocked. reason=lor2</div></body>"; |
| 106 | } |
| 107 | |
| 108 | function defaultRedditHandler(mode) { |
| 109 | return function redditHandler(url, res) { |
| 110 | const m = url.pathname.match(/\/comments\/([0-9a-z]{4,10})\//i); |
| 111 | if (!m) { |
| 112 | res.writeHead(404, { "Content-Type": "text/plain" }); |
| 113 | res.end("no default reddit mock for " + url.pathname); |
| 114 | return; |
| 115 | } |
| 116 | const id = m[1].toLowerCase(); |
| 117 | if (mode === "ok") { |
| 118 | res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" }); |
| 119 | res.end(JSON.stringify(redditListingFor(id))); |
| 120 | return; |
| 121 | } |
| 122 | if (mode === "403") { |
| 123 | res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" }); |
| 124 | res.end(blockHtml()); |
| 125 | return; |
| 126 | } |
| 127 | if (mode === "login-html") { |
| 128 | res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); |
| 129 | res.end(loginHtml()); |
| 130 | return; |
| 131 | } |
| 132 | res.writeHead(500, { "Content-Type": "text/plain" }); |
| 133 | res.end("reddit mock error"); |
| 134 | }; |
| 135 | } |
| 136 | |
| 137 | function defaultChapterHandler(url, res) { |
| 138 | if (!url.pathname.startsWith("/api/posts/ids")) { |
| 139 | res.writeHead(404, { "Content-Type": "text/plain" }); |
| 140 | res.end("no default arctic mock for " + url.pathname); |
| 141 | return; |
| 142 | } |
| 143 | const ids = url.searchParams.get("ids") || ""; |
| 144 | const id = ids.split(",")[0]; |
| 145 | const fixture = { |
| 146 | data: [ |
| 147 | { |
| 148 | id, |
| 149 | title: "The Last Terran - Part 1", |
| 150 | author: "WriterOne", |
| 151 | selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)", |
| 152 | selftext_html: "<p>It begins.</p>", |
| 153 | permalink: "/r/HFY/comments/" + id + "/", |
| 154 | }, |
| 155 | ], |
| 156 | }; |
| 157 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 158 | res.end(JSON.stringify(fixture)); |
| 159 | } |
| 160 | |
| 161 | function wrapResponse(res) { |
| 162 | return { |
| 163 | ok: res.ok, |
| 164 | status: res.status, |
| 165 | headers: res.headers, |
| 166 | async text() { |
| 167 | return await res.text(); |
| 168 | }, |
| 169 | async json() { |
| 170 | const text = await res.text(); |
| 171 | return JSON.parse(text); |
| 172 | }, |
| 173 | url: res.url, |
| 174 | }; |
| 175 | } |
| 176 | |
| 177 | function makeFetchApi(origin) { |
| 178 | return async function fetchApi(url, init) { |
| 179 | let target = String(url); |
| 180 | // Stuur Reddit-JSON naar de lokale testhost, zodat we 200/403/login kunnen simuleren. |
| 181 | if (/^https?:\/\/(www\.|old\.)?reddit\.com\//i.test(target)) { |
| 182 | const parsed = new URL(target); |
| 183 | target = origin + parsed.pathname + parsed.search; |
| 184 | } |
| 185 | const res = await fetch(target, init); |
| 186 | return wrapResponse(res); |
| 187 | }; |
| 188 | } |
| 189 | |
| 190 | function loadPlugin(storageMap, fetchApi) { |
| 191 | const allow = { |
| 192 | "@libs/fetch": { fetchApi, fetchText: async (u, i) => (await fetchApi(u, i)).text() }, |
| 193 | "@libs/filterInputs": { FilterTypes }, |
| 194 | "@libs/defaultCover": { defaultCover: "https://example.invalid/cover.png" }, |
| 195 | "@libs/novelStatus": { NovelStatus }, |
| 196 | "@libs/storage": { |
| 197 | storage: { |
| 198 | get(key) { |
| 199 | return storageMap[key]; |
| 200 | }, |
| 201 | set(key, value, expires) { |
| 202 | storageMap[key] = value; |
| 203 | if (expires != null) { |
| 204 | storageMap[key + "__expires"] = expires; |
| 205 | } |
| 206 | }, |
| 207 | }, |
| 208 | }, |
| 209 | }; |
| 210 | const pluginModule = { exports: {} }; |
| 211 | const fn = new Function("exports", "require", "module", PLUGIN); |
| 212 | fn(pluginModule.exports, (name) => { |
| 213 | if (!allow[name]) { |
| 214 | throw new Error("blocked require: " + name); |
| 215 | } |
| 216 | return allow[name]; |
| 217 | }, pluginModule); |
| 218 | const plugin = pluginModule.exports.default; |
| 219 | if (!plugin) { |
| 220 | throw new Error("geen default export"); |
| 221 | } |
| 222 | for (const method of ["popularNovels", "searchNovels", "parseNovel", "parseChapter"]) { |
| 223 | if (typeof plugin[method] !== "function") { |
| 224 | throw new Error("plugin mist " + method); |
| 225 | } |
| 226 | } |
| 227 | return plugin; |
| 228 | } |
| 229 | |
| 230 | function assert(cond, msg) { |
| 231 | if (!cond) { |
| 232 | throw new Error("FAIL: " + msg); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | function wikiIndexPayload(markdown) { |
| 237 | return { kind: "wikipage", data: { content_md: markdown, revision_date: 1700000000 } }; |
| 238 | } |
| 239 | |
| 240 | function listingOf(posts) { |
| 241 | return { |
| 242 | kind: "Listing", |
| 243 | data: { |
| 244 | children: posts.map((p) => ({ kind: "t3", data: p })), |
| 245 | after: null, |
| 246 | }, |
| 247 | }; |
| 248 | } |
| 249 | |
| 250 | function samplePost(id, title, author, extras) { |
| 251 | const extra = extras || {}; |
| 252 | return Object.assign( |
| 253 | { |
| 254 | id, |
| 255 | title, |
| 256 | author, |
| 257 | created_utc: extra.created_utc || 1700000000, |
| 258 | permalink: "/r/HFY/comments/" + id + "/", |
| 259 | selftext: extra.selftext || "", |
| 260 | selftext_html: extra.selftext_html || "", |
| 261 | link_flair_text: extra.flair || "OC-Series", |
| 262 | over_18: !!extra.over_18, |
| 263 | is_self: true, |
| 264 | }, |
| 265 | extra.more || {}, |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) { |
| 270 | const wikiIndex = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "index.md"), "utf8"); |
| 271 | const wikiTerran = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "pages", "the_last_terran.md"), "utf8"); |
| 272 | const state = { redditMode: "ok", arcticMode: "ok", wikiHits: 0, searchHits: 0, arcticSearchHits: 0, arcticWikiHits: 0, infoHits: 0 }; |
| 273 | |
| 274 | function redditHandler(url, res) { |
| 275 | if (state.redditMode === "403") { |
| 276 | res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" }); |
| 277 | res.end(blockHtml()); |
| 278 | return; |
| 279 | } |
| 280 | if (state.redditMode === "error") { |
| 281 | res.writeHead(500, { "Content-Type": "text/plain" }); |
| 282 | res.end("reddit mock error"); |
| 283 | return; |
| 284 | } |
| 285 | if (/\/wiki\/series\/the_last_terran/i.test(url.pathname)) { |
| 286 | state.wikiHits += 1; |
| 287 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 288 | res.end(JSON.stringify(wikiIndexPayload(wikiTerran))); |
| 289 | return; |
| 290 | } |
| 291 | if (/\/wiki\/series/i.test(url.pathname)) { |
| 292 | state.wikiHits += 1; |
| 293 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 294 | res.end(JSON.stringify(wikiIndexPayload(wikiIndex))); |
| 295 | return; |
| 296 | } |
| 297 | if (/\/search\.json$/i.test(url.pathname)) { |
| 298 | state.searchHits += 1; |
| 299 | const q = (url.searchParams.get("q") || "").toLowerCase(); |
| 300 | const posts = []; |
| 301 | if (q.indexOf("terran") !== -1 || q.indexOf("writerone") !== -1) { |
| 302 | posts.push( |
| 303 | samplePost("aaa111", "[OC] The Last Terran - Part 1", "WriterOne", { |
| 304 | flair: "OC-FirstOfSeries", |
| 305 | selftext: "[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)", |
| 306 | }), |
| 307 | ); |
| 308 | } |
| 309 | if (q.indexOf("star") !== -1 || q.indexOf("boat") !== -1) { |
| 310 | posts.push( |
| 311 | samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", { |
| 312 | flair: "OC-FirstOfSeries", |
| 313 | selftext: "[Next](https://www.reddit.com/r/HFY/comments/ddd002/x/)", |
| 314 | created_utc: 1700345600, |
| 315 | }), |
| 316 | ); |
| 317 | posts.push( |
| 318 | samplePost("ddd002", "Star Boat - Part 2", "Skipper", { |
| 319 | flair: "OC-Series", |
| 320 | selftext: "[Prev](https://www.reddit.com/r/HFY/comments/ddd001/x/)", |
| 321 | created_utc: 1700432000, |
| 322 | }), |
| 323 | ); |
| 324 | } |
| 325 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 326 | res.end(JSON.stringify(listingOf(posts))); |
| 327 | return; |
| 328 | } |
| 329 | if (/\/new\.json$/i.test(url.pathname)) { |
| 330 | state.searchHits += 1; |
| 331 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 332 | res.end( |
| 333 | JSON.stringify( |
| 334 | listingOf([ |
| 335 | samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", { |
| 336 | flair: "OC-FirstOfSeries", |
| 337 | created_utc: 1700345600, |
| 338 | }), |
| 339 | samplePost("meta999", "[META] Weekly thread", "ModAccount", { flair: "Meta", created_utc: 1700345700 }), |
| 340 | samplePost("aaa444", "The Last Terran - Part 4", "WriterOne", { |
| 341 | flair: "OC-Series", |
| 342 | created_utc: 1700259200, |
| 343 | }), |
| 344 | ]), |
| 345 | ), |
| 346 | ); |
| 347 | return; |
| 348 | } |
| 349 | if (url.pathname.startsWith("/api/info") || /\/comments\/[0-9a-z]+\//i.test(url.pathname)) { |
| 350 | state.infoHits += 1; |
| 351 | const ids = []; |
| 352 | if (url.searchParams.get("id")) { |
| 353 | url.searchParams.get("id").split(",").forEach((raw) => ids.push(raw.replace(/^t3_/, "").toLowerCase())); |
| 354 | } else { |
| 355 | const m = url.pathname.match(/\/comments\/([0-9a-z]{4,10})\//i); |
| 356 | if (m) ids.push(m[1].toLowerCase()); |
| 357 | } |
| 358 | const posts = ids.map((id) => { |
| 359 | if (id === "aaa222") { |
| 360 | return samplePost(id, "The Last Terran - Part 2", "WriterOne", { |
| 361 | selftext: "[Prev](https://www.reddit.com/r/HFY/comments/aaa111/x/) | [Next](https://www.reddit.com/r/HFY/comments/aaa333/x/)", |
| 362 | }); |
| 363 | } |
| 364 | if (id === "aaa333") { |
| 365 | return samplePost(id, "The Last Terran Chapter 3", "WriterOne", { |
| 366 | selftext: "[Previous](/r/HFY/comments/aaa222/)", |
| 367 | }); |
| 368 | } |
| 369 | return samplePost(id, "The Last Terran - Part 1", "WriterOne", { |
| 370 | flair: "OC-FirstOfSeries", |
| 371 | selftext: "[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)", |
| 372 | }); |
| 373 | }); |
| 374 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 375 | if (/\/comments\//i.test(url.pathname)) { |
| 376 | res.end(JSON.stringify(redditListingFor(ids[0] || "aaa111"))); |
| 377 | } else { |
| 378 | res.end(JSON.stringify(listingOf(posts))); |
| 379 | } |
| 380 | return; |
| 381 | } |
| 382 | res.writeHead(404, { "Content-Type": "text/plain" }); |
| 383 | res.end("no reddit mock for " + url.pathname); |
| 384 | } |
| 385 | |
| 386 | function arcticHandler(url, res) { |
| 387 | if (url.pathname.startsWith("/api/subreddits/wikis")) { |
| 388 | state.arcticWikiHits += 1; |
| 389 | if (state.arcticMode === "fail") { |
| 390 | res.writeHead(500, { "Content-Type": "text/plain" }); |
| 391 | res.end("arctic wiki fail"); |
| 392 | return; |
| 393 | } |
| 394 | const paths = url.searchParams.get("paths") || ""; |
| 395 | const content = /the_last_terran/.test(paths) ? wikiTerran : wikiIndex; |
| 396 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 397 | res.end(JSON.stringify({ data: [{ path: paths, content }] })); |
| 398 | return; |
| 399 | } |
| 400 | if (url.pathname.startsWith("/api/posts/search")) { |
| 401 | state.arcticSearchHits += 1; |
| 402 | if (state.arcticMode === "fail") { |
| 403 | res.writeHead(500, { "Content-Type": "text/plain" }); |
| 404 | res.end("arctic search fail"); |
| 405 | return; |
| 406 | } |
| 407 | const q = ((url.searchParams.get("query") || "") + " " + (url.searchParams.get("title") || "")).toLowerCase(); |
| 408 | const posts = []; |
| 409 | if (!q.trim() || q.indexOf("star") !== -1 || q.indexOf("boat") !== -1) { |
| 410 | posts.push( |
| 411 | samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", { |
| 412 | flair: "OC-FirstOfSeries", |
| 413 | created_utc: 1700345600, |
| 414 | }), |
| 415 | ); |
| 416 | } |
| 417 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 418 | res.end(JSON.stringify({ data: posts })); |
| 419 | return; |
| 420 | } |
| 421 | if (url.pathname.startsWith("/api/posts/ids")) { |
| 422 | return defaultChapterHandler(url, res); |
| 423 | } |
| 424 | res.writeHead(404); |
| 425 | res.end("no arctic mock"); |
| 426 | } |
| 427 | |
| 428 | const started = await startServer(fixtureRoot, arcticHandler, redditHandler); |
| 429 | const liveFetch = makeFetchApi(started.url); |
| 430 | try { |
| 431 | const storageMap = { |
| 432 | indexBaseUrl: origin, |
| 433 | indexRev: "", |
| 434 | chapterSourceUrl: started.url, |
| 435 | chapterSource: "auto", |
| 436 | }; |
| 437 | const plugin = loadPlugin(storageMap, liveFetch); |
| 438 | |
| 439 | state.wikiHits = 0; |
| 440 | const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} }); |
| 441 | assert(popular.some((n) => n.name === "The Last Terran"), "live wiki-index levert The Last Terran"); |
| 442 | assert(popular.some((n) => n.path.indexOf("the_last_terran") !== -1 || n.path === "wiki/the_last_terran"), "wiki-pad zonder first-id"); |
| 443 | const hitsAfterFirst = state.wikiHits; |
| 444 | assert(hitsAfterFirst >= 1, "wiki-index is bij Reddit opgehaald"); |
| 445 | const popularAgain = await plugin.popularNovels(1, { filters: {} }); |
| 446 | assert(popularAgain.some((n) => n.name === "The Last Terran"), "cache levert opnieuw de wiki-index"); |
| 447 | assert(state.wikiHits === hitsAfterFirst, "tweede popularNovels gebruikt de wiki-cache"); |
| 448 | |
| 449 | const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} }); |
| 450 | assert(latest.some((n) => /Star Boat/i.test(n.name)), "Latest/Nieuw toont recente OC-reeks"); |
| 451 | assert(latest.every((n) => !/Weekly thread/i.test(n.name)), "Meta-posts blijven buiten Nieuw"); |
| 452 | const viaFilter = await plugin.popularNovels(1, { filters: { catalog: { value: "new" } } }); |
| 453 | assert(viaFilter.some((n) => /Star Boat/i.test(n.name)), "filter Nieuw toont recente OC-posts"); |
| 454 | |
| 455 | const search = await plugin.searchNovels("terran", 1); |
| 456 | assert(search.some((n) => /Last Terran/i.test(n.name)), "searchNovels groepeert wiki + Part 1"); |
| 457 | const star = await plugin.searchNovels("Star Boat", 1); |
| 458 | assert(star.length === 1 && /Star Boat/i.test(star[0].name), "losse Part 1+2 worden één novel"); |
| 459 | assert(star[0].path === "series/ddd001", "nieuwe reeks gebruikt het eerste deel als id"); |
| 460 | |
| 461 | const novel = await plugin.parseNovel("wiki/the_last_terran"); |
| 462 | assert(novel.name === "The Last Terran", "parseNovel gebruikt de wiki-titel"); |
| 463 | assert(novel.author === "WriterOne", "parseNovel leest de auteur uit de wiki"); |
| 464 | assert(novel.chapters.length === 3, "parseNovel volgt de wiki-TOC"); |
| 465 | assert(novel.chapters[0].path === "chapter/aaa111", "eerste hoofdstukpad"); |
| 466 | assert(novel.chapters[2].path === "chapter/aaa333", "laatste TOC-hoofdstuk"); |
| 467 | |
| 468 | delete storageMap.wikiSeriesIndex; |
| 469 | state.redditMode = "403"; |
| 470 | state.arcticMode = "ok"; |
| 471 | state.arcticWikiHits = 0; |
| 472 | const plugin403 = loadPlugin(storageMap, liveFetch); |
| 473 | const popular403 = await plugin403.popularNovels(1, { filters: {} }); |
| 474 | assert(popular403.some((n) => n.name === "The Last Terran"), "403 valt terug op Arctic Shift-wiki"); |
| 475 | assert(state.arcticWikiHits >= 1, "403 roept Arctic Shift-wiki aan"); |
| 476 | |
| 477 | const search403 = await plugin403.searchNovels("Star Boat", 1); |
| 478 | assert(search403.some((n) => /Star Boat/i.test(n.name)), "zoeken valt bij 403 terug op Arctic Shift"); |
| 479 | |
| 480 | delete storageMap.wikiSeriesIndex; |
| 481 | state.redditMode = "403"; |
| 482 | state.arcticMode = "fail"; |
| 483 | const pluginStatic = loadPlugin(storageMap, liveFetch); |
| 484 | const popularStatic = await pluginStatic.popularNovels(1, { filters: {} }); |
| 485 | assert(popularStatic.some((n) => n.path === "series/aaa111"), "na Reddit+Arctic Shift volgt de statische index"); |
| 486 | const searchStatic = await pluginStatic.searchNovels("terran", 1); |
| 487 | assert(searchStatic.length === 1 && searchStatic[0].path === "series/aaa111", "zoeken valt terug op de statische index"); |
| 488 | |
| 489 | console.log("✔️ live catalogus: wiki, Nieuw, zoeken, parseNovel, 403→Arctic Shift→index"); |
| 490 | } finally { |
| 491 | started.server.close(); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | |
| 496 | async function main() { |
| 497 | const fixtureRoot = path.join(ROOT, "testdata", "index-fixture"); |
| 498 | const redditState = { mode: "ok", redditHits: 0, arcticHits: 0 }; |
| 499 | const chapterHandler = (reqUrl, res) => { |
| 500 | redditState.arcticHits += 1; |
| 501 | return defaultChapterHandler(reqUrl, res); |
| 502 | }; |
| 503 | const redditHandler = (reqUrl, res) => { |
| 504 | redditState.redditHits += 1; |
| 505 | return defaultRedditHandler(redditState.mode)(reqUrl, res); |
| 506 | }; |
| 507 | const { server, url } = await startServer(fixtureRoot, chapterHandler, redditHandler); |
| 508 | const fetchApi = makeFetchApi(url); |
| 509 | const failures = []; |
| 510 | try { |
| 511 | const storageMap = { |
| 512 | indexBaseUrl: url, |
| 513 | indexRev: "", // geen ?rev= nodig op de testhost |
| 514 | chapterSourceUrl: url, |
| 515 | chapterSource: "auto", |
| 516 | }; |
| 517 | const plugin = loadPlugin(storageMap, fetchApi); |
| 518 | |
| 519 | assert(plugin.id === "hfyNovels", "id"); |
| 520 | assert(plugin.name === "HFY Novels", "name"); |
| 521 | assert(plugin.version === "0.3.0", "version"); |
| 522 | assert(plugin.site === "https://www.reddit.com/r/HFY/", "site"); |
| 523 | assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings"); |
| 524 | assert(plugin.filters && plugin.filters.catalog, "filter Nieuw/wiki"); |
| 525 | assert(plugin.pluginSettings.chapterSource && plugin.pluginSettings.chapterSource.type === "Select", "bron-instelling is Select"); |
| 526 | assert(typeof plugin.resolveUrl === "function", "resolveUrl"); |
| 527 | assert(plugin.resolveUrl("chapter/aaa111") === "https://www.reddit.com/r/HFY/comments/aaa111/", "resolveUrl hoofdstuk"); |
| 528 | assert(plugin.resolveUrl("series/aaa111", true) === "https://www.reddit.com/r/HFY/comments/aaa111/", "resolveUrl reeks"); |
| 529 | assert(plugin.resolveUrl("wiki/the_last_terran", true) === "https://www.reddit.com/r/HFY/wiki/series/the_last_terran/", "resolveUrl wiki"); |
| 530 | |
| 531 | const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} }); |
| 532 | assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items"); |
| 533 | assert(popular[0].name && popular[0].path, "NovelItem heeft name+path"); |
| 534 | assert(popular[0].cover && popular[0].cover.indexOf("/covers/") !== -1, "cover-URL wijst naar covers/"); |
| 535 | const coverIsSvg = /\.svg(\?|$)/i.test(popular[0].cover); |
| 536 | if (coverIsSvg) { |
| 537 | assert(popular[0].cover.indexOf("as=img") !== -1, "SVG-cover heeft as=img"); |
| 538 | } |
| 539 | const coverRes = await fetch(popular[0].cover); |
| 540 | assert(coverRes.ok, "cover is ophaalbaar"); |
| 541 | const coverBuf = Buffer.from(await coverRes.arrayBuffer()); |
| 542 | if (coverIsSvg) { |
| 543 | const coverBody = coverBuf.toString("utf8"); |
| 544 | assert(coverBody.indexOf("<svg") === 0, "cover is een SVG"); |
| 545 | assert(coverBody.indexOf(popular[0].name) !== -1, "cover toont de titel"); |
| 546 | } else { |
| 547 | assert(coverBuf[0] === 0x89 && coverBuf.toString("ascii", 1, 4) === "PNG", "cover is een PNG"); |
| 548 | } |
| 549 | const coverAgain = Buffer.from(await (await fetch(popular[0].cover)).arrayBuffer()); |
| 550 | assert(Buffer.compare(coverBuf, coverAgain) === 0, "dezelfde titel geeft dezelfde cover"); |
| 551 | assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus"); |
| 552 | |
| 553 | const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} }); |
| 554 | assert(latest.length >= 1, "showLatestNovels werkt via zoekindex"); |
| 555 | |
| 556 | const oneshots = await plugin.popularNovels(1, { |
| 557 | filters: { kind: { value: "oneshot" }, nsfw: { value: "hide" } }, |
| 558 | }); |
| 559 | assert(oneshots.length === 1 && oneshots[0].name === "A Short Hello", "filter oneshot"); |
| 560 | |
| 561 | const nsfw = await plugin.popularNovels(1, { |
| 562 | filters: { kind: { value: "all" }, nsfw: { value: "show" } }, |
| 563 | }); |
| 564 | assert(nsfw.some((n) => n.path.includes("ccc001")), "NSFW zichtbaar met filter"); |
| 565 | |
| 566 | const search = await plugin.searchNovels("terran", 1); |
| 567 | assert(search.length === 1 && search[0].path === "series/aaa111", "searchNovels op titel"); |
| 568 | const byAuthor = await plugin.searchNovels("WriterTwo", 1); |
| 569 | assert(byAuthor.length === 1, "searchNovels op auteur"); |
| 570 | assert((await plugin.searchNovels("", 1)).length === 0, "lege zoekterm"); |
| 571 | |
| 572 | const novel = await plugin.parseNovel("series/aaa111"); |
| 573 | assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input"); |
| 574 | assert(novel.author === "WriterOne", "auteur"); |
| 575 | assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "parseNovel heeft een cover-URL"); |
| 576 | assert(novel.chapters.length === 3, "3 hoofdstukken"); |
| 577 | assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad"); |
| 578 | assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer"); |
| 579 | assert(novel.status === NovelStatus.Ongoing || novel.status === NovelStatus.OnHiatus || novel.status === NovelStatus.Unknown, "status enum"); |
| 580 | |
| 581 | redditState.mode = "ok"; |
| 582 | redditState.redditHits = 0; |
| 583 | redditState.arcticHits = 0; |
| 584 | const html = await plugin.parseChapter("chapter/aaa111"); |
| 585 | assert(/It begins/.test(html), "parseChapter bevat tekst"); |
| 586 | assert(/<h1>/.test(html), "parseChapter heeft titel"); |
| 587 | assert(!/<script/i.test(html), "geen script-tags"); |
| 588 | assert(/Bron: Reddit/.test(html), "Reddit-ok toont Bron: Reddit"); |
| 589 | assert(redditState.arcticHits === 0, "bij Reddit-ok geen Arctic Shift-aanroep"); |
| 590 | assert(redditState.redditHits >= 1, "Reddit-JSON is aangeroepen"); |
| 591 | |
| 592 | redditState.mode = "403"; |
| 593 | redditState.redditHits = 0; |
| 594 | redditState.arcticHits = 0; |
| 595 | const html403 = await plugin.parseChapter("chapter/aaa111"); |
| 596 | assert(/It begins/.test(html403), "403 valt terug op Arctic Shift"); |
| 597 | assert(/Bron: Arctic Shift \(fallback\)/.test(html403), "403 toont fallback-bron"); |
| 598 | assert(redditState.arcticHits >= 1, "403 roept Arctic Shift aan"); |
| 599 | assert(redditState.redditHits >= 1, "403 probeert eerst Reddit"); |
| 600 | |
| 601 | redditState.mode = "login-html"; |
| 602 | redditState.redditHits = 0; |
| 603 | redditState.arcticHits = 0; |
| 604 | const htmlLogin = await plugin.parseChapter("chapter/aaa111"); |
| 605 | assert(/It begins/.test(htmlLogin), "login-HTML valt terug op Arctic Shift"); |
| 606 | assert(/Bron: Arctic Shift \(fallback\)/.test(htmlLogin), "login-HTML toont fallback-bron"); |
| 607 | assert(redditState.arcticHits >= 1, "login-HTML roept Arctic Shift aan"); |
| 608 | |
| 609 | storageMap.chapterSource = "reddit"; |
| 610 | redditState.mode = "403"; |
| 611 | redditState.arcticHits = 0; |
| 612 | let redditOnlyThrew = false; |
| 613 | try { |
| 614 | await plugin.parseChapter("chapter/aaa111"); |
| 615 | } catch (err) { |
| 616 | redditOnlyThrew = /Reddit/.test(String(err && err.message)) && /WebView/.test(String(err && err.message)); |
| 617 | } |
| 618 | assert(redditOnlyThrew, "modus Reddit faalt zichtbaar bij 403"); |
| 619 | assert(redditState.arcticHits === 0, "modus Reddit gebruikt geen fallback"); |
| 620 | |
| 621 | storageMap.chapterSource = "arctic"; |
| 622 | redditState.mode = "ok"; |
| 623 | redditState.redditHits = 0; |
| 624 | redditState.arcticHits = 0; |
| 625 | const htmlArctic = await plugin.parseChapter("chapter/aaa111"); |
| 626 | assert(/Bron: Arctic Shift</.test(htmlArctic) && !/fallback/.test(htmlArctic), "modus Arctic Shift slaat Reddit over"); |
| 627 | assert(redditState.redditHits === 0, "modus Arctic Shift roept Reddit niet aan"); |
| 628 | assert(redditState.arcticHits >= 1, "modus Arctic Shift gebruikt Arctic Shift"); |
| 629 | storageMap.chapterSource = "auto"; |
| 630 | |
| 631 | let threw = false; |
| 632 | try { |
| 633 | await plugin.parseChapter("chapter/../etc/passwd"); |
| 634 | } catch (err) { |
| 635 | threw = true; |
| 636 | } |
| 637 | assert(threw, "ongeldig hoofdstuk-id wordt geweigerd"); |
| 638 | |
| 639 | // --- Live catalogus: wiki, zoeken, parseNovel, met fallbacks --- |
| 640 | await testLiveCatalog(url, fixtureRoot, fetchApi, assert); |
| 641 | |
| 642 | // Manifest-vorm controleren. |
| 643 | const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.json"), "utf8")); |
| 644 | const manifestMin = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.min.json"), "utf8")); |
| 645 | assert(Array.isArray(manifest) && manifest.length === 1, "plugins.json is een array"); |
| 646 | assert(manifestMin[0].version === manifest[0].version, "plugins.min.json heeft dezelfde versie"); |
| 647 | const entry = manifest[0]; |
| 648 | for (const key of ["id", "name", "site", "lang", "version", "url", "iconUrl"]) { |
| 649 | assert(entry[key], "manifest mist " + key); |
| 650 | } |
| 651 | assert(entry.id === plugin.id && entry.version === plugin.version, "manifest komt overeen met plugin"); |
| 652 | assert(entry.lang === "English", "lang is de volle taalnaam"); |
| 653 | assert(entry.hasSettings === true, "hasSettings"); |
| 654 | assert(entry.url.includes("/-/raw/.dist/hfy-novels.js"), "raw URL voor de plugin-JS"); |
| 655 | assert(entry.url.includes("rev=master"), "rev=master in de plugin-URL"); |
| 656 | |
| 657 | console.log("✔️ plugininterface: popularNovels, searchNovels, parseNovel, parseChapter"); |
| 658 | console.log("✔️ plugins.json komt overeen met de plugin-export"); |
| 659 | |
| 660 | if (process.env.HFY_LIVE === "1") { |
| 661 | const liveStorage = { |
| 662 | indexBaseUrl: url, |
| 663 | indexRev: "", |
| 664 | chapterSourceUrl: "https://arctic-shift.photon-reddit.com", |
| 665 | }; |
| 666 | const livePlugin = loadPlugin(liveStorage, async (reqUrl, init) => wrapResponse(await fetch(reqUrl, init))); |
| 667 | // Een recent, echt post-id uit de Arctic Shift-probe: willekeurig een |
| 668 | // bekend kort id heeft geen zin. We vragen een recente HFY-post op. |
| 669 | const listing = await fetch( |
| 670 | "https://arctic-shift.photon-reddit.com/api/posts/search?subreddit=HFY&limit=1&sort=desc", |
| 671 | { headers: { "User-Agent": "HFY-Novels/0.1 (plugin live test)" } }, |
| 672 | ); |
| 673 | if (!listing.ok) { |
| 674 | throw new Error("live listing HTTP " + listing.status); |
| 675 | } |
| 676 | const body = await listing.json(); |
| 677 | const liveId = body.data[0].id; |
| 678 | const liveHtml = await livePlugin.parseChapter("chapter/" + liveId); |
| 679 | assert(liveHtml.length > 20, "live parseChapter gaf inhoud"); |
| 680 | const liveSource = /Bron: ([^<]+)/.exec(liveHtml); |
| 681 | console.log("✔️ live parseChapter (" + liveId + ", " + liveHtml.length + " tekens, " + ((liveSource && liveSource[1]) || "bron onbekend") + ")"); |
| 682 | } |
| 683 | } catch (err) { |
| 684 | failures.push(err); |
| 685 | } finally { |
| 686 | server.close(); |
| 687 | } |
| 688 | |
| 689 | if (failures.length) { |
| 690 | for (const err of failures) { |
| 691 | console.error(err); |
| 692 | } |
| 693 | process.exit(1); |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | main().catch((err) => { |
| 698 | console.error(err); |
| 699 | process.exit(1); |
| 700 | }); |