"use strict"; const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const os = require("node:os"); const path = require("node:path"); const { ValidationError, planQueueJobs, buildQueueJobs, STATUS_READ_PROJECTION } = require("../lib/jobValidation"); const { createQueueController } = require("../controllers/queueController"); const { QUERY_TIMEOUT_MS } = require("../lib/statusQuery"); const CREATED = new Date("2026-01-01T12:00:00.000Z"); function seriesBody(changes = {}) { return { mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engsub", name: "Title", token: "fixture-token", season: "1", ...changes, }; } async function temporaryConfig(t) { const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-refinements-")); t.after(() => fs.rm(outputDir, { recursive: true, force: true })); return { outputDir, tokenPrefix: "fixture_cookie=", maxSeriesEpisodes: 500 }; } function response() { return { statusCode: 200, headers: {}, status(code) { this.statusCode = code; return this; }, set(name, value) { this.headers[name] = value; return this; }, render(template, data) { this.template = template; this.data = data; return this; }, json(data) { this.data = data; return this; }, redirect(location) { this.location = location; return this; }, }; } test("series planning uses a minimum three digits for explicit season and episode with the language suffix", async t => { const settings = await temporaryConfig(t); const planned = await planQueueJobs(seriesBody({ token: undefined }), settings, () => CREATED); assert.deepEqual(planned, [ { url: "https://proxer.me/watch/42/9/engsub", filename: "TitleS001E009_engsub", created_at: CREATED }, { url: "https://proxer.me/watch/42/10/engsub", filename: "TitleS001E010_engsub", created_at: CREATED }, ]); const jobs = await buildQueueJobs(seriesBody(), settings, () => CREATED); assert.deepEqual(jobs, planned.map(job => ({ ...job, token: "fixture_cookie=fixture-token" }))); assert.equal(`${jobs[0].filename}.mp4`, "TitleS001E009_engsub.mp4"); }); test("season zero supports specials and larger season or episode numbers are preserved without truncation", async t => { const settings = await temporaryConfig(t); for (const [season, first, expected] of [ ["0", "9", "TitleS000E009_gerdub"], [1, "9", "TitleS001E009_gerdub"], ["1234", "9", "TitleS1234E009_gerdub"], ["1", "1234", "TitleS001E1234_gerdub"], ["1234", "1234", "TitleS1234E1234_gerdub"], ]) { const jobs = await buildQueueJobs(seriesBody({ season, episode_from: first, episode_to: first, language: "gerdub" }), settings); assert.equal(jobs[0].filename, expected); assert.equal(jobs[0].url, `https://proxer.me/watch/42/${first}/gerdub`); } }); test("series filename limits include the full season, episode, language, extension, and Unicode byte length", async t => { const settings = await temporaryConfig(t); const suffix = "S001E009_engsub.mp4"; const available = 255 - Buffer.byteLength(suffix, "utf8"); const title = "界".repeat(Math.floor(available / 3)) + "a".repeat(available % 3); const body = seriesBody({ name: title, episode_to: "9" }); const jobs = await buildQueueJobs(body, settings); assert.equal(Buffer.byteLength(`${jobs[0].filename}.mp4`, "utf8"), 255); await assert.rejects(planQueueJobs({ ...body, name: title + "界" }, settings), ValidationError); await assert.rejects(buildQueueJobs({ ...body, name: title + "a" }, settings), ValidationError); }); test("malformed explicit seasons fail instead of silently selecting a default or legacy filename", async t => { const settings = await temporaryConfig(t); const malformed = ["", null, true, {}, [], "01", "-1", "-0", "1.5", " 1", "1 ", "1e2", "+1", "NaN", Number.MAX_SAFE_INTEGER + 1, Infinity, NaN]; for (const season of malformed) { await assert.rejects(planQueueJobs(seriesBody({ season }), settings), ValidationError, String(season)); } }); test("clients omitting season retain legacy names and single-video requests ignore the series season field", async t => { const settings = await temporaryConfig(t); const legacy = seriesBody({ season: undefined, episode_from: "9", episode_to: "12" }); const jobs = await buildQueueJobs(legacy, settings); assert.deepEqual(jobs.map(job => job.filename), ["TitleE09_engsub", "TitleE10_engsub", "TitleE11_engsub", "TitleE12_engsub"]); const video = { mode: "video", url: "https://proxer.me/watch/42/9/engsub", filename: "My single download", token: "fixture-token", season: { $gt: "not-a-season" }, }; const planned = await planQueueJobs(video, settings); const built = await buildQueueJobs(video, settings); assert.equal(planned[0].filename, "My single download"); assert.equal(built[0].filename, "My single download"); assert.equal(planned[0].token, undefined); assert.equal(built[0].token, "fixture_cookie=fixture-token"); }); test("clear-state validates a scalar allowlisted state and protects processing before any database access", async () => { let connections = 0; const controller = createQueueController({ getDb: async () => { connections += 1; throw new Error("Must not connect"); } }); for (const state of [undefined, null, [], ["queued"], {}, { $ne: "processing" }, "settings", "$where", "all", " queued", "DONE"]) { const result = response(); await controller.clearState({ body: { state } }, result, error => { throw error; }); assert.equal(result.statusCode, 400, String(state)); assert.equal(result.headers["Cache-Control"], "no-store"); assert.equal(result.location, undefined); } const processing = response(); await controller.clearState({ body: { state: "processing" } }, processing, error => { throw error; }); assert.equal(processing.statusCode, 409); assert.equal(processing.location, undefined); assert.equal(connections, 0); }); test("clearing waiting jobs uses one atomic processing-not-true predicate and preserves a concurrently claimed job", async () => { let records = [{ _id: "waiting" }, { _id: "claimed-during-request" }, { _id: "already-active", processing: true }]; const calls = []; const db = { collection(name) { calls.push({ operation: "collection", name }); return { async deleteMany(filter) { calls.push({ operation: "delete", filter }); assert.deepEqual(filter, { processing: { $ne: true } }); // This claim arrives after the HTTP request but before Mongo evaluates // the delete predicate. No earlier list of IDs can authorize its removal. records.find(record => record._id === "claimed-during-request").processing = true; const before = records.length; records = records.filter(record => record.processing === true); return { acknowledged: true, deletedCount: before - records.length }; } }; } }; const result = response(); await createQueueController({ getDb: async () => db }).clearState({ body: { state: "queued", filter: {}, processing: {}, q: "injected" }, query: { state: "processing", q: { $where: "ignored" }, page: "999" }, }, result, error => { throw error; }); assert.deepEqual(calls, [ { operation: "collection", name: "queue" }, { operation: "delete", filter: { processing: { $ne: true } } }, ]); assert.deepEqual(records.map(record => record._id), ["claimed-during-request", "already-active"]); assert.equal(result.location, "/status?state=queued"); }); test("clearing history deletes only the selected history collection and preserves downloaded media", async t => { const settings = await temporaryConfig(t); const media = path.join(settings.outputDir, "TitleS001E009_engsub.mp4"); await fs.writeFile(media, "downloaded-video-fixture"); for (const state of ["done", "failed"]) { const calls = []; const db = { collection(name) { return { async deleteMany(filter) { calls.push({ name, filter }); return { acknowledged: true, deletedCount: 4 }; } }; } }; const result = response(); await createQueueController({ config: settings, getDb: async () => db }).clearState({ body: { state }, query: { q: "arbitrary-filter", filename: media }, }, result, error => { throw error; }); assert.deepEqual(calls, [{ name: state, filter: {} }]); assert.equal(result.location, `/status?state=${state}`); assert.equal(await fs.readFile(media, "utf8"), "downloaded-video-fixture"); } }); test("clear-state database rejection and uncertain deletion reach the error handler without success redirects", async () => { for (const failure of ["rejected", "unacknowledged", "missing", "null", "no-acknowledgement"]) { const original = new Error("private database write detail"); const db = { collection() { return { async deleteMany() { if (failure === "rejected") throw original; if (failure === "missing") return undefined; if (failure === "null") return null; if (failure === "no-acknowledgement") return { deletedCount: 4 }; return { acknowledged: false }; } }; } }; const result = response(); let error; await createQueueController({ getDb: async () => db }).clearState({ body: { state: "queued" } }, result, received => { error = received; }); assert.ok(error instanceof Error, failure); if (failure === "rejected") assert.equal(error, original); assert.equal(result.location, undefined); assert.equal(result.data, undefined); assert.equal(result.headers["Cache-Control"], "no-store"); } }); function queueReadFixture({ recordsAllowed = true } = {}) { const reads = []; const db = { collection(name) { if (name === "settings") return { async findOne(filter, options) { reads.push({ type: "global", filter, options }); return { captcha_blocked: true, pause_reason: "resolution", token: "private-setting" }; } }; return { async countDocuments(filter, options) { reads.push({ type: "count", name, filter, options }); return name === "queue" ? (filter.processing === true ? 1 : 2) : 3; }, find(filter, options) { assert.equal(recordsAllowed, true, "summary must not load job records"); const read = { type: "records", name, filter, options }; reads.push(read); const cursor = { sort(value) { read.sort = value; return cursor; }, skip(value) { read.skip = value; return cursor; }, limit(value) { read.limit = value; return cursor; }, async toArray() { return [{ _id: "queued", filename: "TitleS001E009_engsub", token: "cookie=private-job-token", output_log: "Captured private-job-token", created_at: CREATED }]; }, }; return cursor; }, }; } }; return { db, reads }; } test("status-data includes the activity service snapshot and still returns a bounded sanitized selected page", async () => { const fixture = queueReadFixture(); const activity = { workers: [{ key: "pm2:1", name: "proxer-worker-1", jobs: [] }], unassigned: [], truncated: false, workersTruncated: false, available: true, }; const settings = { outputDir: "/fixture-output", maxSeriesEpisodes: 500 }; let activityCalls = 0; const controller = createQueueController({ config: settings, getDb: async () => fixture.db, readActivity: async (db, options) => { activityCalls += 1; assert.equal(db, fixture.db); assert.equal(options.settings, settings); return activity; }, }); const result = response(); await controller.statusData({ query: {} }, result, error => { throw error; }); assert.equal(activityCalls, 1); assert.equal(result.data.activity, activity); assert.deepEqual(result.data.filters, { state: "queued", q: "" }); assert.equal(result.data.items[0].token, undefined); assert.doesNotMatch(JSON.stringify(result.data), /private-job-token|private-setting/); assert.equal(result.headers["Cache-Control"], "no-store"); const reads = fixture.reads.filter(read => read.type === "records"); assert.deepEqual(reads, [{ type: "records", name: "queue", filter: { processing: { $ne: true } }, options: { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS }, sort: { created_at: 1, _id: 1 }, skip: 0, limit: 25, }]); }); test("status-summary remains count-only and never invokes activity, inventory, job reads, or filesystem checks", async () => { const fixture = queueReadFixture({ recordsAllowed: false }); const settings = { get outputDir() { throw new Error("Summary must not inspect output files"); } }; const controller = createQueueController({ config: settings, getDb: async () => fixture.db, readActivity: async () => { assert.fail("Summary must not request activity or supervisor inventory"); }, }); const result = response(); await controller.statusSummary({}, result, error => { throw error; }); assert.deepEqual(result.data, { counts: { queued: 2, processing: 1, done: 3, failed: 3 }, global: { captcha_blocked: true, pause_reason: "resolution" }, }); assert.equal(result.headers["Cache-Control"], "no-store"); assert.equal(fixture.reads.filter(read => read.type === "count").length, 4); assert.equal(fixture.reads.filter(read => read.type === "records").length, 0); assert.ok(fixture.reads.every(read => read.options.maxTimeMS === QUERY_TIMEOUT_MS)); });