phase 2 rework
This commit is contained in:
1 parent
20054198f3
commit
b397ea9256
44 files changed
+5506
-1355
No files matched your search
@@ -2,9 +2,11 @@
|
||||
|
||||
Express/EJS submission and status pages, a MongoDB episode queue, Node workers managed by PM2, and Python download entrypoints.
|
||||
|
||||
## Phase 1: reliable execution and a protected streaming boundary
|
||||
## Phase 2: dashboard, worker activity, and reusable session tokens
|
||||
|
||||
The Phase 1 changes preserve the original files in `scripts/lib/`, the streaming call sequence, existing CLI entrypoint names, and the established filename conventions. The top bar redesign, full modular execution architecture, expiring job ownership, automatic retries, and enforced bandwidth controls are later phases. See [the rollout roadmap](docs/rollout-roadmap.md).
|
||||
The interface has a responsive top bar, a default Dashboard, active-download cards per worker, a searchable paginated queue with state-specific clearing controls, and numbered quick-add workers. Series submissions include a separate Season field and an exact filename preview. A supplied token is saved in MongoDB after a successful download-access check and checked again on every new submission. See the [refinement guide and verification report](docs/phase-2-refinements.md).
|
||||
|
||||
The user confirmed successful series and single-episode workflows with the first Phase 2 UI, after previously confirming that the verification pause retained and retried the affected episode and completed the queue. These refinements preserve that execution behavior and every original file in `scripts/lib/`. Worker identity is diagnostic metadata; durable ownership, recovery, shared execution modules, and enforced bandwidth controls remain in the [later rollout phases](docs/rollout-roadmap.md).
|
||||
|
||||
The current worker records success only when Python exits with code 0, emits exactly one valid completed result, and produces a nonempty regular output file. This is a completion contract, not full media-integrity verification. The protected stream library still writes directly to the target file and cannot resume a partial transfer.
|
||||
|
||||
@@ -50,7 +52,7 @@ The test runner checks the entire protected directory before and after all suite
|
||||
|
||||
Set `TEST_PYTHON` to an absolute interpreter path when the test interpreter should differ from `python3`. The protected check covers all seven original files, their executable flags, exact directory entries, additions, deletions, and symlinks. The frozen baseline must not be regenerated to hide an unexpected change.
|
||||
|
||||
The current Phase 1 run, including the unresolved-link pause fix, passed **158 tests** (114 Node and 44 Python). See the [verification report](docs/phase-1-verification.md) for coverage, runtime versions, and the remaining deployment checks.
|
||||
The current refinement run passed **258 tests** (214 Node and 44 Python), plus **42 browser checks**. The [current refinement report](docs/phase-2-refinements.md) records the expanded verification and deployment scope; the [initial UI report](docs/phase-2-ui.md) and [Phase 1 report](docs/phase-1-verification.md) preserve their earlier baselines.
|
||||
|
||||
## Start locally
|
||||
|
||||
@@ -66,6 +68,29 @@ npm run worker
|
||||
|
||||
The worker-management page creates workers using the configured checkout and current Node interpreter. It only lists and controls PM2 processes whose executable is this checkout's `queue_worker.js`; unrelated services are excluded. PM2 IDs are resolved on the server. Saving the host-wide PM2 process list is a deployment operation (`pm2 save` as the download account), so the web control is removed.
|
||||
|
||||
## Using the interface
|
||||
|
||||
- **Dashboard** (`/`): see current claims by worker, waiting/active/history counts, and the latest five completed and five failed-attempt records. Each summary links to the relevant full queue or history.
|
||||
- **New download** (`/download`): choose Series or Single episode and check the filename preview. Series has a Season field, defaulting to 1. Leave the token blank to use the saved token, or paste a replacement. Each submission checks access before adding any jobs.
|
||||
- **Queue** (`/status`): choose Queued, Active, Completed, or Failed attempts. Search filenames and choose 10, 25, or 50 results per page. Refresh preserves expanded logs, filters, and unsent search input. The danger button beside Refresh clears the selected waiting/history state after confirmation; Active has no clear operation.
|
||||
- **Workers** (`/pm2`): use **Quick add worker** for `proxer-worker-1`, `proxer-worker-2`, and subsequent numbers. The counter persists in MongoDB and avoids existing PM2 names. Custom names remain available. Select a worker to inspect metrics and logs or start/stop/restart/delete it. Disruptive commands ask for confirmation.
|
||||
|
||||
The dashboard and queue show a card for each managed worker. A newly claimed job carries a startup identity so it can be matched to the correct live process. Legacy claims and ambiguous/stale assignments remain visible without guessing. File sizes describe the current file on disk; there is no guessed percentage or speed. Restart workers after installing this refinement so subsequent claims carry identity metadata.
|
||||
|
||||
The status API returns one selected page in `items`, together with `counts`, `pagination`, `filters`, `global`, and bounded `activity`. It accepts `state`, `q`, `page`, and `pageSize`. `/status-summary` stays count-only, while `/dashboard-data` returns overview counts, activity, and bounded recent history. See the [API details](docs/phase-2-refinements.md#api-and-data-additions).
|
||||
|
||||
Queue/history clearing applies to all records in the selected state, including those outside the current filter or page. Clearing history keeps media files on disk. Active processing flags remain protected.
|
||||
|
||||
### Saved session token
|
||||
|
||||
The cache is a single document in the existing MongoDB `settings` collection (`_id: "proxer-session-token"`), shared by this application deployment. The token field is always empty when a page is rendered; safe metadata reports whether a token is saved and the last successful check. No token is sent back in HTML/JSON, stored in browser storage, or added to a URL.
|
||||
|
||||
Each submission checks the first requested episode's source page using the configured cookie and stream preference. It requires the same positive embed-code evidence as the protected resolver, with a 12-second timeout and 1 MiB response limit. It performs no media transfer and never follows redirects with the cookie. HTTP 200 alone is insufficient.
|
||||
|
||||
A rejected token prompts for a replacement and prevents enqueueing. Verification challenges, missing sources, unfamiliar responses, and connection failures have separate warnings and keep the saved token. A successful replacement is saved only after validation. Revision checks prevent an older in-flight request from erasing or overwriting a newer saved token.
|
||||
|
||||
This validates download access at submission time; it does not prove account identity or guarantee the token will remain usable during a long queue. Existing queued jobs retain their original token. The existing worker pause/verification flow still handles failures after enqueueing. MongoDB access and backups protect the cached credential just as they protect credentials already held in queue records.
|
||||
|
||||
## Submission and filenames
|
||||
|
||||
Only HTTPS Proxer watch URLs on `proxer.me` or `www.proxer.me` are accepted. The URL must identify a positive integer series ID, positive integer episode, and one of `engsub`, `engdub`, `gersub`, or `gerdub`. Fragments and an optional trailing slash are normalized away. Query parameters, credentials in URLs, and custom ports are rejected.
|
||||
@@ -74,10 +99,11 @@ Only HTTPS Proxer watch URLs on `proxer.me` or `www.proxer.me` are accepted. The
|
||||
|---|---|
|
||||
| Web video with title | Explicit legacy `filename`, then the form's `name` |
|
||||
| Web video without title | `{id} E{episode} {language}` |
|
||||
| Web series | `{trimmedNameOrId}E{paddedEpisode}_{language}` |
|
||||
| Web series with Season | `{trimmedNameOrId}S{season:03}E{episode:03}_{language}` |
|
||||
| Legacy web/API series without `season` | `{trimmedNameOrId}E{paddedEpisode}_{language}` |
|
||||
| Standalone series CLI | `{name}_Episode_{episode}_{language}` |
|
||||
|
||||
Web series padding uses the width of the highest requested episode. All destinations are validated before a batch is queued. Filenames must be single names inside the configured directory; symlink and non-file targets are rejected. The corrected video-title fallback is intentional. [Compatibility fixtures](tests/fixtures/legacy-contracts.json) record the original conventions.
|
||||
The current form always submits a season: for example, `My SeriesS001E009_engsub.mp4`. Season and episode use a minimum of three digits and expand beyond 999. Season 0 represents specials. Season affects only the filename, not the source episode numbers; there is no automatic season-to-absolute-episode mapping. Enter the title without an existing season/episode suffix. Legacy clients that omit `season` retain padding based on the highest requested episode. Existing files and queue names are not renamed. All destinations are validated before a batch is queued. Filenames must be single names inside the configured directory; symlink and non-file targets are rejected. The corrected video-title fallback is intentional. [Compatibility fixtures](tests/fixtures/legacy-contracts.json) record the original conventions.
|
||||
|
||||
## Python CLI compatibility
|
||||
|
||||
@@ -111,6 +137,8 @@ The blanket `clear-processing` operation is disabled and returns HTTP 409. Phase
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Phase 2 refinements, token cache, and verification](docs/phase-2-refinements.md)
|
||||
- [Initial Phase 2 interface baseline](docs/phase-2-ui.md)
|
||||
- [Phase 1 baseline and compatibility boundary](docs/phase-1-baseline.md)
|
||||
- [Phase 1 verification report](docs/phase-1-verification.md)
|
||||
- [Unresolved-link pause fix and recovery](docs/phase-1-resolution-fix.md)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"use strict";
|
||||
|
||||
const { getDb } = require("../lib/mongo");
|
||||
const { config } = require("../lib/config");
|
||||
const { STATUS_READ_PROJECTION, toPublicJob } = require("../lib/jobValidation");
|
||||
const { STATES, QUERY_TIMEOUT_MS, stateQuery, publicGlobal } = require("../lib/statusQuery");
|
||||
const { readActivity } = require("../lib/activity");
|
||||
|
||||
const RECENT_LIMIT = 5;
|
||||
|
||||
async function readSummary(db) {
|
||||
const [totals, record] = await Promise.all([
|
||||
Promise.all(STATES.map(state => {
|
||||
const { collection, filter } = stateQuery(state);
|
||||
return db.collection(collection).countDocuments(filter, { maxTimeMS: QUERY_TIMEOUT_MS });
|
||||
})),
|
||||
db.collection("settings").findOne({ _id: "global" }, {
|
||||
projection: { captcha_blocked: 1, pause_reason: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
|
||||
}),
|
||||
]);
|
||||
return { counts: Object.fromEntries(STATES.map((state, index) => [state, totals[index]])), global: publicGlobal(record) };
|
||||
}
|
||||
|
||||
async function readRecent(db, state) {
|
||||
const { collection, filter, sort } = stateQuery(state);
|
||||
const records = await db.collection(collection).find(filter, {
|
||||
projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS,
|
||||
}).sort(sort).limit(RECENT_LIMIT).toArray();
|
||||
return records.map(toPublicJob);
|
||||
}
|
||||
|
||||
function createDashboardController(dependencies = {}) {
|
||||
const connect = dependencies.getDb || getDb;
|
||||
const settings = dependencies.config || config;
|
||||
const activityReader = dependencies.readActivity || readActivity;
|
||||
|
||||
async function readDashboard() {
|
||||
const db = await connect();
|
||||
const [summary, activity, done, failed] = await Promise.all([
|
||||
readSummary(db), activityReader(db, { settings }), readRecent(db, "done"), readRecent(db, "failed"),
|
||||
]);
|
||||
return { ...summary, activity, recent: { done, failed } };
|
||||
}
|
||||
|
||||
async function dashboard(req, res, next) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
try {
|
||||
return res.render("dashboard", { title: "Dashboard", activePage: "dashboard", ...await readDashboard() });
|
||||
} catch (error) { return next(error); }
|
||||
}
|
||||
|
||||
async function dashboardData(req, res, next) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
try { return res.json(await readDashboard()); }
|
||||
catch (error) { return next(error); }
|
||||
}
|
||||
|
||||
return { dashboard, dashboardData, readDashboard };
|
||||
}
|
||||
|
||||
module.exports = { ...createDashboardController(), createDashboardController, readSummary, RECENT_LIMIT };
|
||||
@@ -1,6 +1,10 @@
|
||||
const { spawn } = require('node:child_process');
|
||||
const path = require('node:path');
|
||||
const { config } = require('../lib/config');
|
||||
const { getDb } = require('../lib/mongo');
|
||||
|
||||
const WORKER_SEQUENCE_ID = 'worker-name-sequence';
|
||||
const QUERY_TIMEOUT_MS = 5000;
|
||||
|
||||
function runPm2Command(args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -47,6 +51,8 @@ function normalizeProcess(process) {
|
||||
const env = process.pm2_env || {};
|
||||
const cpu = process.monit?.cpu;
|
||||
const memory = process.monit?.memory;
|
||||
const startedAt = typeof env.pm_uptime === 'number' && Number.isFinite(env.pm_uptime) && env.pm_uptime > 0
|
||||
? new Date(env.pm_uptime) : null;
|
||||
return {
|
||||
name: String(process.name || env.name || '—'),
|
||||
pid: process.pid || '—',
|
||||
@@ -55,6 +61,7 @@ function normalizeProcess(process) {
|
||||
cpu: typeof cpu === 'number' ? `${cpu.toFixed(1)}%` : '—',
|
||||
memoryMB: typeof memory === 'number' ? `${Math.round(memory / 1024 / 1024)} MB` : '—',
|
||||
uptime: humanUptime(env.pm_uptime),
|
||||
startedAtISO: startedAt && Number.isFinite(startedAt.getTime()) ? startedAt.toISOString() : null,
|
||||
execPath: env.pm_exec_path || '—',
|
||||
};
|
||||
}
|
||||
@@ -63,7 +70,7 @@ function validName(name) {
|
||||
return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all';
|
||||
}
|
||||
|
||||
function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
|
||||
function createPm2Controller({ run = runPm2Command, settings = config, getDb: connect = getDb } = {}) {
|
||||
function managed(process) {
|
||||
const executable = process.pm2_env?.pm_exec_path;
|
||||
return typeof executable === 'string' && path.resolve(executable) === settings.workerScript;
|
||||
@@ -87,15 +94,77 @@ function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
|
||||
return { ...normalizeProcess(matches[0]), pm_id: String(id) };
|
||||
}
|
||||
|
||||
async function listManagedProcesses() {
|
||||
return (await processes()).filter(managed).map(normalizeProcess);
|
||||
}
|
||||
|
||||
function createArguments(name) {
|
||||
return ['start', settings.workerScript, '--name', name, '--cwd', settings.projectRoot,
|
||||
'--interpreter', process.execPath, '--kill-timeout', '10000'];
|
||||
}
|
||||
|
||||
async function reserveWorkerName(existing) {
|
||||
let highest = 0;
|
||||
for (const worker of existing) {
|
||||
const match = /^proxer-worker-(\d+)$/.exec(worker.name || worker.pm2_env?.name || '');
|
||||
if (!match) continue;
|
||||
const number = Number(match[1]);
|
||||
if (!Number.isSafeInteger(number) || number >= Number.MAX_SAFE_INTEGER) return null;
|
||||
highest = Math.max(highest, number);
|
||||
}
|
||||
const collection = (await connect()).collection('settings');
|
||||
const seed = { $max: { value: highest } };
|
||||
let seeded;
|
||||
try {
|
||||
seeded = await collection.updateOne({ _id: WORKER_SEQUENCE_ID }, seed, { upsert: true, maxTimeMS: QUERY_TIMEOUT_MS });
|
||||
} catch (error) {
|
||||
// Two first requests can race to create the sequence. The _id index
|
||||
// selects one winner; the other request can safely seed that same row.
|
||||
if (error?.code !== 11000) throw error;
|
||||
seeded = await collection.updateOne({ _id: WORKER_SEQUENCE_ID }, seed, { maxTimeMS: QUERY_TIMEOUT_MS });
|
||||
}
|
||||
if (seeded?.acknowledged !== true) throw new Error('Worker number could not be reserved.');
|
||||
const reserved = await collection.findOneAndUpdate({
|
||||
_id: WORKER_SEQUENCE_ID, value: { $gte: 0, $lt: Number.MAX_SAFE_INTEGER },
|
||||
}, { $inc: { value: 1 } }, {
|
||||
returnDocument: 'after', includeResultMetadata: false, projection: { value: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
|
||||
});
|
||||
if (!reserved || !Number.isSafeInteger(reserved.value) || reserved.value < 1) return null;
|
||||
return `proxer-worker-${reserved.value}`;
|
||||
}
|
||||
|
||||
async function quickAdd(req, res) {
|
||||
if (req.body && (typeof req.body !== 'object' || Array.isArray(req.body) || Object.keys(req.body).length)) {
|
||||
return res.status(400).json({ ok: false, error: 'Quick add chooses the worker name and executable automatically.' });
|
||||
}
|
||||
let name;
|
||||
try {
|
||||
// Inspect every process, including unrelated services, before reserving
|
||||
// a persistent number. Deleting a worker never reuses its number.
|
||||
name = await reserveWorkerName(await processes());
|
||||
if (!name) return res.status(409).json({ ok: false, error: 'A numbered worker name could not be reserved. Use a custom worker name or check the saved worker counter.' });
|
||||
} catch {
|
||||
return res.status(503).json({ ok: false, error: 'Quick add requires the worker supervisor and database to be available. Try again after checking the service.' });
|
||||
}
|
||||
try {
|
||||
const { code } = await run(createArguments(name));
|
||||
return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code, name,
|
||||
message: code === 0 ? `${name} was created and started.` : `Could not start ${name}. Check the worker list and supervisor before trying again.` });
|
||||
} catch {
|
||||
return res.status(503).json({ ok: false, name,
|
||||
error: `Could not confirm whether ${name} started. Refresh the worker list before trying again.` });
|
||||
}
|
||||
}
|
||||
|
||||
async function getManage(req, res, next) {
|
||||
try {
|
||||
res.render('pm2', { title: 'Proxer Workers', processes: (await processes()).filter(managed).map(normalizeProcess) });
|
||||
res.render('pm2', { title: 'Proxer Workers', processes: await listManagedProcesses() });
|
||||
} catch (error) { next(error); }
|
||||
}
|
||||
|
||||
async function listJson(req, res) {
|
||||
try {
|
||||
res.json({ ok: true, processes: (await processes()).filter(managed).map(normalizeProcess) });
|
||||
res.json({ ok: true, processes: await listManagedProcesses() });
|
||||
} catch {
|
||||
res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' });
|
||||
}
|
||||
@@ -119,8 +188,7 @@ function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
|
||||
if ((await processes()).some((process) => (process.name || process.pm2_env?.name) === name)) {
|
||||
return res.status(409).json({ ok: false, error: 'This process name is already in use.' });
|
||||
}
|
||||
args = ['start', settings.workerScript, '--name', name, '--cwd', settings.projectRoot,
|
||||
'--interpreter', process.execPath, '--kill-timeout', '10000'];
|
||||
args = createArguments(name);
|
||||
} else {
|
||||
const worker = await resolveManagedProcess(name);
|
||||
if (!worker) return res.status(404).json({ ok: false, error: 'The selected downloader worker was not found.' });
|
||||
@@ -134,7 +202,7 @@ function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
return { getManage, listJson, postCommand, resolveManagedProcess };
|
||||
return { getManage, listJson, postCommand, quickAdd, resolveManagedProcess, listManagedProcesses };
|
||||
}
|
||||
|
||||
module.exports = { ...createPm2Controller(), createPm2Controller, normalizeProcess, validName };
|
||||
+142
-36
@@ -1,50 +1,118 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const { getDb } = require("../lib/mongo");
|
||||
const { config } = require("../lib/config");
|
||||
const {
|
||||
ValidationError, STATUS_READ_PROJECTION, buildQueueJobs, toPublicJob, validateOutputTarget,
|
||||
ValidationError, STATUS_READ_PROJECTION, planQueueJobs, toPublicJob, validateOutputTarget,
|
||||
} = require("../lib/jobValidation");
|
||||
const {
|
||||
STATES, QUERY_TIMEOUT_MS, parseStatusQuery, stateQuery, statusFilter, publicGlobal,
|
||||
} = require("../lib/statusQuery");
|
||||
const { readActivity } = require("../lib/activity");
|
||||
const { createSessionTokenService, SessionTokenError } = require("../lib/sessionToken");
|
||||
|
||||
function createQueueController(dependencies = {}) {
|
||||
const connect = dependencies.getDb || getDb;
|
||||
const settings = dependencies.config || config;
|
||||
const now = dependencies.now || (() => new Date());
|
||||
const activityReader = dependencies.readActivity || readActivity;
|
||||
const sessionTokens = dependencies.sessionTokens || createSessionTokenService({ getDb: connect, settings, now });
|
||||
|
||||
function formModel(body = {}, formError = null, tokenStatus = { available: false, state: "unknown" }) {
|
||||
const input = body && typeof body === "object" && !Array.isArray(body) ? body : {};
|
||||
const values = {
|
||||
mode: input.mode === "video" ? "video" : "series",
|
||||
id: "", url: "", name: "", language: "engsub", season: "1", episode_from: "", episode_to: "",
|
||||
};
|
||||
for (const [key, limit] of Object.entries({ id: 16, url: 2048, name: 255, season: 16, episode_from: 16, episode_to: 16 })) {
|
||||
if (typeof input[key] !== "string") continue;
|
||||
let value = input[key];
|
||||
// Never re-render credentials, including a token accidentally pasted into
|
||||
// another field. The password input is deliberately absent from values.
|
||||
if (typeof input.token === "string" && input.token) value = value.split(input.token).join("[redacted]");
|
||||
values[key] = value.slice(0, limit).replace(/[\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/gu, "");
|
||||
}
|
||||
if (["engsub", "engdub", "gersub", "gerdub"].includes(input.language)) values.language = input.language;
|
||||
return {
|
||||
title: "New download", activePage: "download", values, formError, tokenStatus,
|
||||
maxSeriesEpisodes: settings.maxSeriesEpisodes, outputDir: settings.outputDir, details: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function safeTokenStatus() {
|
||||
try { return await sessionTokens.readStatus(); }
|
||||
catch { return { available: false, state: "unavailable" }; }
|
||||
}
|
||||
|
||||
async function home(req, res) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
return res.render("index", formModel({ mode: req.query?.mode }, null, await safeTokenStatus()));
|
||||
}
|
||||
|
||||
async function enqueue(req, res) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
try {
|
||||
const jobs = await buildQueueJobs(req.body, settings, now);
|
||||
const planned = await planQueueJobs(req.body, settings, now);
|
||||
const access = await sessionTokens.resolveForEnqueue(req.body.token, { url: planned[0].url });
|
||||
const jobs = planned.map(job => ({ ...job, token: access.cookie }));
|
||||
const db = await connect();
|
||||
if (jobs.length === 1 && req.body.mode === "video") {
|
||||
await db.collection("queue").insertOne(jobs[0]);
|
||||
const result = await db.collection("queue").insertOne(jobs[0]);
|
||||
if (result?.acknowledged !== true) throw new Error("The queue insertion was not acknowledged.");
|
||||
} else {
|
||||
await db.collection("queue").bulkWrite(jobs.map(document => ({ insertOne: { document } })));
|
||||
const result = await db.collection("queue").bulkWrite(jobs.map(document => ({ insertOne: { document } })));
|
||||
if (result?.isOk?.() !== true || result.insertedCount !== jobs.length) throw new Error("The batch insertion was not confirmed.");
|
||||
}
|
||||
return res.redirect("/status");
|
||||
return res.redirect(`/status?state=queued&added=${jobs.length}`);
|
||||
} catch (error) {
|
||||
const invalid = error instanceof ValidationError;
|
||||
return res.status(invalid ? 400 : 500).render("error", {
|
||||
title: "Enqueue failed",
|
||||
message: invalid ? error.message : "The download could not be queued. Check the service configuration and try again.",
|
||||
if (error instanceof SessionTokenError) {
|
||||
const status = error.code === "storage" ? { available: false, state: "unavailable" } : await safeTokenStatus();
|
||||
return res.status(error.httpStatus).render("index", formModel(req.body, error.message, status));
|
||||
}
|
||||
if (error instanceof ValidationError) return res.status(400).render("index", formModel(req.body, error.message));
|
||||
return res.status(500).render("error", {
|
||||
title: "Enqueue failed", activePage: "download",
|
||||
message: "The queue submission could not be confirmed. Check the queue before retrying to avoid duplicate downloads, and check the service configuration if the problem continues.",
|
||||
details: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function readStatus() {
|
||||
async function readSummary(db) {
|
||||
const [totals, record] = await Promise.all([
|
||||
Promise.all(STATES.map(state => {
|
||||
const { collection, filter } = stateQuery(state);
|
||||
return db.collection(collection).countDocuments(filter, { maxTimeMS: QUERY_TIMEOUT_MS });
|
||||
})),
|
||||
db.collection("settings").findOne({ _id: "global" }, {
|
||||
projection: { captcha_blocked: 1, pause_reason: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
|
||||
}),
|
||||
]);
|
||||
return { counts: Object.fromEntries(STATES.map((state, index) => [state, totals[index]])), global: publicGlobal(record) };
|
||||
}
|
||||
|
||||
async function readStatus(query) {
|
||||
const filters = parseStatusQuery(query);
|
||||
const db = await connect();
|
||||
const queries = [
|
||||
["queue", { processing: { $ne: true } }, { created_at: 1 }],
|
||||
["queue", { processing: true }, { created_at: 1 }],
|
||||
["done", {}, { finished_at: -1 }],
|
||||
["failed", {}, { failed_at: -1 }],
|
||||
];
|
||||
const lists = await Promise.all(queries.map(async ([collection, filter, sort]) => {
|
||||
const records = await db.collection(collection).find(filter, { projection: STATUS_READ_PROJECTION }).sort(sort).toArray();
|
||||
return records.map(toPublicJob);
|
||||
}));
|
||||
const [queued, processing, done, failed] = lists;
|
||||
// Asynchronous file checks avoid blocking the web process. Pagination follows in Phase 2.
|
||||
for (const job of [...processing, ...done]) {
|
||||
const selected = stateQuery(filters.state);
|
||||
const filter = statusFilter(filters.state, filters.q);
|
||||
const [summary, matchingTotal, activity] = await Promise.all([
|
||||
readSummary(db),
|
||||
filters.q ? db.collection(selected.collection).countDocuments(filter, { maxTimeMS: QUERY_TIMEOUT_MS }) : null,
|
||||
activityReader(db, { settings }),
|
||||
]);
|
||||
const total = matchingTotal ?? summary.counts[filters.state];
|
||||
const totalPages = Math.max(1, Math.ceil(total / filters.pageSize));
|
||||
const page = Math.min(filters.page, totalPages);
|
||||
const records = await db.collection(selected.collection)
|
||||
.find(filter, { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS })
|
||||
.sort(selected.sort).skip((page - 1) * filters.pageSize).limit(filters.pageSize).toArray();
|
||||
const items = records.map(toPublicJob);
|
||||
// Only the visible page needs filesystem metadata. A summary request never
|
||||
// reads queue records, download logs, cookies, or output files.
|
||||
if (["processing", "done"].includes(filters.state)) {
|
||||
await Promise.all(items.map(async job => {
|
||||
try {
|
||||
const target = await validateOutputTarget(settings.outputDir, job.filename);
|
||||
const stat = await fs.lstat(target);
|
||||
@@ -52,30 +120,48 @@ function createQueueController(dependencies = {}) {
|
||||
} catch {
|
||||
job.fileSize = null;
|
||||
}
|
||||
}));
|
||||
}
|
||||
const global = await db.collection("settings").findOne({ _id: "global" }, { projection: { captcha_blocked: 1, pause_reason: 1 } });
|
||||
return {
|
||||
queued, processing, done, failed,
|
||||
global: {
|
||||
captcha_blocked: global?.captcha_blocked === true,
|
||||
pause_reason: ["authentication", "resolution"].includes(global?.pause_reason) ? global.pause_reason : null,
|
||||
},
|
||||
items, ...summary, activity,
|
||||
pagination: { page, pageSize: filters.pageSize, total, totalPages },
|
||||
filters: { state: filters.state, q: filters.q },
|
||||
};
|
||||
}
|
||||
|
||||
function queryError(error, res, json) {
|
||||
if (!(error instanceof ValidationError)) return false;
|
||||
if (json) res.status(400).json({ ok: false, error: error.message });
|
||||
else res.status(400).render("error", { title: "Invalid queue filters", activePage: "queue", message: error.message, details: null });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function status(req, res, next) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
try {
|
||||
const snapshot = await readStatus();
|
||||
return res.render("status", { ...snapshot, finished: snapshot.done });
|
||||
const snapshot = await readStatus(req.query);
|
||||
const addedText = req.query?.added;
|
||||
const added = typeof addedText === "string" && /^[1-9]\d{0,4}$/.test(addedText)
|
||||
&& Number(addedText) <= settings.maxSeriesEpisodes ? Number(addedText) : 0;
|
||||
return res.render("status", { title: "Queue", activePage: "queue", ...snapshot, added });
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
if (!queryError(error, res, false)) return next(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function statusData(req, res, next) {
|
||||
try {
|
||||
res.set("Cache-Control", "no-store");
|
||||
return res.json(await readStatus());
|
||||
try {
|
||||
return res.json(await readStatus(req.query));
|
||||
} catch (error) {
|
||||
if (!queryError(error, res, true)) return next(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function statusSummary(req, res, next) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
try {
|
||||
return res.json(await readSummary(await connect()));
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
}
|
||||
@@ -83,7 +169,7 @@ function createQueueController(dependencies = {}) {
|
||||
|
||||
function clearProcessing(req, res) {
|
||||
return res.status(409).render("error", {
|
||||
title: "Active downloads are protected",
|
||||
title: "Active downloads are protected", activePage: "queue",
|
||||
message: "Active processing flags cannot be cleared safely while downloads may still be running. Stop the affected worker and verify that its download has ended before performing recovery.",
|
||||
details: null,
|
||||
});
|
||||
@@ -102,7 +188,27 @@ function createQueueController(dependencies = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
return { enqueue, status, statusData, clearProcessing, clearCaptcha };
|
||||
async function clearState(req, res, next, legacyState = undefined) {
|
||||
res.set("Cache-Control", "no-store");
|
||||
const state = legacyState ?? req.body?.state;
|
||||
if (typeof state !== "string" || !STATES.includes(state)) {
|
||||
return res.status(400).render("error", {
|
||||
title: "Choose a queue state", activePage: "queue",
|
||||
message: "Select Waiting, Completed, or Failed attempts before clearing records.", details: null,
|
||||
});
|
||||
}
|
||||
if (state === "processing") return clearProcessing(req, res);
|
||||
try {
|
||||
const { collection, filter } = stateQuery(state);
|
||||
const db = await connect();
|
||||
// Search text and pagination never broaden this to active claims.
|
||||
const result = await db.collection(collection).deleteMany(filter);
|
||||
if (result?.acknowledged !== true) throw new Error("The clear operation was not acknowledged.");
|
||||
return res.redirect(`/status?state=${state}`);
|
||||
} catch (error) { return next(error); }
|
||||
}
|
||||
|
||||
return { home, enqueue, status, statusData, statusSummary, clearState, clearProcessing, clearCaptcha };
|
||||
}
|
||||
|
||||
module.exports = { ...createQueueController(), createQueueController };
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
Verification date: 23 October 2026.
|
||||
|
||||
**Current result: all 158 tests passed, with no failures, cancellations, or skips.** This includes the unresolved-link pause fix following the user's report of successive failed episodes. The protected library matched the reviewed baseline before and after the integrated run, and an independent check passed afterward. The initial Phase 1 release passed 141 tests.
|
||||
**Phase 1 release result: all 158 tests passed, with no failures, cancellations, or skips.** This includes the unresolved-link pause fix following the user's report of successive failed episodes. The protected library matched the reviewed baseline before and after the integrated run, and an independent check passed afterward. The initial Phase 1 release passed 141 tests. Later UI verification is recorded in the [Phase 2 report](phase-2-ui.md).
|
||||
|
||||
The work is available as uncommitted local changes on `phase-1-reliability`, based on upstream commit `211bfd174dd78eac36f3c74411ecaa72f56eec79`. The user installed the initial file update and reported successful episode downloads, followed by an unresolved-link failure that did not pause the queue. This revision fixes that local handling; it has not been checked against the user's live source response or production server. Production validation remains part of the rollout.
|
||||
The work is available as uncommitted local changes on `phase-1-reliability`, based on upstream commit `211bfd174dd78eac36f3c74411ecaa72f56eec79`. The user installed the initial file update and reported successful episode downloads, followed by an unresolved-link failure that did not pause the queue.
|
||||
|
||||
After installing the resolution fix, the user confirmed that downloads paused, waited for confirmation, retried the affected episode, and successfully completed the queue. The supplied log contained the expected structured `resolution` result. This is user-reported deployment validation; the assistant has not accessed the production server or inspected the underlying source response. A resolution result alone does not identify the exact type of verification page.
|
||||
|
||||
## Executed checks
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# Phase 2 refinements: dashboard, worker activity, naming, and session cache
|
||||
|
||||
Implementation date: 23 October 2026.
|
||||
|
||||
The user confirmed that a series and a single episode completed successfully with the first Phase 2 interface, then requested these refinements. This update is applied over `Proxer-Downloader-phase2-ui-update.zip`. It preserves the confirmed verification-pause/retry behavior and the entire original `scripts/lib/` tree.
|
||||
|
||||
## Interface changes
|
||||
|
||||
`/` is now the Dashboard. The top bar links Dashboard, New download (`/download`), Queue, and Workers. Old `/?mode=series` and `/?mode=video` bookmarks redirect to the corresponding form.
|
||||
|
||||
The Dashboard and Queue begin with a horizontally scrollable card strip showing each managed worker's current claims, filename, source episode/language, start time, elapsed time, and current file size. Empty cards distinguish idle, paused, stopped, and uncertain activity. Existing claims without worker metadata appear in a separate unassigned section. Supervisor failure leaves saved claims visible and marks the live inventory unavailable.
|
||||
|
||||
The Dashboard also provides four clickable state totals and the latest five completed and five failed-attempt records. Failed attempts can remain in history after a retained episode subsequently succeeds. Polls run every ten seconds while visible, without duplicate summary polling. Failed refreshes retain the last results and mark them stale.
|
||||
|
||||
The Queue's danger button is beside Refresh and follows the server-selected state and URL:
|
||||
|
||||
| Selected state | Action |
|
||||
|---|---|
|
||||
| Queued | Clear waiting queue |
|
||||
| Active | No destructive action; active downloads are protected |
|
||||
| Completed | Clear completed history |
|
||||
| Failed attempts | Clear failed history |
|
||||
|
||||
Confirmation states that the action applies to all records in that state, including records outside a search/page. History clearing does not remove media. Waiting-job deletion uses `{processing: {$ne: true}}` atomically, so a job claimed before deletion is preserved. The server accepts only the four known states, rejects active clearing, and requires an acknowledged deletion. Navigation/refresh keeps the action disabled while a new state is loading or a refresh has failed.
|
||||
|
||||
Workers offers **Quick add worker**, with server-assigned names `proxer-worker-1`, `proxer-worker-2`, etc. A MongoDB counter is seeded from the highest existing numbered PM2 name, including unrelated processes, then incremented atomically. Deletion/restart does not recycle numbers; a failed creation may leave a gap. Concurrent quick-add submissions reserve different numbers. An optional custom-name form remains available. Existing managed-script and numeric-ID restrictions remain in effect.
|
||||
|
||||
## Series names
|
||||
|
||||
The series form adds Season, default 1. Season 0 is allowed for specials. The title should not already include a season or episode suffix.
|
||||
|
||||
```text
|
||||
Title: My Series
|
||||
Season: 1
|
||||
Episodes: 9–10
|
||||
Language: engsub
|
||||
|
||||
My SeriesS001E009_engsub.mp4
|
||||
My SeriesS001E010_engsub.mp4
|
||||
```
|
||||
|
||||
Season and episode use a minimum of three digits, following the user's requested `{title}S{XXX}E{XXX}` pattern. Larger values expand rather than truncate. The language suffix stays immediately before `.mp4`. Filename previews and server planning use the same format and enforce the existing 255-byte limit including extension.
|
||||
|
||||
Season is filename metadata only. Proxer episode numbers are used unchanged; this update does not map absolute episode numbers into season-relative numbering. Series and season folders are not created. Single-episode explicit/default names, queued filenames, existing files, standalone Python CLI names, and older direct API requests that omit `season` keep their existing behavior.
|
||||
|
||||
The three-digit format is the requested local convention. Plex's [official TV naming guide](https://support.plex.tv/articles/naming-and-organizing-your-tv-show-files/) illustrates `sXXeXX` and separately discusses folder organization; it does not establish a mandatory three-digit width. Test one imported episode against the library's existing scanner and episode ordering.
|
||||
|
||||
## Session cache and access checks
|
||||
|
||||
A blank token field uses the token saved in the existing MongoDB `settings` collection. A supplied token replaces the cache only after a successful source-access check. The page always renders an empty password field and shows only safe metadata: saved/missing/replacement-needed status and last successful check time. Token values are absent from HTML/JSON responses, browser storage, URLs, raw upstream errors, and logs.
|
||||
|
||||
Every submission is checked, including repeated use on the same day. There is no fixed 24-hour expiration assumption or validation bypass based on cache age. Source/filename/output validation happens before the access probe, and no queue write happens until access succeeds.
|
||||
|
||||
The probe requests the first planned canonical HTTPS Proxer watch page using the configured cookie and `stream_choose=proxer-stream`. It requires positive `"code":"..."` evidence matching the protected resolver's source-access contract. It does not download media or alter `scripts/lib/`. Requests are capped at twelve seconds and one MiB; credentials are never forwarded through redirects or to other hosts.
|
||||
|
||||
| Result | Behavior |
|
||||
|---|---|
|
||||
| Positive source-access evidence | Save/revalidate the token, then enqueue with that verified credential |
|
||||
| No cached token and blank field | Ask for a token; add no jobs |
|
||||
| Explicit rejection | Ask for a current token; invalidate the exact rejected cache revision; add no jobs |
|
||||
| CAPTCHA/verification challenge | Ask for verification and a refreshed token; keep cache; add no jobs |
|
||||
| Missing first source | Ask to check series, episode, and language; keep cache; add no jobs |
|
||||
| Network, timeout, rate limit, server error | Report unavailable validation; keep cache; add no jobs |
|
||||
| Unrecognized source response or redirect | Report that access could not be verified; keep cache; add no jobs |
|
||||
| Cache read/write failure | Report unavailable token storage; add no jobs |
|
||||
|
||||
Concurrent updates use revision comparisons, including rotation after successful revalidation. An older rejected check cannot erase a newer saved or successfully revalidated token. A stale successful request cannot overwrite a newer replacement. Each accepted batch uses the credential actually checked for that submission.
|
||||
|
||||
This is a download-access check, not an assertion of account identity. The configured cookie can serve different purposes; Proxer's [published API documentation](https://proxer.me/wiki/Proxer_API/v1) describes a separate API-key/token mechanism. No new API key or login automation is introduced.
|
||||
|
||||
Existing queued jobs keep their original token. Rotation after enqueueing can still trigger the existing worker pause. The cache is shared by this application's database and is covered by the same MongoDB access and backup protection as queued credentials. There is no multi-user token ownership or encryption-key migration in this refinement.
|
||||
|
||||
## API and data additions
|
||||
|
||||
- `GET /dashboard-data`: `{counts, global, activity, recent: {done, failed}}`.
|
||||
- `GET /status-data`: retains the paginated Phase 2 shape and adds `activity`.
|
||||
- `GET /status-summary`: still only `{counts, global}`; no job, log, token, filesystem, or supervisor reads.
|
||||
- `POST /clear-state`: form body `state=queued|done|failed`; `processing` returns 409. Legacy clear endpoints remain scoped to their named states.
|
||||
- `POST /pm2/quick-add`: accepts an empty body and returns the server-assigned worker name on success.
|
||||
- `POST /queue`: `season` is optional for legacy series clients; a blank/missing token now uses the cache. Submission success is reported only after a confirmed insert/batch result. An uncertain queue write instructs the user to inspect the queue before retrying because partial insertion remains possible.
|
||||
|
||||
Activity includes `workers`, `unassigned`, `available`, `truncated`, and `workersTruncated`. Each worker includes safe identity/status fields and bounded public jobs. At most 51 processing records are read to display 50 and detect truncation; at most 50 worker cards are shown. PM2 inventory is cached for ten seconds with a single shared in-flight read. File metadata is read only for displayed active claims and the existing visible processing/completed queue page. Recent history reads at most five records per history state.
|
||||
|
||||
New claims atomically store `{name,pid,host,run_id,started_at}` under `worker`. A match requires the current host, an unambiguous live PID, and compatible worker/process start times. PID reuse, missing identities, and stopped/replaced processes do not create invented attribution. Claim release removes the metadata. This identity is diagnostic; it is not a lease, recovery lock, or new authority to release a claim.
|
||||
|
||||
Two additive settings records are used:
|
||||
|
||||
- `worker-name-sequence`: the highest reserved quick-add number.
|
||||
- `proxer-session-token`: the credential and internal revision plus safe status timestamps.
|
||||
|
||||
No migration of existing queue or history records is required. No dependency versions, Python entrypoints, streaming code, or environment-variable contract change.
|
||||
|
||||
## Verification
|
||||
|
||||
The final integrated `npm test` run passed **258 tests: 214 Node and 44 Python**, with no failures, skips, or cancellations. The protected-tree guard matched all seven original files before and after the run; `git diff --check` passed. Tests use local fixtures and injected database, process, and network interfaces.
|
||||
|
||||
| Suite | Passed |
|
||||
|---|---:|
|
||||
| Python downloader | 44 |
|
||||
| Node-to-Python integration | 5 |
|
||||
| Protected-library guard | 10 |
|
||||
| Runtime services | 25 |
|
||||
| HTTP and WebSocket services | 19 |
|
||||
| Submission, status, and safe templates | 19 |
|
||||
| Worker lifecycle | 39 |
|
||||
| Status query and form model | 16 |
|
||||
| Worker browser behavior | 11 |
|
||||
| Worker attribution and dashboard reads | 14 |
|
||||
| Numbered quick-add | 10 |
|
||||
| Season naming and clear-state integration | 11 |
|
||||
| Token cache and HTTP probe | 24 |
|
||||
| Token/controller integration | 11 |
|
||||
| **Total** | **258** |
|
||||
|
||||
Token tests cover validation on every submission, cache metadata secrecy, explicit rejection versus challenges/network failures, first-source ordering, no queue writes after failed checks, bounded/no-redirect probes, bodyless/error responses, and concurrent replacement/revalidation/invalidation races. Clear-state tests cover a concurrent claim, allowlisted predicates, acknowledgements, and preservation of media. Worker tests preserve the confirmed pause/retry and result-validation behavior.
|
||||
|
||||
A separate Playwright run in Chrome **151.0.7922.34** passed **42 browser checks** with zero JavaScript errors and no external requests. It used the real Express application, queue/dashboard/PM2 controllers, EJS/browser assets, activity service, and token-cache service with synthetic MongoDB/PM2/probe interfaces. Expected test failures deliberately returned HTTP 400, 409, and 503.
|
||||
|
||||
The browser run exercised real series/single form POSTs, season-zero and three-digit preview agreement, saved-token reuse/replacement/rejection, unavailable validation with cache retention, state-specific clearing with cancellation and active protection, quick-add selection and duplicate-command suppression, focused-link/log preservation, and shared-summary isolation. Worker cards show an overflow cue and can be scrolled with the keyboard.
|
||||
|
||||
Desktop views at 1440 × 1000 and all four pages at **390 × 844** and **320 × 844** were checked without page-level horizontal overflow. Screenshots were visually reviewed; the worker strip intentionally scrolls horizontally within its own container. Local runtimes were Node.js 24.19.0 and Python 3.12.14.
|
||||
|
||||
Live production MongoDB, PM2, authenticated media, and Plex import were not exercised in this workspace. The previous production workflow success was reported by the user. The new live access probe requires a valid cookie on the Debian host for acceptance.
|
||||
|
||||
## Deployment and acceptance
|
||||
|
||||
Use the `UPDATE.md`, manifest, read-only checker, and checksums in the refinement ZIP. Wait until both waiting and active counts reach zero, stop the actual web process and currently online managed workers, back up the application/configuration/database, and apply the complete `files/` overlay. Run preflight before copying and postflight plus the protected check/tests afterward. Restart the web process and the workers that were previously online. Reload open browser tabs.
|
||||
|
||||
The web entrypoint is still `server.js`; the worker entrypoint is still `queue_worker.js`. Run both as the download account. Existing `.env`, virtual environment, dependencies, and `/mnt/media/WIP` files stay in place. This refinement needs no new sudo privilege.
|
||||
|
||||
Recommended production acceptance checks:
|
||||
|
||||
1. Open `/`: the Dashboard is the landing page; worker cards show the newly restarted workers.
|
||||
2. Quick-add two workers and verify their distinct incremented names, selection, and logs.
|
||||
3. Submit a short series with Season 1, checking the filename preview. Submit another request with the token blank and confirm reuse.
|
||||
4. Try a rejected token and confirm a visible warning with no new jobs. Restore a valid token. A connection/challenge warning must not claim definite expiry.
|
||||
5. Check a current download card against its worker logs and file size. Verify the existing pause/manual-resume/retry flow still works.
|
||||
6. Switch queue states: confirm the danger action changes; cancel a clear confirmation once, then clear disposable completed/failed history and verify media remains.
|
||||
7. Import one `TitleS001E009_engsub.mp4` sample into the existing Plex library and confirm its series/season/episode mapping.
|
||||
|
||||
The next planned phase remains the shared execution refactor. Durable recovery, safe drain controls, advanced worker policies, and enforced speed limits remain later roadmap work.
|
||||
@@ -0,0 +1,119 @@
|
||||
# Phase 2: interface and bounded status reads
|
||||
|
||||
Implementation and verification date: 23 October 2026.
|
||||
|
||||
**Historical baseline:** this report describes the first Phase 2 ZIP, which the user installed and confirmed worked for both series and single episodes. The subsequent [Phase 2 refinements](phase-2-refinements.md) add the dashboard, worker attribution, season naming, quick-add, and token caching. Use the newer deployment instructions for that update; it requires restarting workers as well as the web process.
|
||||
|
||||
The user authorized this phase after confirming that the Phase 1 resolution fix paused downloads, retained the affected episode, waited for confirmation, retried successfully, and completed the queue. That execution baseline remains intact.
|
||||
|
||||
## What changes
|
||||
|
||||
### Navigation and shared status
|
||||
|
||||
A responsive top bar links New download, Queue, and Workers, with active-page indication, a pending-count badge, and a queue readiness/verification indicator. The interface uses local CSS and JavaScript without the previous Bootstrap CDN dependency. It includes keyboard focus styling, a skip link, labeled controls, and layouts that adapt to narrow screens.
|
||||
|
||||
The existing verification banner is available on every page. It retains the cautious resolution/authentication messages and the existing **Resume after verification** action. A status refresh failure keeps a known pause visible and marks the status unavailable.
|
||||
|
||||
Non-queue pages poll the lightweight summary endpoint. The queue page updates the shared status from its own result, avoiding a second history request. Polling is bounded, avoids overlapping reads, and pauses when the document is hidden.
|
||||
|
||||
### Download submission
|
||||
|
||||
Series and Single episode use native radio controls. Fields for the inactive mode are disabled, so hidden fields cannot interfere with browser validation or submission. A no-JavaScript mode switch is available through ordinary links.
|
||||
|
||||
The form previews the actual legacy filename convention, episode count, and configured destination. Series padding follows the width of the last requested episode. Single-episode language comes from its URL. Client-side range/name checks provide immediate feedback; server validation remains authoritative.
|
||||
|
||||
The token starts as a password field and has an optional show/hide button. It is not written to local/session storage or query parameters. Validation errors retain safe non-secret fields and require the token again. Successfully queued batches redirect to the queued tab with an episode-count notice.
|
||||
|
||||
### Queue and history
|
||||
|
||||
The four state cards select Queued, Active, Completed, or Failed attempts. The selected state has literal case-insensitive filename search, 10/25/50 items per page, stable ordering, and previous/next navigation. Filter state is represented in the URL and works with browser back/forward navigation.
|
||||
|
||||
Automatic refresh preserves unsent search input, existing row nodes, expanded logs, and log scroll positions. Manual refresh and an auto-refresh toggle support close inspection. File sizes use readable binary units; no guessed percentage or transfer rate is shown.
|
||||
|
||||
Failed attempts are labeled as attempts: the verification flow can keep an episode queued and later complete it while its earlier failure remains in history. History/queue clearing controls are grouped below the list and confirm their complete scope. They affect all records in the named state, including records outside the selected filter or page. History clearing leaves media files on disk. Active downloads remain protected from blanket flag clearing.
|
||||
|
||||
### Workers
|
||||
|
||||
The worker page provides named worker creation, a selectable worker list, CPU/memory/uptime details, and the existing start/stop/restart/delete operations. Controls show action results and prevent concurrent commands. Stop, restart, and delete ask for confirmation because they can interrupt work.
|
||||
|
||||
Keyed row updates preserve worker selection and focus during polling. The log viewer supports following output, holding the scroll position while inspecting older lines, clearing only the visible log, and reconnecting. Logs are rendered as text, bounded to 64 KiB of UTF-8 content. Switching workers closes the previous subscription and rejects delayed events from an obsolete socket.
|
||||
|
||||
These controls use the established server restriction to this checkout's managed workers. This phase does not introduce worker limits, bandwidth caps, new persisted settings, or automatic recovery.
|
||||
|
||||
## Status API
|
||||
|
||||
`GET /status-data` and the server-rendered `/status` accept:
|
||||
|
||||
| Parameter | Accepted values | Default |
|
||||
|---|---|---|
|
||||
| `state` | `queued`, `processing`, `done`, `failed` | `queued` |
|
||||
| `q` | Literal filename text, at most 100 characters, no control characters | Empty |
|
||||
| `page` | Positive whole number, at most 100000 | `1` |
|
||||
| `pageSize` | `10`, `25`, `50` | `25` |
|
||||
|
||||
Arrays/objects and malformed values are rejected with a safe HTTP 400 response before querying the database. Search text is escaped before use in the MongoDB regex and searches only filenames.
|
||||
|
||||
The JSON response shape is:
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [],
|
||||
"counts": { "queued": 0, "processing": 0, "done": 0, "failed": 0 },
|
||||
"pagination": { "page": 1, "pageSize": 25, "total": 0, "totalPages": 1 },
|
||||
"filters": { "state": "queued", "q": "" },
|
||||
"global": { "captcha_blocked": false, "pause_reason": null }
|
||||
}
|
||||
```
|
||||
|
||||
`items` contains only the selected page of public jobs. `counts` covers all records in each state; `pagination.total` reflects the selected state's filename filter. An out-of-range page is clamped after counting. Empty results have page 1 of 1.
|
||||
|
||||
`GET /status-summary` returns only `counts` and `global`. It does not load job records, output logs, cookies, or filesystem metadata. Both JSON endpoints use `Cache-Control: no-store`.
|
||||
|
||||
Only the selected processing/completed page receives file-size checks. Records retain the Phase 1 public projection and exact-value credential redaction. The pause reason remains restricted to `authentication`, `resolution`, or null.
|
||||
|
||||
This replaces the previous four-array `/status-data` shape. The bundled frontend is updated together; any external client using `queued`, `processing`, `done`, and `failed` arrays must adapt to the paginated contract.
|
||||
|
||||
Each MongoDB read is bounded to five seconds. Sorting uses the existing state timestamp with `_id` as a deterministic tie-breaker. Bounded page retrieval reduces response size and file reads; exact counts, case-insensitive substring search, and high-offset `skip` can still become expensive on very large legacy collections. Index/cursor planning remains part of Phase 4. No migration or background index build is performed.
|
||||
|
||||
## Automated verification
|
||||
|
||||
`npm test` passed **183 tests: 139 Node and 44 Python**, with no failures, skips, or cancellations. The entire protected tree matched the original baseline before and after the run.
|
||||
|
||||
| Suite | Passed |
|
||||
|---|---:|
|
||||
| Python downloader | 44 |
|
||||
| Node-to-Python integration | 5 |
|
||||
| Protected-library guard | 10 |
|
||||
| Runtime services | 25 |
|
||||
| HTTP and WebSocket services | 19 |
|
||||
| Submission, public status, and safe templates | 19 |
|
||||
| Worker execution lifecycle | 36 |
|
||||
| Status query/pagination and form model | 16 |
|
||||
| Worker interface behavior | 9 |
|
||||
| **Total** | **183** |
|
||||
|
||||
New query tests cover literal-search escaping, malformed query shapes, stable sorts, skip/limit bounds, page clamping, selected-page-only reads, summary isolation, token redaction, symlink refusal, and form retention without credentials. New worker UI tests cover safe DOM text, bounded Unicode logs, selection/socket races, command serialization, cancellation, named creation, errors, and page cleanup.
|
||||
|
||||
Local test runtimes are Node.js 24.19.0 and Python 3.12.14. Database, PM2, and stream dependencies in tests are synthetic interfaces. No test contacts production MongoDB or downloads authenticated media.
|
||||
|
||||
## Browser and visual verification
|
||||
|
||||
A separate Playwright run in Chrome 151.0.7922.34 passed **27 browser checks with no failures**. It served the real application factory, queue controller, EJS templates, and browser scripts with synthetic database records and local worker/log simulators.
|
||||
|
||||
The checks exercised real form POSTs for both modes, native keyboard mode selection, filename padding and language derivation, client range validation, server validation with credential removal, literal filename search, bounded page reads, pagination/browser Back, and refresh preservation of open logs, focus, scroll position, and unsent search input.
|
||||
|
||||
They also exercised the resolution banner and resume action while retaining the affected queued record, safe HTML rendering, worker selection and refresh, log follow/scroll, scoped stop confirmation, named creation, and shared-summary isolation. No JavaScript errors or external/CDN requests occurred. The deliberately invalid form POST produced its expected HTTP 400 response.
|
||||
|
||||
Desktop screenshots at 1440 × 1000 and all three pages at 390 × 844 and 320 × 844 were visually inspected. Navigation, controls, forms, rows, process details, and logs fit without horizontal overflow. These are local fixture checks; the user will validate the new interface in the existing Debian deployment.
|
||||
|
||||
## Deployment scope
|
||||
|
||||
Apply the Phase 2 ZIP over the installed Phase 1 update **including the resolution fix**. The archive contains a read-only preflight checker, a per-file manifest, checksums, installation instructions, and only the changed/new project files.
|
||||
|
||||
The Node worker, Python entrypoints, `scripts/requirements.txt`, Node dependencies, environment-variable contract, and every file under `scripts/lib/` are unchanged from the installed fix. Keep `.env`, the Python environment, dependencies, and media in place.
|
||||
|
||||
Stop the web process while copying the complete update and restart that web process after verification. Existing downloader workers do not need a code restart for this phase. Reload already-open browser tabs so they use the new API/frontend pair. No database migration is required.
|
||||
|
||||
The production web entrypoint remains `server.js`. The worker entrypoint remains `queue_worker.js`. Run both under the download account with its existing media access; Phase 2 requires no additional privilege or sudoers rule.
|
||||
|
||||
For rollback, stop the web process, restore all replaced web files from the backup, and remove the Phase 2 additions identified by the manifest before restarting it. Keep the installed Phase 1 worker/resolution fix. Restore a matching frontend/API pair together.
|
||||
+14
-4
@@ -2,17 +2,17 @@
|
||||
|
||||
Baseline: upstream `211bfd174dd78eac36f3c74411ecaa72f56eec79`.
|
||||
|
||||
The user approved the roadmap and authorized Phase 1 on 23 October 2026. The intended server is Debian 13, under the download account's home directory, with `/mnt/media/WIP/` access through `plex` and administrative `sudo` available. The user has installed the initial Phase 1 update and reported successful episode downloads. A follow-up unresolved-link pause fix is prepared locally; the assistant has not accessed or changed the server.
|
||||
The user approved the roadmap and authorized Phase 1 on 23 October 2026. The intended server is Debian 13, under the download account's home directory, with `/mnt/media/WIP/` access through `plex` and administrative `sudo` available. After installing Phase 1 and the resolution fix, the user confirmed successful episode downloads, verification pause, manual confirmation, retry of the affected episode, and completion of the full queue. The user then authorized Phase 2, confirmed that both series and single downloads worked with its UI, and requested the dashboard, state-specific clear actions, numbered workers, current-download cards, season naming, and MongoDB token caching. The assistant has not accessed or changed the production server.
|
||||
|
||||
All phases preserve the exact contents and paths under `scripts/lib/`. New code stays outside that directory, and Python bytecode writing is disabled.
|
||||
|
||||
**Current status:** Phase 0 review and Phase 1 implementation are complete. The current revision, including the [unresolved-link pause fix](phase-1-resolution-fix.md), passed all 158 offline tests and the protected-tree checks; see the [verification report](phase-1-verification.md). The user is testing Phase 1 on the target server. Phase 2 remains the next planned implementation phase.
|
||||
**Current status:** Phases 0, 1, and 2 are implemented locally. The user confirmed the initial Phase 2 workflow in production; the requested refinements are documented in the [current report](phase-2-refinements.md), including their acceptance checks. They preserve the [unresolved-link pause fix](phase-1-resolution-fix.md). Phase 3 is the next planned implementation phase and awaits authorization.
|
||||
|
||||
| Phase | Scope | Acceptance gate |
|
||||
|---|---|---|
|
||||
| 0 — Review | Clone and inspect the source; map data flow and preservation boundary | Clean reviewed baseline and complete protected-tree manifest |
|
||||
| 1 — Reliable behavior | Truthful subprocess results; child startup handling; safe input/output validation; corrected video title; public status projections; safe rendering; shared configuration; deployment feasibility | Failed or malformed results cannot become successful jobs; infrastructure failures preserve pending requests; offline regressions and protected-tree checks pass |
|
||||
| 2 — UI shell | Responsive top bar; consistent visual styling; accessible submission form; filters and pagination; lightweight shared status | Both submission modes work on mobile/keyboard; refresh preserves interaction state and does not repeatedly load all history |
|
||||
| 2 — UI shell and requested refinements | Responsive top bar; default dashboard; active worker cards; accessible submission with season preview; filters, pagination and state-specific clear actions; numbered quick-add; per-submission token-cache validation | Both modes work on mobile/keyboard; refresh preserves interaction state; bounded activity/history; failed access checks never enqueue or expose tokens; protected stream unchanged |
|
||||
| 3 — Shared execution modules | Extract the shared Python executor and Node planning/process/supervisor services; structured events; temporary output and publication policy | Compatibility of filenames/flags/stream call order; explicit results; safe output publication |
|
||||
| 4 — Recoverable queue | Explicit authoritative states; ownership and heartbeats; attempts; recovery; retries; global concurrency; grouping and indexes | Safe concurrent claims and worker-loss recovery; stale attempts cannot publish accepted output; reversible data migration |
|
||||
| 5 — Worker management | Persisted defaults/overrides; pause/drain/restart/cancel; operational limits; proven external bandwidth control | Settings are enforced and survive restarts; per-worker and shared bandwidth caps hold under concurrent transfers |
|
||||
@@ -22,10 +22,20 @@ All phases preserve the exact contents and paths under `scripts/lib/`. New code
|
||||
|
||||
The legacy collections remain in place. Successful and ordinary failed jobs are still recorded in their respective history collections before removal from the queue; this sequence is not an atomic cross-collection transaction. Do not mix old and new worker code during a rollout. Stop or drain existing work before replacing the worker/script pair, because the new worker requires the new completion record and stdin credential interface.
|
||||
|
||||
The top-bar redesign and new advanced worker settings are pending. No bandwidth limit, privileged helper, network namespace, traffic-control rule, systemd unit, or sudoers entry is installed by Phase 1.
|
||||
Phase 2 delivers the top-bar redesign and improves the existing worker controls. Persisted advanced worker settings and enforced bandwidth control remain in Phase 5. Neither Phase 1 nor Phase 2 installs a bandwidth limit, privileged helper, network namespace, traffic-control rule, systemd unit, or sudoers entry.
|
||||
|
||||
The Debian bandwidth assessment recommends validating a separately privileged shaper on an isolated worker traffic path. The host's actual route/interface/capability details and measured incoming-rate behavior remain prerequisites for choosing the backend.
|
||||
|
||||
## Phase 2 boundaries
|
||||
|
||||
The first UI release changed only web code and did not require a worker restart. The subsequent requested refinements add diagnostic identity to atomic worker claims and clear that identity when a claim is released. The metadata does not grant ownership, implement a lease, authorize recovery, or change download/verification behavior. Restart both web and workers after applying the refinement update to enable attribution on future claims. Drain waiting and active work before stopping and replacing worker code.
|
||||
|
||||
Series naming changes only for new web requests that explicitly provide `season`. The form always provides it; legacy clients that omit it retain their previous names. Existing files, queued filenames, standalone CLI names, and all Python/protected stream code are unchanged.
|
||||
|
||||
The token cache and numbered worker counter add documents to the existing `settings` collection. Existing queue credentials are not rewritten. Access checks use the first requested source and cannot guarantee validity after a token rotates mid-queue. No destructive migration is introduced.
|
||||
|
||||
Selected status results remain paginated, recent history is capped at five records per history state, and activity reads/display are capped at 50 jobs and 50 workers with explicit truncation notices. The shared summary avoids record/log/file/PM2 reads. Exact counts and literal filename searches still query legacy collections. Index planning, cursor pagination, durable ownership, recovery, and grouped jobs remain in Phase 4.
|
||||
|
||||
## Rollback and migration
|
||||
|
||||
Keep the source version and database snapshot for each deployed phase. For Phase 1 rollback, stop the new workers and verify their children have terminated before restoring the old worker and Python entrypoints together. Additional history metadata is additive; no destructive database migration is introduced here. Rollback to the old application also restores its known reliability limitations and should be deliberate.
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const { config } = require("./config");
|
||||
const { STATUS_READ_PROJECTION, toPublicJob, validateOutputTarget } = require("./jobValidation");
|
||||
const { QUERY_TIMEOUT_MS } = require("./statusQuery");
|
||||
const { toPublicWorkerIdentity, validWorkerName, isoTimestamp } = require("./workerIdentity");
|
||||
|
||||
const ACTIVE_JOB_LIMIT = 50;
|
||||
const WORKER_LIMIT = 50;
|
||||
const INVENTORY_CACHE_MS = 10000;
|
||||
const ACTIVITY_READ_PROJECTION = Object.freeze({ ...STATUS_READ_PROJECTION, worker: 1 });
|
||||
const PROCESS_STATES = new Set(["online", "stopped", "stopping", "launching", "errored", "waiting restart", "one-launch-status"]);
|
||||
|
||||
async function inventorySnapshot(listWorkers) {
|
||||
try {
|
||||
const workers = await listWorkers();
|
||||
if (!Array.isArray(workers)) throw new Error("Invalid worker inventory.");
|
||||
const visible = workers.slice(0, WORKER_LIMIT + 1);
|
||||
const pidCounts = new Map(visible.filter(worker => Number.isSafeInteger(worker?.pid) && worker.pid > 0)
|
||||
.map(worker => [worker.pid, 0]));
|
||||
// Check duplicate PIDs against the full bounded PM2 response before keeping
|
||||
// only the first page. A duplicate beyond that page is still ambiguous.
|
||||
for (const worker of workers) {
|
||||
if (pidCounts.has(worker?.pid)) pidCounts.set(worker.pid, pidCounts.get(worker.pid) + 1);
|
||||
}
|
||||
return { available: true, workers: visible,
|
||||
ambiguousPids: new Set([...pidCounts].filter(([, count]) => count > 1).map(([pid]) => pid)) };
|
||||
} catch {
|
||||
// A supervisor failure must not turn existing processing records into an
|
||||
// apparently empty queue, or prevent users from reading download status.
|
||||
return { available: false, workers: [], ambiguousPids: new Set() };
|
||||
}
|
||||
}
|
||||
|
||||
function createInventoryReader(listWorkers, { now = Date.now, ttlMs = INVENTORY_CACHE_MS } = {}) {
|
||||
let cached = null;
|
||||
let expiresAt = 0;
|
||||
let pending = null;
|
||||
return async function readInventory() {
|
||||
if (cached && now() < expiresAt) return cached;
|
||||
if (pending) return pending;
|
||||
pending = inventorySnapshot(listWorkers).then(snapshot => {
|
||||
cached = snapshot;
|
||||
expiresAt = now() + ttlMs;
|
||||
return snapshot;
|
||||
}).finally(() => { pending = null; });
|
||||
return pending;
|
||||
};
|
||||
}
|
||||
|
||||
const readDefaultInventory = createInventoryReader(() => require("../controllers/pm2Controller").listManagedProcesses());
|
||||
|
||||
async function readActiveFileSize(job, settings) {
|
||||
try {
|
||||
const target = await validateOutputTarget(settings.outputDir, job.filename);
|
||||
const stat = await fs.lstat(target);
|
||||
return stat.isFile() && !stat.isSymbolicLink() ? stat.size : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function publicProcess(record, index) {
|
||||
const value = record && typeof record === "object" ? record : {};
|
||||
const id = typeof value.pm_id === "number" ? String(value.pm_id) : value.pm_id;
|
||||
const pm_id = typeof id === "string" && /^(0|[1-9]\d{0,9})$/.test(id) ? id : null;
|
||||
return {
|
||||
key: `pm2:${pm_id ?? "unknown"}:${index}`,
|
||||
name: validWorkerName(value.name) ? value.name : (pm_id === null ? "Unknown worker" : `Worker ${pm_id}`),
|
||||
pm_id, pid: Number.isSafeInteger(value.pid) && value.pid > 0 ? value.pid : null,
|
||||
status: PROCESS_STATES.has(value.status) ? value.status : "unknown",
|
||||
startedAtISO: isoTimestamp(value.startedAtISO),
|
||||
available: true, jobs: [], activityUnknown: false,
|
||||
};
|
||||
}
|
||||
|
||||
function assignment(job, inventory, workers, host) {
|
||||
const identity = job.worker;
|
||||
if (!identity) return { reason: "unknown-worker" };
|
||||
if (identity.host !== host) return { reason: "remote-worker" };
|
||||
if (!inventory.available) return { reason: "supervisor-unavailable" };
|
||||
const candidates = workers.filter(worker => worker.pid === identity.pid);
|
||||
// Duplicate inventory PIDs are ambiguous. Do not choose whichever row happens
|
||||
// to come first, even if only one of the rows claims to be online.
|
||||
if (candidates.length > 1 || inventory.ambiguousPids.has(identity.pid)) return { reason: "ambiguous-worker" };
|
||||
const worker = candidates[0];
|
||||
if (!worker && inventory.workers.length > WORKER_LIMIT) return { reason: "worker-not-shown" };
|
||||
if (!worker || worker.status !== "online") return { reason: "worker-not-running" };
|
||||
const workerStarted = Date.parse(identity.started_at);
|
||||
const claimStarted = Date.parse(job.started_at);
|
||||
if (!worker.startedAtISO || !Number.isFinite(claimStarted) || workerStarted > claimStarted) {
|
||||
return { reason: "unverified-worker" };
|
||||
}
|
||||
// A recycled PID must not attach an old held claim to a replacement process.
|
||||
if (workerStarted < Date.parse(worker.startedAtISO)) return { reason: "stale-worker" };
|
||||
return { worker };
|
||||
}
|
||||
|
||||
async function readActivity(db, {
|
||||
settings = config, listWorkers, host = os.hostname(), readFileSize = readActiveFileSize,
|
||||
} = {}) {
|
||||
const [records, inventory] = await Promise.all([
|
||||
db.collection("queue").find({ processing: true }, {
|
||||
projection: ACTIVITY_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS,
|
||||
}).sort({ created_at: 1, _id: 1 }).limit(ACTIVE_JOB_LIMIT + 1).toArray(),
|
||||
listWorkers ? inventorySnapshot(listWorkers) : readDefaultInventory(),
|
||||
]);
|
||||
const truncated = records.length > ACTIVE_JOB_LIMIT;
|
||||
const workersTruncated = inventory.workers.length > WORKER_LIMIT;
|
||||
const inventoryWorkers = inventory.workers.map(publicProcess);
|
||||
const workers = inventoryWorkers.slice(0, WORKER_LIMIT);
|
||||
const jobs = await Promise.all(records.slice(0, ACTIVE_JOB_LIMIT).map(async record => {
|
||||
const job = { ...toPublicJob(record), worker: toPublicWorkerIdentity(record.worker) };
|
||||
try {
|
||||
const size = await readFileSize(job, settings);
|
||||
job.fileSize = Number.isSafeInteger(size) && size >= 0 ? size : null;
|
||||
} catch { job.fileSize = null; }
|
||||
return job;
|
||||
}));
|
||||
const unassigned = [];
|
||||
for (const job of jobs) {
|
||||
const match = assignment(job, inventory, inventoryWorkers, host);
|
||||
if (match.worker && workers.includes(match.worker)) match.worker.jobs.push(job);
|
||||
else unassigned.push({ ...job, assignmentReason: match.reason || "worker-not-shown" });
|
||||
}
|
||||
const uncertainLocalClaims = unassigned.some(job => !job.worker || job.worker.host === host);
|
||||
for (const worker of workers) {
|
||||
// Pre-update claims have no reliable worker identity. In that situation an
|
||||
// empty card means activity is unknown, not evidence that a worker is idle.
|
||||
worker.activityUnknown = truncated || workersTruncated || uncertainLocalClaims;
|
||||
}
|
||||
return { workers, unassigned, truncated, workersTruncated, available: inventory.available };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readActivity, createInventoryReader, readActiveFileSize,
|
||||
ACTIVE_JOB_LIMIT, WORKER_LIMIT, INVENTORY_CACHE_MS, ACTIVITY_READ_PROJECTION,
|
||||
};
|
||||
+24
-7
@@ -29,6 +29,14 @@ function positiveInteger(value, label) {
|
||||
return number;
|
||||
}
|
||||
|
||||
function seasonNumber(value) {
|
||||
const text = typeof value === "number" ? String(value) : value;
|
||||
if (typeof text !== "string" || !/^(0|[1-9]\d*)$/.test(text) || !Number.isSafeInteger(Number(text))) {
|
||||
throw new ValidationError("Season must be a whole number of zero or greater within the supported range.");
|
||||
}
|
||||
return Number(text);
|
||||
}
|
||||
|
||||
function isWellFormedText(value) {
|
||||
// In Unicode mode a valid surrogate pair is one code point outside this range.
|
||||
// Lone surrogates would otherwise be replaced silently when converted to UTF-8.
|
||||
@@ -115,17 +123,16 @@ function optionalTitle(value) {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
async function planQueueJobs(body, config, now = () => new Date()) {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) throw new ValidationError("Invalid download request.");
|
||||
if (body.mode !== "video" && body.mode !== "series") throw new ValidationError("Choose video or series mode.");
|
||||
const token = cookieToken(body.token, config.tokenPrefix);
|
||||
const created_at = now();
|
||||
const jobs = [];
|
||||
if (body.mode === "video") {
|
||||
const source = normalizeWatchUrl(body.url);
|
||||
const filename = normalizeFilename(optionalTitle(body.filename) || optionalTitle(body.name)
|
||||
|| `${source.id} E${source.episode} ${source.language}`);
|
||||
jobs.push({ url: source.url, token, filename, created_at });
|
||||
jobs.push({ url: source.url, filename, created_at });
|
||||
} else {
|
||||
const id = positiveInteger(body.id, "Series ID");
|
||||
const from = positiveInteger(body.episode_from, "First episode");
|
||||
@@ -137,11 +144,15 @@ async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
if (!LANGUAGES.has(body.language)) throw new ValidationError("Choose a supported language.");
|
||||
const name = optionalTitle(body.name) || String(id);
|
||||
const pad = String(to).length;
|
||||
// Older direct API clients omit season and keep their established names.
|
||||
// The web form always sends a season, including zero for specials.
|
||||
const season = body.season === undefined ? null : seasonNumber(body.season);
|
||||
for (let ep = from; ep <= to; ep += 1) {
|
||||
jobs.push({
|
||||
url: `https://proxer.me/watch/${id}/${ep}/${body.language}`,
|
||||
token,
|
||||
filename: normalizeFilename(`${name}E${String(ep).padStart(pad, "0")}_${body.language}`),
|
||||
filename: normalizeFilename(season === null
|
||||
? `${name}E${String(ep).padStart(pad, "0")}_${body.language}`
|
||||
: `${name}S${String(season).padStart(3, "0")}E${String(ep).padStart(3, "0")}_${body.language}`),
|
||||
created_at,
|
||||
});
|
||||
}
|
||||
@@ -151,6 +162,12 @@ async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
return jobs;
|
||||
}
|
||||
|
||||
async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
const jobs = await planQueueJobs(body, config, now);
|
||||
const token = cookieToken(body.token, config.tokenPrefix);
|
||||
return jobs.map(job => ({ ...job, token }));
|
||||
}
|
||||
|
||||
function sanitizeLog(value, sensitiveValues = []) {
|
||||
if (typeof value !== "string") return "";
|
||||
let result = value;
|
||||
@@ -191,6 +208,6 @@ function toPublicJob(job) {
|
||||
|
||||
module.exports = {
|
||||
ValidationError, LANGUAGES, MAX_LOG_BYTES, STATUS_READ_PROJECTION,
|
||||
positiveInteger, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob,
|
||||
positiveInteger, seasonNumber, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, planQueueJobs, buildQueueJobs, sanitizeLog, toPublicJob,
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
"use strict";
|
||||
|
||||
const { normalizeWatchUrl, cookieToken } = require("./jobValidation");
|
||||
|
||||
const PROBE_TIMEOUT_MS = 12_000;
|
||||
const PROBE_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
// This is a read-only download-access check, not an account-login assertion.
|
||||
// The configured cookie may be a Joomla session or a verification cookie.
|
||||
// scripts/lib/proxer_utils.py resolves the same exact `"code":"` marker;
|
||||
// HTTP 200 alone, a missing marker, and a generic 403 prove neither login nor
|
||||
// expiry. No protected library or media-transfer code is involved here.
|
||||
function classifyWatchResponse(status, html, contentType = "text/html") {
|
||||
const isHtml = typeof html === "string"
|
||||
&& /^\s*(?:text\/html|application\/xhtml\+xml)(?:\s*;|\s*$)/i.test(contentType);
|
||||
const title = isHtml ? html.match(/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i)?.[1] || "" : "";
|
||||
const challenge = isHtml && (/(?:Just a moment|Attention Required|Checking your browser)/i.test(title)
|
||||
|| /\bid\s*=\s*["'](?:challenge-form|cf-challenge-running|cf-error-details)["']/i.test(html));
|
||||
if (challenge) return { state: "verification" };
|
||||
// These HTTP outcomes remain meaningful when an upstream error is JSON or
|
||||
// plain text. An observed verification challenge still takes precedence.
|
||||
if (status === 401) return { state: "invalid" };
|
||||
if (status === 429 || status >= 500) return { state: "unavailable" };
|
||||
if (status === 404 || status === 410) return { state: "source" };
|
||||
if (status !== 200 || !isHtml) return { state: "unverifiable" };
|
||||
|
||||
// Restrict the marker's value to a plausible embed identifier; never return
|
||||
// it or any upstream HTML, user information, signed URL, or response header.
|
||||
if (/"code":"[A-Za-z0-9_-]{1,256}"/.test(html)) return { state: "valid" };
|
||||
|
||||
const visibleText = html.replace(/<!--[\s\S]*?-->/g, " ")
|
||||
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ")
|
||||
.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ");
|
||||
// Proxer's public logged-out pages use this explicit access-denied wording.
|
||||
// Observed primary source: https://proxer.me/manga/doujin/clicks/S
|
||||
// A login form in the navigation alone is not treated as an invalid cookie.
|
||||
if (/Bitte logge dich ein, um diesen Bereich betreten zu k(?:ö|ö)nnen\./i.test(visibleText)) {
|
||||
return { state: "invalid" };
|
||||
}
|
||||
if (/\bcaptcha\b/i.test(visibleText)) return { state: "verification" };
|
||||
return { state: "unverifiable" };
|
||||
}
|
||||
|
||||
async function boundedHtml(response, maxBytes) {
|
||||
const declaredLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
return null;
|
||||
}
|
||||
if (!response.body) return null;
|
||||
const reader = response.body.getReader();
|
||||
let size = 0;
|
||||
const parts = [];
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) return Buffer.concat(parts, size).toString("utf8");
|
||||
size += value.byteLength;
|
||||
if (size > maxBytes) {
|
||||
await reader.cancel().catch(() => {});
|
||||
return null;
|
||||
}
|
||||
parts.push(Buffer.from(value));
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function createProxerSessionProbe({ fetch: fetchImpl = globalThis.fetch, timeoutMs = PROBE_TIMEOUT_MS, maxBytes = PROBE_MAX_BYTES } = {}) {
|
||||
return async function probe(cookie, { url } = {}) {
|
||||
// Canonicalization forbids arbitrary hosts, ports, credentials, queries and
|
||||
// non-watch paths. Redirects are never followed with the credential.
|
||||
const target = normalizeWatchUrl(url).url;
|
||||
const equals = typeof cookie === "string" ? cookie.indexOf("=") : -1;
|
||||
if (equals < 1) throw new Error("A complete validated cookie is required for the access check.");
|
||||
cookieToken(cookie.slice(equals + 1), cookie.slice(0, equals + 1));
|
||||
const controller = new AbortController();
|
||||
let timer;
|
||||
try {
|
||||
const inspect = (async () => {
|
||||
const response = await fetchImpl(target, {
|
||||
method: "GET", redirect: "manual", credentials: "omit", signal: controller.signal,
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0", Accept: "text/html,application/xhtml+xml",
|
||||
"Cache-Control": "no-cache", Cookie: `${cookie}; stream_choose=proxer-stream`,
|
||||
},
|
||||
});
|
||||
if (response.headers.get("cf-mitigated") === "challenge") {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
return { state: "verification" };
|
||||
}
|
||||
if (response.status >= 300 && response.status < 400) {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
return { state: "unverifiable" };
|
||||
}
|
||||
const html = await boundedHtml(response, maxBytes);
|
||||
// An absent or oversized body cannot prove success. Preserve explicit
|
||||
// HTTP rejection/source/availability outcomes; challenge headers were
|
||||
// already handled before reading any body.
|
||||
return classifyWatchResponse(response.status, html ?? "", response.headers.get("content-type") || "");
|
||||
})();
|
||||
const timeout = new Promise(resolve => {
|
||||
timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
resolve({ state: "unavailable" });
|
||||
}, timeoutMs);
|
||||
});
|
||||
return await Promise.race([inspect, timeout]);
|
||||
} catch {
|
||||
return { state: "unavailable" };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PROBE_TIMEOUT_MS, PROBE_MAX_BYTES, classifyWatchResponse, createProxerSessionProbe,
|
||||
probeSessionToken: createProxerSessionProbe(),
|
||||
};
|
||||
@@ -0,0 +1,162 @@
|
||||
"use strict";
|
||||
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { getDb } = require("./mongo");
|
||||
const { config } = require("./config");
|
||||
const { ValidationError, cookieToken, normalizeWatchUrl } = require("./jobValidation");
|
||||
const { probeSessionToken } = require("./proxerSessionProbe");
|
||||
|
||||
const CACHE_ID = "proxer-session-token";
|
||||
const CACHE_QUERY_TIMEOUT_MS = 5000;
|
||||
const STATUS_PROJECTION = Object.freeze({ cookie_name: 1, state: 1, validated_at: 1, saved_at: 1 });
|
||||
|
||||
class SessionTokenError extends ValidationError {
|
||||
constructor(code, message, httpStatus = 400) {
|
||||
super(message);
|
||||
this.name = "SessionTokenError";
|
||||
this.code = code;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
}
|
||||
|
||||
function iso(value) {
|
||||
if (value == null) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) ? date.toISOString() : null;
|
||||
}
|
||||
|
||||
function publicCacheStatus(record, prefix) {
|
||||
const matches = record && record.cookie_name === prefix.slice(0, -1);
|
||||
const state = matches && record.state === "ready" ? "saved" : matches && record.state === "invalid" ? "invalid" : "missing";
|
||||
return {
|
||||
available: state === "saved", state,
|
||||
lastValidatedAt: matches ? iso(record.validated_at) : null,
|
||||
savedAt: matches ? iso(record.saved_at) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function revisionFilter(record) {
|
||||
return {
|
||||
_id: CACHE_ID,
|
||||
revision: record && Object.hasOwn(record, "revision") ? { $eq: record.revision } : { $exists: false },
|
||||
};
|
||||
}
|
||||
|
||||
function storageError() {
|
||||
return new SessionTokenError("storage", "The saved token could not be accessed or updated. Check the database connection and try again. Nothing was queued.", 503);
|
||||
}
|
||||
|
||||
function probeError(state) {
|
||||
if (state === "invalid") return new SessionTokenError("invalid", "Proxer rejected the token. Supply a current token and try again. Nothing was queued.");
|
||||
if (state === "verification") return new SessionTokenError("verification", "Proxer requires verification before the token can be used. Complete the verification in your browser and supply a refreshed token, then try again. Nothing was queued.", 409);
|
||||
if (state === "source") return new SessionTokenError("source", "The first requested episode is unavailable, so token access could not be checked. Check the series, episode, and language, then try again. The saved token was kept and nothing was queued.", 409);
|
||||
if (state === "unavailable") return new SessionTokenError("unavailable", "The token access check could not reach Proxer or timed out. Try again when the connection is available. The saved token was kept and nothing was queued.", 503);
|
||||
return new SessionTokenError("unverifiable", "The first episode's video link could not be resolved during the token access check. Open that source page, complete any required verification, and supply a current token if needed. The saved token was kept and nothing was queued.", 409);
|
||||
}
|
||||
|
||||
function createSessionTokenService({ getDb: connect = getDb, settings = config, probe = probeSessionToken, now = () => new Date() } = {}) {
|
||||
async function statusFrom(collection) {
|
||||
const record = await collection.findOne({ _id: CACHE_ID }, { projection: STATUS_PROJECTION, maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
|
||||
return publicCacheStatus(record, settings.tokenPrefix);
|
||||
}
|
||||
|
||||
async function readStatus() {
|
||||
try {
|
||||
return await statusFrom((await connect()).collection("settings"));
|
||||
} catch {
|
||||
throw storageError();
|
||||
}
|
||||
}
|
||||
|
||||
async function invalidate(collection, record) {
|
||||
if (!record) return;
|
||||
const result = await collection.updateOne(revisionFilter(record), {
|
||||
$set: { state: "invalid", invalidated_at: now(), revision: randomUUID() },
|
||||
$unset: { cookie: "" },
|
||||
}, { maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
|
||||
if (!result.acknowledged) throw storageError();
|
||||
}
|
||||
|
||||
async function resolveForEnqueue(rawValue, { url } = {}) {
|
||||
try {
|
||||
const target = normalizeWatchUrl(url).url;
|
||||
const supplied = rawValue !== undefined && rawValue !== null && rawValue !== "";
|
||||
// Validate a supplied value before touching MongoDB or the network.
|
||||
let cookie = supplied ? cookieToken(rawValue, settings.tokenPrefix) : null;
|
||||
const collection = (await connect()).collection("settings");
|
||||
const record = await collection.findOne({ _id: CACHE_ID }, {
|
||||
projection: { cookie: 1, cookie_name: 1, state: 1, revision: 1, validated_at: 1, saved_at: 1 },
|
||||
maxTimeMS: CACHE_QUERY_TIMEOUT_MS,
|
||||
});
|
||||
if (!supplied) {
|
||||
const status = publicCacheStatus(record, settings.tokenPrefix);
|
||||
if (!status.available) {
|
||||
throw new SessionTokenError(status.state === "invalid" ? "invalid" : "missing",
|
||||
status.state === "invalid" ? "The saved token was rejected. Supply a new token before adding downloads."
|
||||
: "No saved token is available. Supply a token once; it will be checked and saved for later downloads.");
|
||||
}
|
||||
try {
|
||||
if (typeof record.cookie !== "string" || !record.cookie.startsWith(settings.tokenPrefix)) throw new Error("invalid cache");
|
||||
cookie = cookieToken(record.cookie.slice(settings.tokenPrefix.length), settings.tokenPrefix);
|
||||
} catch {
|
||||
await invalidate(collection, record);
|
||||
throw new SessionTokenError("invalid", "The saved token cannot be used. Supply a new token before adding downloads.");
|
||||
}
|
||||
}
|
||||
|
||||
let outcome;
|
||||
try {
|
||||
outcome = await probe(cookie, { url: target });
|
||||
} catch {
|
||||
throw probeError("unavailable");
|
||||
}
|
||||
if (outcome?.state !== "valid") {
|
||||
// Only a proven rejection invalidates a cached credential. A challenge,
|
||||
// a source failure, a layout change and network errors retain it.
|
||||
// Matching a revision prevents an old in-flight check erasing a token
|
||||
// supplied successfully by another browser or server process.
|
||||
if (outcome?.state === "invalid" && record && record.cookie === cookie) await invalidate(collection, record);
|
||||
throw probeError(outcome?.state);
|
||||
}
|
||||
|
||||
const checkedAt = now();
|
||||
let saved = false;
|
||||
let status;
|
||||
if (supplied) {
|
||||
const replacement = {
|
||||
cookie, cookie_name: settings.tokenPrefix.slice(0, -1), state: "ready",
|
||||
revision: randomUUID(), saved_at: checkedAt, validated_at: checkedAt,
|
||||
};
|
||||
try {
|
||||
const result = await collection.updateOne(revisionFilter(record), {
|
||||
$set: replacement, $unset: { invalidated_at: "" },
|
||||
}, { upsert: !record, maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
|
||||
if (!result.acknowledged) throw storageError();
|
||||
saved = result.matchedCount === 1 || result.upsertedCount === 1;
|
||||
} catch (error) {
|
||||
// Two first-time submissions may both observe an empty cache. The
|
||||
// unique _id and compare-and-set let one publish without overwriting
|
||||
// the other's newer credential; both validated queue jobs remain safe.
|
||||
if (error.code !== 11000) throw error;
|
||||
}
|
||||
if (saved) status = publicCacheStatus(replacement, settings.tokenPrefix);
|
||||
} else {
|
||||
const result = await collection.updateOne(revisionFilter(record), {
|
||||
$set: { validated_at: checkedAt, revision: randomUUID() },
|
||||
}, { maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
|
||||
if (!result.acknowledged) throw storageError();
|
||||
saved = result.matchedCount === 1;
|
||||
if (saved) status = publicCacheStatus({ ...record, validated_at: checkedAt }, settings.tokenPrefix);
|
||||
}
|
||||
if (!status) status = await statusFrom(collection);
|
||||
return { cookie, source: supplied ? "supplied" : "cached", status };
|
||||
} catch (error) {
|
||||
if (error instanceof SessionTokenError || error instanceof ValidationError) throw error;
|
||||
throw storageError();
|
||||
}
|
||||
}
|
||||
|
||||
return { readStatus, resolveForEnqueue };
|
||||
}
|
||||
|
||||
module.exports = { CACHE_ID, STATUS_PROJECTION, SessionTokenError, publicCacheStatus, createSessionTokenService };
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
|
||||
const { ValidationError } = require("./jobValidation");
|
||||
|
||||
const STATES = Object.freeze(["queued", "processing", "done", "failed"]);
|
||||
const PAGE_SIZES = Object.freeze([10, 25, 50]);
|
||||
const MAX_PAGE = 100000;
|
||||
const MAX_SEARCH_LENGTH = 100;
|
||||
const QUERY_TIMEOUT_MS = 5000;
|
||||
|
||||
function parseStatusQuery(query = {}) {
|
||||
if (!query || typeof query !== "object" || Array.isArray(query)) {
|
||||
throw new ValidationError("Invalid queue filters.");
|
||||
}
|
||||
for (const key of ["state", "q", "page", "pageSize"]) {
|
||||
if (query[key] !== undefined && typeof query[key] !== "string") {
|
||||
throw new ValidationError("Each queue filter must have a single text value.");
|
||||
}
|
||||
}
|
||||
const state = query.state === undefined ? "queued" : query.state;
|
||||
if (!STATES.includes(state)) throw new ValidationError("Choose a supported queue state.");
|
||||
const rawSearch = query.q ?? "";
|
||||
if (rawSearch.length > MAX_SEARCH_LENGTH || /[\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/u.test(rawSearch)) {
|
||||
throw new ValidationError(`Search must contain at most ${MAX_SEARCH_LENGTH} characters without control characters.`);
|
||||
}
|
||||
const q = rawSearch.trim();
|
||||
const pageText = query.page ?? "1";
|
||||
if (!/^[1-9]\d{0,5}$/.test(pageText) || Number(pageText) > MAX_PAGE) {
|
||||
throw new ValidationError(`Page must be a whole number between 1 and ${MAX_PAGE}.`);
|
||||
}
|
||||
const sizeText = query.pageSize ?? "25";
|
||||
if (!/^(10|25|50)$/.test(sizeText)) throw new ValidationError("Choose 10, 25, or 50 items per page.");
|
||||
return { state, q, page: Number(pageText), pageSize: Number(sizeText) };
|
||||
}
|
||||
|
||||
function stateQuery(state) {
|
||||
if (state === "queued") return { collection: "queue", filter: { processing: { $ne: true } }, sort: { created_at: 1, _id: 1 } };
|
||||
if (state === "processing") return { collection: "queue", filter: { processing: true }, sort: { created_at: 1, _id: 1 } };
|
||||
if (state === "done") return { collection: "done", filter: {}, sort: { finished_at: -1, _id: -1 } };
|
||||
if (state === "failed") return { collection: "failed", filter: {}, sort: { failed_at: -1, _id: -1 } };
|
||||
throw new ValidationError("Choose a supported queue state.");
|
||||
}
|
||||
|
||||
function statusFilter(state, q) {
|
||||
const { filter } = stateQuery(state);
|
||||
// Treat user input as literal text. No query keys or regular expressions are
|
||||
// accepted from the caller; search is confined to public filenames.
|
||||
if (q) filter.filename = { $regex: q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), $options: "i" };
|
||||
return filter;
|
||||
}
|
||||
|
||||
function publicGlobal(record) {
|
||||
return {
|
||||
captcha_blocked: record?.captcha_blocked === true,
|
||||
pause_reason: ["authentication", "resolution"].includes(record?.pause_reason) ? record.pause_reason : null,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STATES, PAGE_SIZES, MAX_PAGE, MAX_SEARCH_LENGTH, QUERY_TIMEOUT_MS,
|
||||
parseStatusQuery, stateQuery, statusFilter, publicGlobal,
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
|
||||
const os = require("node:os");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
|
||||
function validWorkerName(value) {
|
||||
return typeof value === "string" && /^[A-Za-z0-9][\w-]{0,63}$/.test(value)
|
||||
&& value.toLowerCase() !== "all";
|
||||
}
|
||||
|
||||
function isoTimestamp(value) {
|
||||
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) && date.getTime() > 0 && date.toISOString() === value ? value : null;
|
||||
}
|
||||
|
||||
// Worker metadata is display-only. It is never a lease or permission to release
|
||||
// a claim, and malformed/legacy metadata must never identify a current worker.
|
||||
function toPublicWorkerIdentity(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)
|
||||
|| !validWorkerName(value.name)
|
||||
|| !Number.isSafeInteger(value.pid) || value.pid <= 0
|
||||
|| typeof value.host !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$/.test(value.host)
|
||||
|| typeof value.run_id !== "string"
|
||||
|| !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.run_id)
|
||||
|| !isoTimestamp(value.started_at)) return null;
|
||||
return {
|
||||
name: value.name, pid: value.pid, host: value.host,
|
||||
run_id: value.run_id.toLowerCase(), started_at: value.started_at,
|
||||
};
|
||||
}
|
||||
|
||||
function createWorkerIdentity({
|
||||
env = process.env, pid = process.pid, host = os.hostname(),
|
||||
now = () => new Date(), uuid = randomUUID,
|
||||
} = {}) {
|
||||
const name = [env.PROXER_WORKER_NAME, env.name].find(validWorkerName) || `worker-${pid}`;
|
||||
const identity = toPublicWorkerIdentity({ name, pid, host, run_id: uuid(), started_at: now().toISOString() });
|
||||
if (!identity) throw new Error("The worker identity could not be initialized.");
|
||||
// This identity belongs to one Node process and is reused for every claim.
|
||||
return Object.freeze(identity);
|
||||
}
|
||||
|
||||
module.exports = { createWorkerIdentity, toPublicWorkerIdentity, validWorkerName, isoTimestamp };
|
||||
@@ -0,0 +1,120 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
const section = document.getElementById('current-downloads');
|
||||
if (!section) return;
|
||||
const workerList = document.getElementById('activity-workers');
|
||||
const unknownList = document.getElementById('activity-unassigned-jobs');
|
||||
const manage = document.getElementById('activity-manage');
|
||||
const scrollHint = document.getElementById('activity-scroll-hint');
|
||||
const text = (node, value) => { const next = String(value ?? ''); if (node.textContent !== next) node.textContent = next; };
|
||||
const element = (tag, className, parent) => {
|
||||
const node = document.createElement(tag); if (className) node.className = className; if (parent) parent.append(node); return node;
|
||||
};
|
||||
function updateScrollHint() {
|
||||
const overflowing = workerList.scrollWidth > workerList.clientWidth + 1;
|
||||
scrollHint.hidden = !overflowing;
|
||||
workerList.tabIndex = overflowing ? 0 : -1;
|
||||
text(scrollHint, 'Scroll sideways to view all ' + workerList.children.length + ' workers.');
|
||||
}
|
||||
function safeSource(value) {
|
||||
return typeof value === 'string' && /^https:\/\/proxer\.me\/watch\/[1-9]\d*\/[1-9]\d*\/(engsub|engdub|gersub|gerdub)$/.test(value) ? value : '';
|
||||
}
|
||||
function bytes(value) {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return 'Size unavailable';
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
||||
const index = value ? Math.min(Math.floor(Math.log(value) / Math.log(1024)), 4) : 0;
|
||||
return (value / 1024 ** index).toFixed(index ? 1 : 0) + ' ' + units[index] + ' on disk';
|
||||
}
|
||||
function elapsed(value) {
|
||||
const date = new Date(value);
|
||||
if (!value || !Number.isFinite(date.getTime())) return 'Start time unavailable';
|
||||
const seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));
|
||||
const duration = seconds < 60 ? '<1m' : seconds < 3600 ? Math.floor(seconds / 60) + 'm'
|
||||
: Math.floor(seconds / 3600) + 'h ' + Math.floor(seconds % 3600 / 60) + 'm';
|
||||
return 'Started ' + date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) + ' · ' + duration;
|
||||
}
|
||||
function validJob(job) { return job && typeof job._id === 'string' && typeof job.filename === 'string'; }
|
||||
function valid(data) {
|
||||
return data && typeof data.available === 'boolean' && Array.isArray(data.workers) && data.workers.length <= 50
|
||||
&& Array.isArray(data.unassigned) && data.unassigned.length <= 50 && data.unassigned.every(validJob)
|
||||
&& data.workers.every(worker => worker && typeof worker.key === 'string' && typeof worker.name === 'string'
|
||||
&& typeof worker.status === 'string' && Array.isArray(worker.jobs) && worker.jobs.length <= 50 && worker.jobs.every(validJob));
|
||||
}
|
||||
function reconcile(list, entries, key, create, update, dataKey) {
|
||||
const existing = new Map(Array.from(list.children, row => [row.dataset[dataKey], row]));
|
||||
let cursor = list.firstElementChild;
|
||||
for (const entry of entries) {
|
||||
const id = String(key(entry)); const row = existing.get(id) || create();
|
||||
existing.delete(id); row.dataset[dataKey] = id; update(row, entry);
|
||||
if (row === cursor) cursor = cursor.nextElementSibling; else list.insertBefore(row, cursor);
|
||||
}
|
||||
for (const row of existing.values()) {
|
||||
if (row.contains(document.activeElement)) manage.focus({ preventScroll: true });
|
||||
row.remove();
|
||||
}
|
||||
}
|
||||
function newJob() {
|
||||
const row = element('li', 'active-job');
|
||||
element('strong', 'active-job-name', row); element('a', 'active-job-source', row);
|
||||
const metrics = element('div', 'active-job-metrics', row);
|
||||
element('span', 'active-job-size', metrics); element('span', 'active-job-time', metrics);
|
||||
element('p', 'active-job-attribution field-hint', row);
|
||||
return row;
|
||||
}
|
||||
function updateJob(row, job, unassigned = false) {
|
||||
text(row.querySelector('.active-job-name'), job.filename);
|
||||
const link = row.querySelector('.active-job-source'); const source = safeSource(job.url);
|
||||
if (source) { link.href = source; link.target = '_blank'; link.rel = 'noopener noreferrer'; }
|
||||
else { link.removeAttribute('href'); link.removeAttribute('target'); link.removeAttribute('rel'); }
|
||||
const parts = source.split('/');
|
||||
text(link, source ? 'Series ' + parts[4] + ' · Episode ' + parts[5] + ' · ' + parts[6] : 'Source unavailable');
|
||||
text(row.querySelector('.active-job-size'), bytes(job.fileSize));
|
||||
const time = row.querySelector('.active-job-time'); time.dataset.startedAt = job.started_at || ''; text(time, elapsed(job.started_at));
|
||||
const attribution = row.querySelector('.active-job-attribution'); attribution.hidden = !unassigned;
|
||||
text(attribution, !unassigned ? '' : job.worker && typeof job.worker.name === 'string'
|
||||
? 'Saved worker: ' + job.worker.name + ' · live assignment unconfirmed' : 'Worker was not recorded for this claim.');
|
||||
}
|
||||
function newWorker() {
|
||||
const card = element('li', 'worker-card'); const heading = element('div', 'worker-card-heading', card);
|
||||
element('strong', 'worker-card-name', heading); element('span', 'worker-card-state badge', heading);
|
||||
element('ul', 'worker-card-jobs', card); element('p', 'worker-card-empty', card); return card;
|
||||
}
|
||||
function render(data, paused) {
|
||||
if (!valid(data)) return false;
|
||||
reconcile(workerList, data.workers, worker => worker.key, newWorker, (card, worker) => {
|
||||
const state = worker.jobs.length ? 'Active' : worker.status !== 'online'
|
||||
? (worker.status === 'errored' ? 'Error' : worker.status === 'stopped' ? 'Stopped' : 'Not ready')
|
||||
: worker.activityUnknown ? 'Activity unknown' : paused ? 'Paused' : 'Idle';
|
||||
text(card.querySelector('.worker-card-name'), worker.name);
|
||||
const badge = card.querySelector('.worker-card-state'); text(badge, state);
|
||||
badge.className = 'worker-card-state badge ' + (state === 'Active' ? 'badge-info'
|
||||
: ['Paused', 'Activity unknown'].includes(state) ? 'badge-warning' : state === 'Idle' ? 'badge-success' : 'badge-neutral');
|
||||
reconcile(card.querySelector('.worker-card-jobs'), worker.jobs, job => job._id, newJob, updateJob, 'activeJobId');
|
||||
const empty = card.querySelector('.worker-card-empty'); empty.hidden = worker.jobs.length > 0;
|
||||
text(empty, worker.activityUnknown && worker.status === 'online' ? 'No current job could be reliably linked to this worker.'
|
||||
: worker.status !== 'online' ? 'Start the worker to take queued episodes.' : paused ? 'Waiting for verification to clear.' : 'Ready for the next queued episode.');
|
||||
}, 'workerKey');
|
||||
reconcile(unknownList, data.unassigned, job => job._id, newJob, (row, job) => updateJob(row, job, true), 'activeJobId');
|
||||
document.getElementById('activity-unassigned').hidden = !data.unassigned.length;
|
||||
const empty = document.getElementById('activity-empty'); empty.hidden = data.workers.length > 0;
|
||||
text(empty.querySelector('strong'), data.available ? 'No managed workers yet' : 'Worker inventory unavailable');
|
||||
text(empty.querySelector('span'), data.available ? 'Quick-add a worker to start taking queued episodes.' : 'Check the worker supervisor, then refresh.');
|
||||
const warning = document.getElementById('activity-warning');
|
||||
warning.hidden = data.available && !data.truncated && !data.workersTruncated;
|
||||
text(warning, !data.available ? 'Worker status is unavailable. Saved active claims are still shown below.'
|
||||
: 'Showing up to 50 workers and 50 active claims. Open the Active queue for the full list; empty cards may have unlisted activity.');
|
||||
text(document.getElementById('activity-freshness'), 'Current claims by worker · updated ' + new Date().toLocaleTimeString());
|
||||
document.getElementById('activity-freshness').classList.remove('feedback-error');
|
||||
updateScrollHint();
|
||||
return true;
|
||||
}
|
||||
document.addEventListener('proxer:status', event => { if (event.detail?.activity) render(event.detail.activity, event.detail.global?.captcha_blocked === true); });
|
||||
document.addEventListener('proxer:status-error', () => {
|
||||
const freshness = document.getElementById('activity-freshness');
|
||||
text(freshness, 'Refresh unavailable · showing the last loaded activity'); freshness.classList.add('feedback-error');
|
||||
});
|
||||
for (const time of section.querySelectorAll('[data-started-at]')) text(time, elapsed(time.dataset.startedAt));
|
||||
updateScrollHint();
|
||||
window.addEventListener('resize', updateScrollHint);
|
||||
window.ProxerActivity = Object.freeze({ valid });
|
||||
})();
|
||||
@@ -0,0 +1,94 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const main = document.getElementById('main-content');
|
||||
const alert = document.getElementById('captcha-alert');
|
||||
const message = document.getElementById('captcha-message');
|
||||
const status = document.getElementById('global-status');
|
||||
const statusText = document.getElementById('global-status-text');
|
||||
const queueCount = document.getElementById('nav-queue-count');
|
||||
let inFlight = false;
|
||||
let timer = null;
|
||||
let controller = null;
|
||||
let disposed = false;
|
||||
let lastPaused = alert ? !alert.hidden : false;
|
||||
|
||||
function updateStatus(snapshot) {
|
||||
if (!snapshot || typeof snapshot.global !== 'object' || snapshot.global === null) return;
|
||||
lastPaused = snapshot.global.captcha_blocked === true;
|
||||
if (message) message.textContent = snapshot.global.pause_reason === 'resolution'
|
||||
? 'The video link could not be resolved. Possible causes include CAPTCHA or login verification, an unavailable video, or a source change. Workers are paused for verification.'
|
||||
: 'Authentication or access needs verification on Proxer. Workers are paused until verification is complete.';
|
||||
if (alert) alert.hidden = !lastPaused;
|
||||
if (status) {
|
||||
status.classList.toggle('is-paused', lastPaused);
|
||||
status.classList.toggle('is-ready', !lastPaused);
|
||||
status.classList.remove('is-stale');
|
||||
status.removeAttribute('title');
|
||||
}
|
||||
if (statusText) statusText.textContent = lastPaused ? 'Downloads paused' : 'Queue ready';
|
||||
if (queueCount && snapshot.counts) {
|
||||
const queued = Number(snapshot.counts.queued);
|
||||
const processing = Number(snapshot.counts.processing);
|
||||
if (Number.isFinite(queued) && queued >= 0 && Number.isFinite(processing) && processing >= 0) {
|
||||
queueCount.textContent = (queued + processing).toLocaleString();
|
||||
queueCount.hidden = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function markUnavailable() {
|
||||
if (status) {
|
||||
status.classList.remove('is-ready');
|
||||
status.classList.add('is-stale');
|
||||
status.title = 'The latest queue status could not be loaded. The last known information is still shown.';
|
||||
}
|
||||
if (statusText) statusText.textContent = lastPaused ? 'Paused · status unavailable' : 'Status unavailable';
|
||||
}
|
||||
|
||||
async function refreshSummary() {
|
||||
if (disposed || inFlight || document.hidden || ['queue', 'dashboard'].includes(main?.dataset.page)) return;
|
||||
inFlight = true;
|
||||
controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller?.abort(), 8000);
|
||||
try {
|
||||
const response = await fetch('/status-summary', { cache: 'no-store', signal: controller.signal });
|
||||
if (!response.ok) throw new Error('Status unavailable');
|
||||
const snapshot = await response.json();
|
||||
if (!snapshot || typeof snapshot.global !== 'object' || !snapshot.counts) throw new Error('Invalid status');
|
||||
if (!disposed) updateStatus(snapshot);
|
||||
} catch {
|
||||
if (!disposed && !document.hidden) markUnavailable();
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
inFlight = false;
|
||||
controller = null;
|
||||
if (!disposed) timer = setTimeout(refreshSummary, 10000);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('proxer:status', event => updateStatus(event.detail));
|
||||
document.addEventListener('proxer:status-error', markUnavailable);
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
clearTimeout(timer);
|
||||
if (document.hidden) controller?.abort();
|
||||
else refreshSummary();
|
||||
});
|
||||
document.addEventListener('submit', event => {
|
||||
const confirmation = event.target?.dataset?.confirm;
|
||||
if (!event.defaultPrevented && confirmation && !window.confirm(confirmation)) event.preventDefault();
|
||||
});
|
||||
window.addEventListener('pagehide', () => {
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
controller?.abort();
|
||||
});
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (event.persisted) {
|
||||
disposed = false;
|
||||
refreshSummary();
|
||||
}
|
||||
});
|
||||
window.ProxerUI = Object.freeze({ updateStatus, markUnavailable });
|
||||
refreshSummary();
|
||||
})();
|
||||
@@ -0,0 +1,79 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
const refreshButton = document.getElementById('dashboard-refresh');
|
||||
if (!refreshButton) return;
|
||||
const feedback = document.getElementById('dashboard-feedback');
|
||||
const states = ['queued', 'processing', 'done', 'failed'];
|
||||
let activeRequest = null;
|
||||
let disposed = false;
|
||||
let generation = 0;
|
||||
let failed = false;
|
||||
function text(node, value) { const next = String(value ?? ''); if (node.textContent !== next) node.textContent = next; }
|
||||
function displayTime(value) {
|
||||
const date = new Date(value);
|
||||
return value && Number.isFinite(date.getTime()) ? date.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : 'Time not recorded';
|
||||
}
|
||||
function valid(data) {
|
||||
return data && data.counts && states.every(state => Number.isSafeInteger(data.counts[state]) && data.counts[state] >= 0)
|
||||
&& data.global && typeof data.global.captcha_blocked === 'boolean' && window.ProxerActivity?.valid(data.activity)
|
||||
&& data.recent && ['done', 'failed'].every(state => Array.isArray(data.recent[state]) && data.recent[state].length <= 5
|
||||
&& data.recent[state].every(job => job && typeof job._id === 'string' && typeof job.filename === 'string'));
|
||||
}
|
||||
function updateRecent(state, jobs) {
|
||||
const list = document.getElementById('recent-' + state);
|
||||
const previous = new Map(Array.from(list.children, row => [row.dataset.recentId, row]));
|
||||
let cursor = list.firstElementChild;
|
||||
for (const job of jobs) {
|
||||
const row = previous.get(job._id) || document.createElement('li');
|
||||
previous.delete(job._id);
|
||||
if (!row.className) {
|
||||
row.className = 'recent-job'; const primary = document.createElement('div'); primary.className = 'recent-primary';
|
||||
const title = document.createElement('strong'); title.className = 'recent-name'; primary.append(title);
|
||||
const time = document.createElement('time'); time.className = 'muted'; primary.append(time); row.append(primary);
|
||||
const badge = document.createElement('span'); badge.className = 'badge ' + (state === 'done' ? 'badge-success' : 'badge-danger'); row.append(badge);
|
||||
}
|
||||
row.dataset.recentId = job._id; text(row.querySelector('.recent-name'), job.filename);
|
||||
const time = row.querySelector('time'); const stamp = job[state === 'done' ? 'finished_at' : 'failed_at'] || job.created_at;
|
||||
if (stamp && Number.isFinite(new Date(stamp).getTime())) time.dateTime = stamp; else time.removeAttribute('datetime');
|
||||
text(time, displayTime(stamp)); text(row.querySelector('.badge'), state === 'done' ? 'Completed' : job.error_category || 'Failed');
|
||||
if (row === cursor) cursor = cursor.nextElementSibling; else list.insertBefore(row, cursor);
|
||||
}
|
||||
for (const row of previous.values()) row.remove();
|
||||
document.getElementById('recent-' + state + '-empty').hidden = jobs.length > 0;
|
||||
}
|
||||
async function refresh(manual = false) {
|
||||
if (disposed || activeRequest || (!manual && document.hidden)) return;
|
||||
const request = new AbortController(); const requestGeneration = ++generation;
|
||||
activeRequest = request; refreshButton.disabled = true;
|
||||
const timeout = setTimeout(() => request.abort(), 15000);
|
||||
try {
|
||||
const response = await fetch('/dashboard-data', { cache: 'no-store', signal: request.signal });
|
||||
if (!response.ok) throw new Error('Unavailable');
|
||||
const data = await response.json(); if (!valid(data)) throw new Error('Invalid response');
|
||||
if (disposed || requestGeneration !== generation) return;
|
||||
for (const state of states) text(document.querySelector('[data-dashboard-count="' + state + '"]'), data.counts[state].toLocaleString());
|
||||
for (const state of ['done', 'failed']) updateRecent(state, data.recent[state]);
|
||||
document.dispatchEvent(new CustomEvent('proxer:status', { detail: data }));
|
||||
if (manual || failed) text(feedback, 'Updated at ' + new Date().toLocaleTimeString() + '. Auto refresh is on.');
|
||||
feedback.classList.remove('feedback-error'); failed = false;
|
||||
} catch {
|
||||
if (disposed || requestGeneration !== generation) return;
|
||||
text(feedback, 'Could not refresh the dashboard. The last loaded results are still shown. Try Refresh to reconnect.');
|
||||
feedback.classList.add('feedback-error'); failed = true;
|
||||
document.dispatchEvent(new CustomEvent('proxer:status-error'));
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
if (requestGeneration === generation) { activeRequest = null; refreshButton.disabled = false; }
|
||||
}
|
||||
}
|
||||
refreshButton.addEventListener('click', () => refresh(true));
|
||||
document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
|
||||
let timer = setInterval(() => refresh(), 10000);
|
||||
window.addEventListener('pagehide', () => { disposed = true; generation++; clearInterval(timer); activeRequest?.abort(); });
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (!event.persisted) return;
|
||||
disposed = false; activeRequest = null; refreshButton.disabled = false;
|
||||
timer = setInterval(() => refresh(), 10000); refresh();
|
||||
});
|
||||
for (const time of document.querySelectorAll('.recent-list time[datetime]')) text(time, displayTime(time.dateTime));
|
||||
})();
|
||||
@@ -0,0 +1,143 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const form = document.getElementById('jobForm');
|
||||
if (!form) return;
|
||||
const modePicker = document.getElementById('download-mode');
|
||||
const modes = Array.from(form.querySelectorAll('input[name="mode"]'));
|
||||
const seriesFields = document.getElementById('series-fields');
|
||||
const videoFields = document.getElementById('video-fields');
|
||||
const id = document.getElementById('series-id');
|
||||
const season = document.getElementById('series-season');
|
||||
const first = document.getElementById('episode-from');
|
||||
const last = document.getElementById('episode-to');
|
||||
const url = document.getElementById('episode-url');
|
||||
const language = document.getElementById('language');
|
||||
const name = document.getElementById('download-name');
|
||||
const token = document.getElementById('download-token');
|
||||
const submit = document.getElementById('queue-download');
|
||||
const toggleToken = document.getElementById('toggle-token');
|
||||
const maximum = Number(form.dataset.maxEpisodes) || 500;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function positive(value) {
|
||||
return /^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value));
|
||||
}
|
||||
|
||||
function watchSource(value) {
|
||||
if (!value || value.length > 2048 || /[\s\\\u0000-\u001f\u007f-\u009f]/u.test(value)) return null;
|
||||
try {
|
||||
const source = new URL(value);
|
||||
if (source.protocol !== 'https:' || !['proxer.me', 'www.proxer.me'].includes(source.hostname)
|
||||
|| /^https:\/\/[^/?#]*@/i.test(value) || source.username || source.password
|
||||
|| (source.port && source.port !== '443') || source.search) return null;
|
||||
const match = source.pathname.match(/^\/watch\/([1-9]\d*)\/([1-9]\d*)\/(engsub|engdub|gersub|gerdub)\/?$/);
|
||||
return match && positive(match[1]) && positive(match[2])
|
||||
? { id: String(Number(match[1])), episode: String(Number(match[2])), language: match[3] } : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function validFilename(value) {
|
||||
return value && value !== '.' && value !== '..'
|
||||
&& !/[\/\\\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/u.test(value)
|
||||
&& encoder.encode(`${value}.mp4`).length <= 255;
|
||||
}
|
||||
|
||||
function preview() {
|
||||
const series = modes.find(input => input.checked)?.value !== 'video';
|
||||
for (const input of [id, season, first, last, url, name, token]) input.setCustomValidity('');
|
||||
let count = null;
|
||||
let firstFilename = '';
|
||||
let lastFilename = '';
|
||||
let invalidMessage = '';
|
||||
const title = name.value.trim();
|
||||
if (series) {
|
||||
const validSeason = /^(0|[1-9]\d*)$/.test(season.value) && Number.isSafeInteger(Number(season.value));
|
||||
if (season.value && !validSeason) season.setCustomValidity('Season must be a whole number of zero or greater within the supported range.');
|
||||
for (const [input, label] of [[id, 'Series ID'], [first, 'First episode'], [last, 'Last episode']]) {
|
||||
if (input.value && !positive(input.value)) input.setCustomValidity(`${label} must be a positive whole number within the supported range.`);
|
||||
}
|
||||
if (positive(first.value) && positive(last.value)) {
|
||||
const from = Number(first.value), to = Number(last.value);
|
||||
if (to < from) invalidMessage = 'The last episode must be greater than or equal to the first.';
|
||||
else if (to - from + 1 > maximum) invalidMessage = `Choose no more than ${maximum.toLocaleString()} episodes per submission.`;
|
||||
else count = to - from + 1;
|
||||
last.setCustomValidity(invalidMessage);
|
||||
if (count !== null && positive(id.value) && validSeason) {
|
||||
const base = title || String(Number(id.value));
|
||||
const seasonText = String(Number(season.value)).padStart(3, '0');
|
||||
firstFilename = `${base}S${seasonText}E${String(from).padStart(3, '0')}_${language.value}`;
|
||||
lastFilename = `${base}S${seasonText}E${String(to).padStart(3, '0')}_${language.value}`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const source = watchSource(url.value);
|
||||
if (url.value && !source) url.setCustomValidity('Enter an HTTPS Proxer watch URL with a series ID, episode and supported language.');
|
||||
if (source) {
|
||||
count = 1;
|
||||
firstFilename = title || `${source.id} E${source.episode} ${source.language}`;
|
||||
}
|
||||
}
|
||||
if ((title && /[\/\\\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/u.test(title))
|
||||
|| (firstFilename && !validFilename(firstFilename)) || (lastFilename && !validFilename(lastFilename))) {
|
||||
invalidMessage = 'Choose a shorter filename without slashes or control characters. The full name including .mp4 must fit within 255 bytes.';
|
||||
name.setCustomValidity(invalidMessage);
|
||||
}
|
||||
if (token.value && /[\s;\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/u.test(token.value)) {
|
||||
token.setCustomValidity('Enter the token value without spaces, control characters or cookie separators.');
|
||||
}
|
||||
document.getElementById('preview-count').textContent = count === null ? '—' : count.toLocaleString();
|
||||
document.getElementById('preview-count-label').textContent = count === 1 ? 'episode to queue' : 'episodes to queue';
|
||||
document.getElementById('filename-preview').textContent = firstFilename ? `${firstFilename}.mp4` : 'Fill in the episode details to see your filenames.';
|
||||
const final = document.getElementById('preview-last');
|
||||
final.hidden = !lastFilename || lastFilename === firstFilename;
|
||||
final.textContent = final.hidden ? '' : `… through ${lastFilename}.mp4`;
|
||||
document.getElementById('preview-validation').textContent = invalidMessage;
|
||||
}
|
||||
|
||||
function updateMode() {
|
||||
const series = modes.find(input => input.checked)?.value !== 'video';
|
||||
seriesFields.hidden = seriesFields.disabled = !series;
|
||||
videoFields.hidden = videoFields.disabled = series;
|
||||
document.getElementById('preview-mode').textContent = series ? 'Series' : 'Single episode';
|
||||
document.getElementById('name-label').textContent = series ? 'Series title' : 'Filename';
|
||||
name.placeholder = series ? 'e.g. My Series' : 'e.g. My SeriesS001E001_engsub';
|
||||
document.getElementById('name-hint').textContent = series
|
||||
? 'Enter the title without season or episode numbers. Season, episode and language are added automatically. Leave blank to use the series ID.'
|
||||
: 'Enter a filename without .mp4. Leave blank to use the series ID, episode and language.';
|
||||
preview();
|
||||
}
|
||||
|
||||
modes.forEach(input => input.addEventListener('change', updateMode));
|
||||
form.addEventListener('input', preview);
|
||||
language.addEventListener('change', preview);
|
||||
toggleToken.hidden = false;
|
||||
toggleToken.addEventListener('click', () => {
|
||||
const showing = token.type === 'password';
|
||||
token.type = showing ? 'text' : 'password';
|
||||
toggleToken.textContent = showing ? 'Hide' : 'Show';
|
||||
toggleToken.setAttribute('aria-pressed', String(showing));
|
||||
});
|
||||
form.addEventListener('submit', event => {
|
||||
preview();
|
||||
if (!form.checkValidity()) {
|
||||
event.preventDefault();
|
||||
form.reportValidity();
|
||||
return;
|
||||
}
|
||||
token.type = 'password';
|
||||
toggleToken.textContent = 'Show';
|
||||
toggleToken.setAttribute('aria-pressed', 'false');
|
||||
submit.disabled = true;
|
||||
submit.textContent = 'Checking access and adding…';
|
||||
});
|
||||
window.addEventListener('pageshow', () => {
|
||||
submit.disabled = false;
|
||||
submit.textContent = 'Add to queue →';
|
||||
updateMode();
|
||||
});
|
||||
modePicker.hidden = false;
|
||||
const checkedAt = document.getElementById('token-checked-at');
|
||||
if (checkedAt) checkedAt.textContent = new Date(checkedAt.dateTime).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
||||
updateMode();
|
||||
document.getElementById('form-error')?.focus();
|
||||
})();
|
||||
@@ -0,0 +1,324 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const view = document.getElementById("queue-view");
|
||||
if (!view) return;
|
||||
const list = document.getElementById("queue-jobs");
|
||||
const form = document.getElementById("queue-filter-form");
|
||||
const feedback = document.getElementById("queue-feedback");
|
||||
const refreshButton = document.getElementById("queue-refresh");
|
||||
const autoButton = document.getElementById("queue-auto-refresh");
|
||||
const clearForm = document.getElementById("queue-clear-state-form");
|
||||
const clearButton = document.getElementById("queue-clear-state-button");
|
||||
const clearActions = {
|
||||
queued: { label: "Clear waiting queue", confirmation: "Remove every waiting episode from the queue, including episodes outside this filter or page? Active downloads will continue." },
|
||||
done: { label: "Clear completed history", confirmation: "Clear all completed download records, including records outside this filter or page? Downloaded files will remain on disk." },
|
||||
failed: { label: "Clear failed history", confirmation: "Clear all failed-attempt records, including records outside this filter or page? Retained queued episodes and files will remain unchanged." }
|
||||
};
|
||||
const states = {
|
||||
queued: { label: "Queued", badge: "badge-neutral", date: "created_at", dateLabel: "Queued",
|
||||
note: "Waiting episodes are taken by available workers when verification is clear.",
|
||||
empty: "Add a series or a single episode to get started." },
|
||||
processing: { label: "Active", badge: "badge-info", date: "started_at", dateLabel: "Started",
|
||||
note: "File size shows the current file on disk. A claimed item may be resolving its source or transferring.",
|
||||
empty: "No episodes are currently claimed by a worker." },
|
||||
done: { label: "Completed", badge: "badge-success", date: "finished_at", dateLabel: "Finished",
|
||||
note: "Completed downloads stay in history until you clear their records.",
|
||||
empty: "Successful downloads will appear here." },
|
||||
failed: { label: "Failed attempts", badge: "badge-danger", date: "failed_at", dateLabel: "Failed",
|
||||
note: "An attempt can appear here even when its retained episode later completes. Check the queue and completed downloads before resubmitting.",
|
||||
empty: "No failed attempts are recorded." }
|
||||
};
|
||||
const languages = { engsub: "English sub", engdub: "English dub", gersub: "German sub", gerdub: "German dub" };
|
||||
let current = {
|
||||
state: view.dataset.state, q: view.dataset.query,
|
||||
page: Number(view.dataset.page), pageSize: Number(view.dataset.pageSize)
|
||||
};
|
||||
let auto = true;
|
||||
let activeRequest = null;
|
||||
let generation = 0;
|
||||
let disposed = false;
|
||||
let lastRefreshFailed = false;
|
||||
let clearAllowed = !clearButton.disabled;
|
||||
|
||||
function parameters(selection) {
|
||||
return new URLSearchParams({
|
||||
state: selection.state, q: selection.q,
|
||||
page: String(selection.page), pageSize: String(selection.pageSize)
|
||||
});
|
||||
}
|
||||
function pageUrl(selection) { return "/status?" + parameters(selection); }
|
||||
function setText(element, value) {
|
||||
const text = String(value == null ? "" : value);
|
||||
if (element.textContent !== text) element.textContent = text;
|
||||
}
|
||||
function element(tag, className, parent) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (parent) parent.append(node);
|
||||
return node;
|
||||
}
|
||||
function safeSource(value) {
|
||||
return typeof value === "string" && /^https:\/\/proxer\.me\/watch\/[1-9]\d*\/[1-9]\d*\/(engsub|engdub|gersub|gerdub)$/.test(value) ? value : "";
|
||||
}
|
||||
function sourceLabel(value) {
|
||||
const parts = safeSource(value).split("/");
|
||||
return parts.length === 7
|
||||
? "Series " + parts[4] + " · Episode " + parts[5] + " · " + languages[parts[6]]
|
||||
: "Source unavailable";
|
||||
}
|
||||
function formatBytes(value) {
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return "—";
|
||||
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
|
||||
const index = value > 0 ? Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1) : 0;
|
||||
return (value / Math.pow(1024, index)).toFixed(index === 0 ? 0 : 1) + " " + units[index];
|
||||
}
|
||||
function formatTime(value) {
|
||||
const date = new Date(value);
|
||||
return value && Number.isFinite(date.getTime())
|
||||
? date.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })
|
||||
: "Not recorded";
|
||||
}
|
||||
|
||||
function createRow() {
|
||||
const row = element("li", "job-row");
|
||||
const primary = element("div", "job-primary", row);
|
||||
element("strong", "job-filename", primary);
|
||||
element("a", "job-source", primary);
|
||||
const status = element("div", "job-state", row);
|
||||
element("span", "badge", status);
|
||||
element("span", "job-error-category muted", status);
|
||||
const time = element("div", "job-time", row);
|
||||
element("span", "job-time-label muted", time);
|
||||
element("time", "", time);
|
||||
const size = element("div", "job-size", row);
|
||||
element("span", "job-size-value", size);
|
||||
element("small", "muted", size);
|
||||
const details = element("details", "job-log", row);
|
||||
element("summary", "", details);
|
||||
element("pre", "log-output", details).tabIndex = 0;
|
||||
return row;
|
||||
}
|
||||
|
||||
function updateRow(row, job, state) {
|
||||
const info = states[state];
|
||||
row.dataset.jobId = String(job._id);
|
||||
row.dataset.jobState = state;
|
||||
setText(row.querySelector(".job-filename"), job.filename);
|
||||
const source = row.querySelector(".job-source");
|
||||
const sourceUrl = safeSource(job.url);
|
||||
if (sourceUrl) {
|
||||
source.href = sourceUrl;
|
||||
source.target = "_blank";
|
||||
source.rel = "noopener noreferrer";
|
||||
} else {
|
||||
source.removeAttribute("href");
|
||||
source.removeAttribute("target");
|
||||
source.removeAttribute("rel");
|
||||
}
|
||||
setText(source, sourceLabel(job.url));
|
||||
const badge = row.querySelector(".badge");
|
||||
badge.className = "badge " + info.badge;
|
||||
setText(badge, info.label);
|
||||
setText(row.querySelector(".job-error-category"), job.error_category || "");
|
||||
setText(row.querySelector(".job-time-label"), state === "processing" && !job.started_at ? "Queued" : info.dateLabel);
|
||||
const time = row.querySelector("time");
|
||||
const timestamp = job[info.date] || job.created_at;
|
||||
if (timestamp && Number.isFinite(new Date(timestamp).getTime())) time.dateTime = timestamp;
|
||||
else time.removeAttribute("datetime");
|
||||
setText(time, formatTime(timestamp));
|
||||
setText(row.querySelector(".job-size-value"), formatBytes(job.fileSize));
|
||||
setText(row.querySelector(".job-size small"), typeof job.fileSize === "number" ? "on disk" : "not available");
|
||||
const details = row.querySelector(".job-log");
|
||||
details.hidden = !job.output_log;
|
||||
setText(details.querySelector("summary"), state === "failed" ? "View attempt log" : "View log");
|
||||
const log = details.querySelector("pre");
|
||||
const scrollTop = log.scrollTop;
|
||||
setText(log, job.output_log || "");
|
||||
log.scrollTop = scrollTop;
|
||||
}
|
||||
|
||||
function renderRows(items, state) {
|
||||
const existing = new Map(Array.from(list.children, row => [
|
||||
row.dataset.jobState + ":" + row.dataset.jobId, row
|
||||
]));
|
||||
let cursor = list.firstElementChild;
|
||||
for (const job of items) {
|
||||
const key = state + ":" + String(job._id);
|
||||
const row = existing.get(key) || createRow();
|
||||
existing.delete(key);
|
||||
updateRow(row, job, state);
|
||||
// Leave unchanged nodes in place so focus, expanded logs and log scrolling survive polling.
|
||||
if (row === cursor) cursor = cursor.nextElementSibling;
|
||||
else list.insertBefore(row, cursor);
|
||||
}
|
||||
for (const row of existing.values()) {
|
||||
if (row.contains(document.activeElement)) refreshButton.focus({ preventScroll: true });
|
||||
row.remove();
|
||||
}
|
||||
list.setAttribute("aria-label", states[state].label);
|
||||
}
|
||||
|
||||
function validSnapshot(data) {
|
||||
const whole = value => Number.isSafeInteger(value) && value >= 0;
|
||||
return data && Array.isArray(data.items) && data.items.length <= 50
|
||||
&& data.items.every(job => job && typeof job._id === "string" && typeof job.filename === "string")
|
||||
&& data.filters && Object.hasOwn(states, data.filters.state) && typeof data.filters.q === "string"
|
||||
&& data.pagination && whole(data.pagination.total) && whole(data.pagination.page)
|
||||
&& data.pagination.page >= 1 && whole(data.pagination.totalPages) && data.pagination.totalPages >= 1
|
||||
&& [10, 25, 50].includes(data.pagination.pageSize)
|
||||
&& data.counts && Object.keys(states).every(state => whole(data.counts[state]))
|
||||
&& window.ProxerActivity?.valid(data.activity);
|
||||
}
|
||||
|
||||
function renderSnapshot(data) {
|
||||
const info = states[current.state];
|
||||
const clearAction = clearActions[current.state];
|
||||
clearForm.hidden = !clearAction;
|
||||
clearForm.dataset.confirm = clearAction?.confirmation || "";
|
||||
document.getElementById("queue-clear-state").value = current.state;
|
||||
setText(clearButton, clearAction?.label || "Clear records");
|
||||
document.getElementById("queue-active-protected").hidden = Boolean(clearAction);
|
||||
clearAllowed = Boolean(clearAction) && data.counts[current.state] > 0;
|
||||
setText(document.getElementById("queue-title"), info.label);
|
||||
setText(document.getElementById("queue-state-note"), info.note);
|
||||
for (const link of document.querySelectorAll("[data-state-link]")) {
|
||||
const state = link.dataset.stateLink;
|
||||
const selected = state === current.state;
|
||||
link.classList.toggle("is-selected", selected);
|
||||
if (selected) link.setAttribute("aria-current", "page");
|
||||
else link.removeAttribute("aria-current");
|
||||
link.href = pageUrl({ ...current, state, page: 1 });
|
||||
setText(link.querySelector("[data-state-count]"), data.counts[state]);
|
||||
}
|
||||
document.getElementById("queue-state").value = current.state;
|
||||
const clearLink = document.getElementById("queue-clear-filter");
|
||||
clearLink.hidden = !current.q;
|
||||
clearLink.href = pageUrl({ ...current, q: "", page: 1 });
|
||||
renderRows(data.items, current.state);
|
||||
document.getElementById("queue-empty").hidden = data.items.length !== 0;
|
||||
setText(document.getElementById("queue-empty-title"), current.q ? "No matching filenames" : "No " + info.label.toLowerCase());
|
||||
setText(document.getElementById("queue-empty-message"), current.q ? "Try a shorter search or choose another state." : info.empty);
|
||||
const pagination = data.pagination;
|
||||
const start = (pagination.page - 1) * pagination.pageSize + 1;
|
||||
const end = Math.min(pagination.page * pagination.pageSize, pagination.total);
|
||||
setText(document.getElementById("queue-range"), pagination.total
|
||||
? start + "–" + end + " of " + pagination.total + (current.q ? " matches" : "")
|
||||
: "0 results");
|
||||
setText(document.getElementById("queue-page-label"), "Page " + pagination.page + " of " + pagination.totalPages);
|
||||
for (const link of document.querySelectorAll("[data-page-link]")) {
|
||||
const previous = link.dataset.pageLink === "previous";
|
||||
const disabled = previous ? current.page <= 1 : current.page >= pagination.totalPages;
|
||||
link.setAttribute("aria-disabled", String(disabled));
|
||||
link.tabIndex = disabled ? -1 : 0;
|
||||
link.href = pageUrl({ ...current, page: previous ? Math.max(1, current.page - 1) : Math.min(pagination.totalPages, current.page + 1) });
|
||||
}
|
||||
Object.assign(view.dataset, { state: current.state, page: String(current.page), pageSize: String(current.pageSize), query: current.q });
|
||||
document.dispatchEvent(new CustomEvent("proxer:status", { detail: data }));
|
||||
}
|
||||
|
||||
async function refresh(next = current, mode = "auto") {
|
||||
if (disposed || (mode === "auto" && (document.hidden || !auto || activeRequest))) return;
|
||||
if (activeRequest) activeRequest.abort();
|
||||
const request = new AbortController();
|
||||
const requestGeneration = ++generation;
|
||||
activeRequest = request;
|
||||
refreshButton.disabled = true;
|
||||
clearButton.disabled = true;
|
||||
view.setAttribute("aria-busy", "true");
|
||||
const timeout = setTimeout(() => request.abort(), 15000);
|
||||
try {
|
||||
const response = await fetch("/status-data?" + parameters(next), { cache: "no-store", signal: request.signal });
|
||||
if (!response.ok) throw new Error("Unavailable");
|
||||
const data = await response.json();
|
||||
if (!validSnapshot(data)) throw new Error("Invalid response");
|
||||
if (requestGeneration !== generation || disposed) return;
|
||||
current = { ...data.filters, page: data.pagination.page, pageSize: data.pagination.pageSize };
|
||||
renderSnapshot(data);
|
||||
if (mode === "navigate" || mode === "popstate") {
|
||||
document.getElementById("queue-query").value = current.q;
|
||||
document.getElementById("queue-page-size").value = String(current.pageSize);
|
||||
}
|
||||
if (mode === "navigate") history.pushState(null, "", pageUrl(current));
|
||||
else if (mode === "popstate" || current.page !== next.page) history.replaceState(null, "", pageUrl(current));
|
||||
if (mode !== "auto" || lastRefreshFailed) {
|
||||
setText(feedback, "Updated at " + new Date().toLocaleTimeString() + (auto ? ". Auto refresh is on." : ". Auto refresh is off."));
|
||||
}
|
||||
feedback.classList.remove("feedback-error");
|
||||
lastRefreshFailed = false;
|
||||
} catch {
|
||||
if (requestGeneration !== generation || disposed) return;
|
||||
setText(feedback, "Could not refresh the queue. The last loaded results are still shown. Try Refresh to reconnect.");
|
||||
feedback.classList.add("feedback-error");
|
||||
lastRefreshFailed = true;
|
||||
document.dispatchEvent(new CustomEvent("proxer:status-error"));
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
if (requestGeneration === generation) {
|
||||
activeRequest = null;
|
||||
refreshButton.disabled = false;
|
||||
clearButton.disabled = !clearAllowed || lastRefreshFailed;
|
||||
view.setAttribute("aria-busy", "false");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
form.addEventListener("submit", event => {
|
||||
event.preventDefault();
|
||||
if (!form.reportValidity()) return;
|
||||
refresh({
|
||||
state: current.state,
|
||||
q: document.getElementById("queue-query").value.trim(),
|
||||
pageSize: Number(document.getElementById("queue-page-size").value), page: 1
|
||||
}, "navigate");
|
||||
});
|
||||
clearForm.addEventListener("submit", event => {
|
||||
if (activeRequest || lastRefreshFailed || !clearAllowed) event.preventDefault();
|
||||
});
|
||||
document.addEventListener("click", event => {
|
||||
const link = event.target.closest("[data-state-link], [data-page-link], #queue-clear-filter");
|
||||
if (!link || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
event.preventDefault();
|
||||
if (link.getAttribute("aria-disabled") === "true") return;
|
||||
const params = new URL(link.href).searchParams;
|
||||
refresh({
|
||||
state: params.get("state") || "queued", q: params.get("q") || "",
|
||||
page: Number(params.get("page") || 1), pageSize: Number(params.get("pageSize") || 25)
|
||||
}, "navigate");
|
||||
});
|
||||
refreshButton.addEventListener("click", () => refresh(current, "manual"));
|
||||
autoButton.addEventListener("click", () => {
|
||||
auto = !auto;
|
||||
autoButton.setAttribute("aria-pressed", String(auto));
|
||||
setText(autoButton, "Auto refresh: " + (auto ? "on" : "off"));
|
||||
setText(feedback, auto ? "Updates every 10 seconds while this page is visible." : "Auto refresh is off. Use Refresh when you are ready.");
|
||||
if (auto) refresh();
|
||||
});
|
||||
window.addEventListener("popstate", () => {
|
||||
const params = new URLSearchParams(location.search);
|
||||
refresh({
|
||||
state: params.get("state") || "queued", q: params.get("q") || "",
|
||||
page: Number(params.get("page") || 1), pageSize: Number(params.get("pageSize") || 25)
|
||||
}, "popstate");
|
||||
});
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(); });
|
||||
let timer = setInterval(() => refresh(), 10000);
|
||||
window.addEventListener("pagehide", () => {
|
||||
disposed = true;
|
||||
generation++;
|
||||
clearInterval(timer);
|
||||
activeRequest?.abort();
|
||||
});
|
||||
window.addEventListener("pageshow", event => {
|
||||
if (!event.persisted) return;
|
||||
disposed = false;
|
||||
activeRequest = null;
|
||||
refreshButton.disabled = false;
|
||||
clearButton.disabled = !clearAllowed || lastRefreshFailed;
|
||||
view.setAttribute("aria-busy", "false");
|
||||
timer = setInterval(() => refresh(), 10000);
|
||||
refresh();
|
||||
});
|
||||
// Server-rendered timestamps are immediately localized without changing row identity.
|
||||
for (const time of list.querySelectorAll("time[datetime]")) setText(time, formatTime(time.dateTime));
|
||||
})();
|
||||
+446
-216
@@ -1,222 +1,452 @@
|
||||
/* ===============================
|
||||
GLOBAL STYLING — Dark Grey Theme
|
||||
=============================== */
|
||||
/* Shared application shell. Assets stay local so the UI also works without a CDN. */
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--background: #101519;
|
||||
--surface: #181f25;
|
||||
--surface-raised: #202a32;
|
||||
--surface-input: #11191f;
|
||||
--border: #2d3943;
|
||||
--border-soft: #26313a;
|
||||
--text: #edf2f5;
|
||||
--muted: #a2b1bd;
|
||||
--faint: #8696a3;
|
||||
--accent: #80ddca;
|
||||
--accent-ink: #102a25;
|
||||
--accent-soft: #213d37;
|
||||
--blue: #a6caff;
|
||||
--warning: #efc77e;
|
||||
--danger: #ffaaa0;
|
||||
--radius: 12px;
|
||||
--content-width: 1320px;
|
||||
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: 15px;
|
||||
line-height: 1.55;
|
||||
font-synthesis: none;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
body { margin: 0; min-width: 300px; background: var(--background); color: var(--text); }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button, input, select, textarea, a, summary { -webkit-tap-highlight-color: transparent; }
|
||||
button { cursor: pointer; }
|
||||
button:disabled { cursor: not-allowed; opacity: .5; }
|
||||
a { color: var(--accent); text-underline-offset: 3px; }
|
||||
a:hover { color: #b1f3e5; }
|
||||
h1, h2, h3, p, dl { margin: 0; }
|
||||
fieldset { min-width: 0; margin: 0; padding: 0; border: 0; }
|
||||
legend { padding: 0; }
|
||||
button, a, summary, input, select { touch-action: manipulation; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
|
||||
::selection { background: var(--accent-soft); color: #fff; }
|
||||
input::placeholder { color: var(--faint); opacity: 1; }
|
||||
input[type="number"] { appearance: textfield; }
|
||||
input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
.visually-hidden, .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.muted { color: var(--muted); }
|
||||
.small, small { font-size: .82rem; }
|
||||
.skip-link { position: fixed; z-index: 100; top: 10px; left: 14px; transform: translateY(-160%); background: var(--accent); color: var(--accent-ink); padding: 10px 16px; border-radius: 6px; font-weight: 700; }
|
||||
.skip-link:focus { transform: translateY(0); }
|
||||
|
||||
body {
|
||||
background: #2C2C2C; /* dark grey */
|
||||
color: #E0E0E0; /* soft light grey text */
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
/* Navigation and shared state */
|
||||
.topbar { position: sticky; top: 0; z-index: 20; background: #151c22; border-bottom: 1px solid var(--border); }
|
||||
.topbar-inner { display: flex; align-items: center; gap: 38px; max-width: var(--content-width); min-height: 80px; padding: 0 32px; margin: auto; }
|
||||
.brand { display: flex; align-items: center; flex: 0 0 auto; gap: 11px; color: var(--text); text-decoration: none; }
|
||||
.brand:hover { color: var(--text); }
|
||||
.brand-mark { display: grid; place-items: center; width: 37px; height: 37px; background: var(--accent); border-radius: 10px; color: var(--accent-ink); }
|
||||
.brand-mark svg { width: 25px; height: 25px; }
|
||||
.brand-text { display: flex; flex-direction: column; font-size: 1.12rem; font-weight: 750; line-height: 1.17; letter-spacing: -.02em; }
|
||||
.brand-text > span { color: var(--muted); font-size: .73rem; font-weight: 500; letter-spacing: .035em; }
|
||||
.main-nav { display: flex; align-self: stretch; align-items: stretch; gap: 8px; }
|
||||
.nav-link { display: flex; align-items: center; gap: 8px; position: relative; padding: 0 16px; color: var(--muted); font-size: .9rem; font-weight: 600; text-decoration: none; white-space: nowrap; }
|
||||
.nav-link:hover { color: var(--text); background: #1b242b; }
|
||||
.nav-link.is-active { color: var(--accent); }
|
||||
.nav-link.is-active::after { content: ""; position: absolute; bottom: -1px; height: 3px; left: 16px; right: 16px; background: var(--accent); border-radius: 3px 3px 0 0; }
|
||||
.nav-count { display: inline-flex; justify-content: center; min-width: 21px; padding: 1px 6px; border-radius: 5px; background: var(--surface-raised); font-size: .7rem; line-height: 1.5; font-variant-numeric: tabular-nums; color: var(--muted); }
|
||||
.nav-link.is-active .nav-count { background: var(--accent-soft); color: var(--accent); }
|
||||
.connection-status { display: inline-flex; align-items: center; gap: 8px; margin-left: auto; padding: 6px 10px; color: var(--muted); border: 1px solid var(--border); border-radius: 6px; font-size: .76rem; white-space: nowrap; }
|
||||
.status-dot { width: 6px; height: 6px; flex: 0 0 auto; border-radius: 50%; background: var(--faint); }
|
||||
.connection-status.is-ready .status-dot { background: var(--accent); }
|
||||
.connection-status.is-paused { color: var(--warning); border-color: #65502d; }
|
||||
.connection-status.is-paused .status-dot, .connection-status.is-stale .status-dot { background: var(--warning); }
|
||||
.connection-status.is-stale { color: var(--warning); }
|
||||
.notice-wrap { max-width: var(--content-width); padding: 0 32px; margin: auto; }
|
||||
.verification-notice { display: flex; gap: 24px; align-items: center; justify-content: space-between; margin-top: 24px; padding: 18px 22px; background: #2d281e; border: 1px solid #65502d; border-radius: var(--radius); }
|
||||
.notice-copy { display: flex; flex-direction: column; gap: 5px; }
|
||||
.notice-copy > strong { color: var(--warning); font-size: .92rem; }
|
||||
.notice-copy > span { color: #e1ceb0; font-size: .85rem; }
|
||||
.verification-notice form { flex-shrink: 0; }
|
||||
|
||||
/* Layout and common controls */
|
||||
.app-main { max-width: var(--content-width); min-height: calc(100vh - 180px); margin: 0 auto; padding: 36px 32px 48px; }
|
||||
.page-heading { display: flex; align-items: center; justify-content: space-between; gap: 24px; margin-bottom: 30px; }
|
||||
.eyebrow { color: var(--faint); font-size: .67rem; font-weight: 700; letter-spacing: .14em; margin-bottom: 9px; }
|
||||
.page-title { font-size: clamp(1.8rem, 3vw, 2.18rem); line-height: 1.2; letter-spacing: -.035em; font-weight: 650; }
|
||||
.page-description { color: var(--muted); margin-top: 9px; max-width: 750px; font-size: .9rem; }
|
||||
.panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); min-width: 0; overflow: clip; }
|
||||
.panel-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 20px 24px; border-bottom: 1px solid var(--border-soft); }
|
||||
.panel-header h2 { font-size: 1rem; font-weight: 650; letter-spacing: -.015em; }
|
||||
.panel-body { padding: 24px; }
|
||||
.button { display: inline-flex; align-items: center; justify-content: center; gap: 9px; min-height: 42px; padding: 9px 16px; border: 1px solid transparent; border-radius: 7px; font-size: .86rem; font-weight: 650; line-height: 1.4; color: var(--text); background: var(--surface-raised); text-decoration: none; transition: background-color .15s, border-color .15s; }
|
||||
.button:hover { background: #2b3740; color: var(--text); }
|
||||
.button-primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
|
||||
.button-primary:hover { background: #a0ebdc; color: var(--accent-ink); border-color: #a0ebdc; }
|
||||
.button-secondary { background: transparent; border-color: #3b4a56; }
|
||||
.button-secondary:hover { background: var(--surface-raised); border-color: #5c7180; }
|
||||
.button-ghost { background: transparent; color: var(--muted); }
|
||||
.button-ghost:hover { background: var(--surface-raised); }
|
||||
.button-danger { color: var(--danger); background: #372724; border-color: #64413b; }
|
||||
.button-danger:hover { color: #ffd6cf; background: #4a2d29; border-color: #996056; }
|
||||
.button-warning { color: #f7d69d; background: #48391e; border-color: #856839; }
|
||||
.button-warning:hover { color: #ffdfac; background: #5a4623; }
|
||||
.button-small { min-height: 34px; padding: 6px 11px; font-size: .79rem; }
|
||||
.button[aria-disabled="true"] { pointer-events: none; opacity: .45; }
|
||||
.button-group, .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
|
||||
.page-actions { display: flex; align-items: center; flex-wrap: wrap; justify-content: end; gap: 14px; }
|
||||
.badge { display: inline-flex; align-items: center; justify-content: center; padding: 3px 8px; border: 1px solid transparent; border-radius: 5px; font-size: .7rem; font-weight: 600; line-height: 1.6; white-space: nowrap; }
|
||||
.badge-neutral { background: #27323c; color: #c4d0db; border-color: #354451; }
|
||||
.badge-success, .status-online { background: #203a32; color: #9de4c3; border-color: #315645; }
|
||||
.badge-warning, .status-pending { background: #3e3321; color: #f1d399; border-color: #5f4d30; }
|
||||
.badge-danger, .status-stopped { background: #3f2a2a; color: #ffb7ad; border-color: #5d3a36; }
|
||||
.badge-info, .badge-active { background: #23374b; color: #adceff; border-color: #35516c; }
|
||||
.field { min-width: 0; }
|
||||
.field-label { display: block; font-size: .83rem; font-weight: 550; color: #d5dfe6; margin-bottom: 8px; }
|
||||
.field-label > span[aria-hidden] { color: var(--accent); }
|
||||
.field-input, .input { width: 100%; min-height: 44px; padding: 10px 12px; border: 1px solid #3c4b57; border-radius: 7px; background: var(--surface-input); color: var(--text); line-height: 1.4; font-size: .9rem; }
|
||||
select.field-input { padding-right: 30px; }
|
||||
.field-input:focus, .input:focus { border-color: var(--accent); outline: 2px solid #80ddca33; outline-offset: 1px; }
|
||||
.field-input[aria-invalid="true"] { border-color: var(--danger); }
|
||||
.field-hint { color: var(--muted); font-size: .77rem; line-height: 1.6; margin-top: 7px; overflow-wrap: anywhere; }
|
||||
.optional { margin-left: 5px; color: var(--faint); font-size: .73rem; font-weight: 400; }
|
||||
.inline-notice, .notice { margin-bottom: 20px; padding: 14px 16px; border: 1px solid var(--border); background: var(--surface-raised); border-radius: 8px; font-size: .88rem; }
|
||||
.inline-notice p { margin-top: 5px; }
|
||||
.notice-error, .notice-danger { color: #ffc2b8; border-color: #6f4540; background: #3b2928; }
|
||||
.notice-success { color: #afe6cc; border-color: #35624e; background: #203b30; }
|
||||
.notice-warning { color: #f1d399; border-color: #65502d; background: #352d20; }
|
||||
.empty-state { text-align: center; padding: 56px 24px; color: var(--muted); }
|
||||
.empty-state h2, .empty-state h3, .empty-state strong { color: var(--text); font-size: 1.05rem; font-weight: 550; }
|
||||
.empty-state p { margin: 7px auto 16px; max-width: 450px; font-size: .85rem; }
|
||||
.app-footer { display: flex; justify-content: space-between; gap: 20px; max-width: var(--content-width); margin: 0 auto; padding: 20px 32px 26px; color: var(--faint); font-size: .73rem; border-top: 1px solid var(--border-soft); }
|
||||
.error-panel { max-width: 760px; margin: 40px auto; }
|
||||
.error-panel .panel-body { padding: 36px; }
|
||||
.error-panel .button-group { margin-top: 26px; }
|
||||
|
||||
/* Download form */
|
||||
.download-layout { display: grid; grid-template-columns: minmax(0, 1fr) 340px; align-items: start; gap: 24px; }
|
||||
.download-sidebar { display: grid; gap: 20px; position: sticky; top: 104px; }
|
||||
.mode-switch { display: flex; gap: 12px; margin-bottom: 29px; }
|
||||
.mode-choice { position: relative; flex: 1; cursor: pointer; }
|
||||
.mode-choice input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; margin: 0; cursor: pointer; }
|
||||
.mode-choice > span { display: flex; flex-direction: column; gap: 3px; padding: 13px 16px; border: 1px solid #3c4b57; border-radius: 8px; background: var(--surface-input); }
|
||||
.mode-choice strong { font-size: .88rem; font-weight: 650; }
|
||||
.mode-choice small { color: var(--muted); font-size: .73rem; }
|
||||
.mode-choice input:checked + span { border-color: var(--accent); background: #21342f; }
|
||||
.mode-choice input:checked + span > strong { color: var(--accent); }
|
||||
.mode-choice input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 4px; }
|
||||
.mode-choice:hover > span { border-color: #718d9c; }
|
||||
.form-section { padding-top: 25px; margin-top: 24px; border-top: 1px solid var(--border-soft); }
|
||||
#series-fields, #video-fields { padding-top: 0; margin-top: 0; border-top: 0; }
|
||||
.section-label { display: flex; align-items: center; gap: 9px; margin-bottom: 18px; color: var(--faint); font-size: .72rem; font-weight: 500; }
|
||||
.section-label > span { color: var(--text); font-size: .9rem; font-weight: 600; }
|
||||
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
|
||||
.input-with-action { display: flex; align-items: stretch; position: relative; }
|
||||
.input-with-action .field-input { padding-right: 64px; }
|
||||
.input-action { position: absolute; right: 7px; top: 7px; bottom: 7px; border: 0; border-radius: 4px; padding: 2px 8px; color: var(--muted); background: var(--surface-raised); font-size: .72rem; }
|
||||
.input-action:hover { color: var(--text); }
|
||||
.form-actions { display: flex; align-items: center; gap: 18px; border-top: 1px solid var(--border-soft); margin-top: 26px; padding-top: 24px; }
|
||||
.form-actions > .button { flex-shrink: 0; }
|
||||
.preview-count { display: flex; flex-direction: column; gap: 7px; margin-bottom: 24px; }
|
||||
.preview-count > strong { font-size: 2.8rem; line-height: 1.15; font-weight: 600; letter-spacing: -.04em; color: var(--accent); }
|
||||
.preview-count > span { color: var(--muted); font-size: .85rem; }
|
||||
.preview-section { padding-top: 20px; margin-top: 20px; border-top: 1px solid var(--border-soft); }
|
||||
.preview-section h3 { color: var(--faint); font-size: .7rem; letter-spacing: .06em; text-transform: uppercase; font-weight: 650; margin-bottom: 10px; }
|
||||
.preview-filename, .destination-path { overflow-wrap: anywhere; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: .8rem; line-height: 1.75; }
|
||||
.destination-path { color: var(--accent); }
|
||||
.preview-validation { font-size: .8rem; line-height: 1.6; color: var(--warning); }
|
||||
.preview-validation:not(:empty) { margin-top: 18px; }
|
||||
.help-card { display: flex; align-items: start; gap: 12px; padding: 20px 8px; }
|
||||
.help-icon { display: grid; place-items: center; flex: 0 0 auto; width: 20px; height: 20px; border-radius: 50%; color: var(--muted); border: 1px solid #59707d; font-size: .75rem; font-family: Georgia, serif; font-style: italic; }
|
||||
.help-card h2 { font-size: .85rem; font-weight: 600; margin-bottom: 8px; }
|
||||
.help-card p { color: var(--muted); font-size: .8rem; line-height: 1.75; }
|
||||
.help-card strong { font-weight: 550; color: #c4d2dc; }
|
||||
|
||||
/* Queue and history */
|
||||
.queue-overview { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 26px; }
|
||||
.queue-stat { display: flex; flex-direction: column; gap: 5px; padding: 18px 21px; color: var(--text); text-decoration: none; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); }
|
||||
.queue-stat:hover { color: var(--text); border-color: #657c8c; background: #1c262d; }
|
||||
.queue-stat.is-selected { background: #1d302d; border-color: #68b9a8; }
|
||||
.queue-stat-label { color: #bac8d2; font-size: .8rem; font-weight: 550; }
|
||||
.queue-stat-count { font-size: 2rem; line-height: 1.25; font-weight: 600; letter-spacing: -.025em; font-variant-numeric: tabular-nums; }
|
||||
.queue-stat.is-selected .queue-stat-count { color: var(--accent); }
|
||||
.queue-stat-note { color: var(--faint); font-size: .72rem; }
|
||||
.queue-filters { display: flex; flex-wrap: wrap; align-items: end; gap: 14px; padding: 20px 24px; border-bottom: 1px solid var(--border-soft); }
|
||||
.queue-filters > .field:first-child, .queue-filters .field-grow { flex: 1 1 260px; }
|
||||
.queue-filters > .field:not(:first-child) { flex: 0 0 130px; }
|
||||
.queue-filters > .field.queue-search { flex: 1 1 260px; }
|
||||
.queue-filters .field-label { font-size: .75rem; margin-bottom: 7px; }
|
||||
.queue-filters .button { min-height: 44px; }
|
||||
.panel-body > .queue-filters { padding: 0; border: 0; }
|
||||
#queue-state-note { font-size: .79rem; margin-top: 5px; }
|
||||
.job-error-category { display: block; font-size: .69rem; margin-top: 5px; overflow-wrap: anywhere; }
|
||||
.queue-columns, .job-row { display: grid; grid-template-columns: minmax(0, 1fr) 120px 175px 110px; column-gap: 22px; align-items: center; }
|
||||
.queue-columns { padding: 13px 24px; color: var(--faint); font-size: .67rem; letter-spacing: .07em; text-transform: uppercase; border-bottom: 1px solid var(--border-soft); }
|
||||
.job-list { margin: 0; padding: 0; list-style: none; }
|
||||
.job-row { padding: 20px 24px; border-bottom: 1px solid var(--border-soft); }
|
||||
.job-row:last-child { border-bottom: 0; }
|
||||
.job-row:hover { background: #1a242b; }
|
||||
.job-primary, .job-time, .job-size, .job-state { min-width: 0; }
|
||||
.job-filename { display: block; color: var(--text); font-size: .9rem; font-weight: 600; overflow-wrap: anywhere; }
|
||||
.job-source { display: block; margin-top: 5px; color: var(--muted); font-size: .73rem; overflow-wrap: anywhere; }
|
||||
.job-source:hover { color: var(--accent); }
|
||||
.job-id { display: block; margin-top: 3px; color: var(--faint); font-size: .7rem; overflow-wrap: anywhere; }
|
||||
.job-time { font-size: .77rem; color: #bfccd5; }
|
||||
.job-time time { display: block; }
|
||||
.job-time-label { display: block; color: var(--faint); font-size: .69rem; margin-bottom: 3px; }
|
||||
.job-size-value { display: block; color: #d4dfe7; font-size: .8rem; font-variant-numeric: tabular-nums; }
|
||||
.job-size small { display: block; margin-top: 3px; color: var(--faint); font-size: .69rem; }
|
||||
.job-log { grid-column: 1 / -1; margin-top: 12px; }
|
||||
details > summary { cursor: pointer; font-size: .78rem; color: var(--muted); }
|
||||
details > summary:hover { color: var(--text); }
|
||||
.job-log[open] > summary { color: var(--accent); margin-bottom: 10px; }
|
||||
.log-output, .log-view { margin: 0; padding: 18px; overflow: auto; border: 1px solid var(--border-soft); border-radius: 8px; color: #cad9e3; background: #10171c; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: .77rem; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; tab-size: 2; max-height: 26rem; }
|
||||
.queue-pagination { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 14px; padding: 18px 24px; border-top: 1px solid var(--border-soft); color: var(--muted); font-size: .8rem; }
|
||||
.queue-pagination > div, .queue-pagination nav { display: flex; align-items: center; gap: 10px; }
|
||||
.queue-actions { margin-top: 24px; border-top: 1px solid var(--border-soft); padding-top: 18px; }
|
||||
.queue-actions > summary { color: var(--faint); font-size: .8rem; }
|
||||
.queue-actions[open] > summary { margin-bottom: 15px; }
|
||||
.queue-actions p { color: var(--muted); font-size: .8rem; max-width: 780px; margin: 10px 0 16px; }
|
||||
.queue-actions form { display: inline-block; margin: 0 8px 8px 0; }
|
||||
#queue-feedback { color: var(--muted); font-size: .77rem; }
|
||||
#queue-feedback.is-error { color: var(--warning); }
|
||||
#queue-feedback.feedback-error { color: var(--warning); }
|
||||
|
||||
/* Worker management */
|
||||
.workers-layout { display: grid; grid-template-columns: 360px minmax(0, 1fr); gap: 24px; align-items: start; }
|
||||
.worker-workspace { display: grid; gap: 24px; min-width: 0; }
|
||||
.workers-layout > .panel > .panel-body { padding: 0; }
|
||||
.worker-list { list-style: none; padding: 12px; margin: 0; display: grid; gap: 7px; max-height: 440px; overflow-y: auto; }
|
||||
.worker-list-item { min-width: 0; }
|
||||
.worker-row { width: 100%; text-align: left; padding: 14px; background: transparent; color: var(--text); border: 1px solid transparent; border-radius: 8px; }
|
||||
.worker-row:hover { background: var(--surface-raised); border-color: var(--border); }
|
||||
.worker-row.is-selected { border-color: #68b9a8; background: #21352f; }
|
||||
.worker-row-heading, .worker-summary { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.worker-name { color: var(--text); font-size: .88rem; font-weight: 600; overflow-wrap: anywhere; }
|
||||
.worker-row-meta, .worker-metrics, .worker-counts { color: var(--muted); font-size: .74rem; margin-top: 6px; }
|
||||
.worker-row-meta { display: block; }
|
||||
.worker-metrics { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px; }
|
||||
.worker-create { padding: 20px 24px; border-top: 1px solid var(--border-soft); }
|
||||
.worker-create h3 { font-size: .9rem; font-weight: 600; margin-bottom: 17px; }
|
||||
.worker-create > .button { margin-top: 15px; }
|
||||
.inline-form { display: flex; gap: 8px; align-items: end; }
|
||||
.inline-form .field { flex: 1; min-width: 0; }
|
||||
.worker-create .field-hint { margin-top: 9px; }
|
||||
.worker-controls { min-width: 0; }
|
||||
.worker-actions { display: flex; flex-wrap: wrap; gap: 9px; margin: 0 0 22px; }
|
||||
.worker-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 20px 0; }
|
||||
.worker-stats > div { padding: 13px 15px; border: 1px solid var(--border-soft); background: var(--surface-input); border-radius: 8px; }
|
||||
.worker-stats dt { color: var(--faint); font-size: .71rem; }
|
||||
.worker-stats dd { margin: 5px 0 0; color: var(--text); font-size: 1.1rem; font-weight: 550; font-variant-numeric: tabular-nums; }
|
||||
.worker-details { font-size: .8rem; }
|
||||
.worker-details > dl { display: grid; gap: 9px; margin-top: 14px; }
|
||||
.worker-details > dl > div { display: grid; grid-template-columns: 110px minmax(0, 1fr); column-gap: 18px; }
|
||||
.worker-details dt { color: var(--faint); }
|
||||
.worker-details dd { margin: 0; color: #c8d5df; overflow-wrap: anywhere; }
|
||||
.worker-selection-empty { padding: 42px 24px; color: var(--muted); text-align: center; }
|
||||
.worker-selection-empty .empty-state { padding: 0; }
|
||||
.worker-selection-empty h2 { color: var(--text); font-size: 1rem; font-weight: 550; margin-bottom: 8px; }
|
||||
.worker-selection-empty p { font-size: .85rem; }
|
||||
.action-message { padding: 12px 15px; border: 1px solid var(--border); background: var(--surface-input); color: var(--muted); border-radius: 8px; font-size: .8rem; overflow-wrap: anywhere; }
|
||||
.action-message.is-error { border-color: #70443e; background: #3a2926; color: var(--danger); }
|
||||
.action-message.is-success { border-color: #3e6555; background: #20372e; color: #b4e7ce; }
|
||||
.log-panel { min-width: 0; }
|
||||
.log-toolbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; }
|
||||
.log-toolbar .button-group { gap: 7px; }
|
||||
.log-toolbar .worker-actions { margin: 0; gap: 7px; }
|
||||
.log-toolbar { margin-bottom: 14px; }
|
||||
.checkbox-label { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); font-size: .77rem; }
|
||||
.checkbox-label input { accent-color: var(--accent); }
|
||||
.log-view { height: 28rem; max-height: 28rem; }
|
||||
.log-panel .panel-body { padding: 16px; }
|
||||
.log-panel .panel-header { flex-wrap: wrap; }
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.topbar-inner { gap: 22px; }
|
||||
.nav-link { padding: 0 12px; }
|
||||
.download-layout { grid-template-columns: minmax(0, 1fr) 290px; gap: 20px; }
|
||||
.workers-layout { grid-template-columns: 310px minmax(0, 1fr); gap: 20px; }
|
||||
.queue-columns, .job-row { grid-template-columns: minmax(0, 1fr) 100px 145px 90px; gap: 16px; }
|
||||
.worker-stats > div { padding: 11px; }
|
||||
}
|
||||
@media (max-width: 850px) {
|
||||
.topbar-inner { flex-wrap: wrap; padding-top: 16px; gap: 12px 20px; }
|
||||
.brand { margin-bottom: 3px; }
|
||||
.main-nav { order: 3; flex-basis: 100%; height: 48px; gap: 8px; }
|
||||
.nav-link { padding: 0 14px; }
|
||||
.connection-status { margin-bottom: 3px; }
|
||||
.app-main { padding-top: 28px; }
|
||||
.download-layout { grid-template-columns: minmax(0, 1fr) 270px; gap: 16px; }
|
||||
.panel-header, .panel-body { padding: 20px; }
|
||||
.panel-header { flex-wrap: wrap; gap: 7px; }
|
||||
.download-sidebar { top: 142px; }
|
||||
.form-actions { align-items: start; flex-direction: column; gap: 10px; }
|
||||
.mode-choice > span { padding: 12px 11px; }
|
||||
.mode-choice small { font-size: .67rem; }
|
||||
.workers-layout { grid-template-columns: 270px minmax(0, 1fr); gap: 16px; }
|
||||
.worker-stats { gap: 7px; }
|
||||
.worker-stats dd { font-size: .95rem; }
|
||||
.worker-details > dl > div { grid-template-columns: 80px minmax(0, 1fr); gap: 8px; }
|
||||
}
|
||||
@media (max-width: 740px) {
|
||||
.topbar-inner, .notice-wrap { padding-left: 20px; padding-right: 20px; }
|
||||
.app-main { padding: 25px 20px 36px; }
|
||||
.app-footer { padding-left: 20px; padding-right: 20px; }
|
||||
.page-heading { align-items: start; gap: 16px; margin-bottom: 24px; }
|
||||
.page-heading > .button { flex-shrink: 0; }
|
||||
.page-heading .page-description { font-size: .84rem; }
|
||||
.download-layout, .workers-layout { grid-template-columns: minmax(0, 1fr); }
|
||||
.download-sidebar { position: static; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); align-items: start; }
|
||||
.help-card { padding: 15px 5px; }
|
||||
.queue-overview { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-bottom: 20px; }
|
||||
.queue-stat { padding: 15px 17px; }
|
||||
.queue-stat-count { font-size: 1.8rem; }
|
||||
.queue-columns { display: none; }
|
||||
.job-row { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px 20px; }
|
||||
.job-primary { grid-column: 1 / -1; }
|
||||
.job-state { grid-column: 2; grid-row: 2; justify-self: end; }
|
||||
.job-time { grid-column: 1; grid-row: 2; }
|
||||
.job-size { grid-column: 1; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.job-size small { margin-top: 0; }
|
||||
.job-log { margin-top: 0; }
|
||||
.queue-filters { padding: 18px 20px; }
|
||||
.queue-filters > .field:first-child, .queue-filters .field-grow { flex-basis: 100%; }
|
||||
.queue-filters > .field:not(:first-child) { flex: 1; }
|
||||
.queue-filters > .field.queue-search { flex: 1 1 100%; }
|
||||
.queue-pagination { padding: 16px 20px; }
|
||||
.verification-notice { align-items: start; flex-direction: column; gap: 15px; padding: 18px; margin-top: 20px; }
|
||||
.worker-list { max-height: 320px; }
|
||||
.worker-stats { gap: 12px; }
|
||||
.worker-stats dd { font-size: 1.15rem; }
|
||||
.log-view { height: 22rem; max-height: 22rem; }
|
||||
}
|
||||
@media (max-width: 470px) {
|
||||
.topbar-inner { padding-left: 16px; padding-right: 16px; gap: 12px; }
|
||||
.main-nav { gap: 0; justify-content: space-between; }
|
||||
.nav-link { padding: 0 10px; font-size: .81rem; }
|
||||
.nav-link.is-active::after { left: 10px; right: 10px; }
|
||||
.connection-status { padding: 5px 7px; font-size: .65rem; gap: 6px; max-width: 160px; white-space: normal; }
|
||||
.brand-mark { width: 33px; height: 33px; }
|
||||
.brand-text { font-size: 1rem; }
|
||||
.brand-text > span { font-size: .67rem; }
|
||||
.app-main { padding: 23px 16px 30px; }
|
||||
.notice-wrap { padding: 0 16px; }
|
||||
.page-heading { flex-direction: column; align-items: stretch; gap: 17px; }
|
||||
.page-heading > .button { align-self: start; }
|
||||
.page-actions { justify-content: start; }
|
||||
.page-title { font-size: 1.85rem; }
|
||||
.eyebrow { font-size: .61rem; }
|
||||
.panel-header, .panel-body { padding: 18px; }
|
||||
.download-sidebar { grid-template-columns: minmax(0, 1fr); gap: 8px; }
|
||||
.form-grid { column-gap: 14px; row-gap: 18px; }
|
||||
.form-grid > .field:nth-child(-n+2) { grid-column: 1 / -1; }
|
||||
.field-input { font-size: 16px; }
|
||||
.field-label { font-size: .8rem; }
|
||||
.mode-switch { gap: 8px; }
|
||||
.mode-choice > span { padding: 12px; }
|
||||
.mode-choice strong { font-size: .81rem; }
|
||||
.mode-choice small { font-size: .67rem; }
|
||||
.form-actions .button { width: 100%; }
|
||||
.queue-filters, .job-row { padding-left: 18px; padding-right: 18px; }
|
||||
.queue-pagination { align-items: start; flex-direction: column; }
|
||||
.queue-pagination > div, .queue-pagination nav { width: 100%; justify-content: space-between; }
|
||||
.worker-row-heading { gap: 6px; }
|
||||
.worker-stats { gap: 7px; }
|
||||
.worker-stats > div { padding: 10px; }
|
||||
.worker-stats dd { font-size: 1rem; }
|
||||
.worker-create { padding: 18px; }
|
||||
.worker-actions .button { flex: 1 1 40%; }
|
||||
.app-footer { padding-left: 16px; padding-right: 16px; font-size: .68rem; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { transition-duration: 0s !important; scroll-behavior: auto !important; }
|
||||
}
|
||||
|
||||
/* Container boundaries (Bootstrap container inside layout.ejs) */
|
||||
.container {
|
||||
max-width: 1100px;
|
||||
/* Dashboard and current worker claims */
|
||||
.section-heading { display: flex; justify-content: space-between; align-items: center; gap: 18px; margin-bottom: 15px; }
|
||||
.section-heading h2 { font-size: 1rem; font-weight: 650; letter-spacing: -.015em; }
|
||||
.section-heading h3 { font-size: .9rem; font-weight: 600; }
|
||||
.section-heading .field-hint { margin-top: 3px; }
|
||||
.text-link { font-size: .8rem; font-weight: 600; text-decoration: none; flex-shrink: 0; }
|
||||
.text-link:hover { text-decoration: underline; }
|
||||
.activity-section { margin-bottom: 28px; min-width: 0; }
|
||||
.activity-cards { display: grid; grid-auto-flow: column; grid-auto-columns: calc((100% - 28px) / 3); gap: 14px; overflow-x: auto; padding: 0 0 7px; margin: 0; list-style: none; scroll-snap-type: x proximity; scrollbar-color: #435461 transparent; scrollbar-width: thin; }
|
||||
.activity-cards:empty { display: none; }
|
||||
.worker-card { background: var(--surface); border: 1px solid var(--border); border-top: 2px solid #42675f; border-radius: 10px; min-width: 0; padding: 17px 18px; scroll-snap-align: start; }
|
||||
.worker-card-heading { display: flex; align-items: start; justify-content: space-between; gap: 9px; margin-bottom: 15px; }
|
||||
.worker-card-name { min-width: 0; overflow-wrap: anywhere; color: var(--muted); font-size: .78rem; font-weight: 600; }
|
||||
.worker-card-state { font-size: .65rem; padding: 1px 6px; }
|
||||
.worker-card-jobs, .unassigned-jobs { list-style: none; padding: 0; margin: 0; }
|
||||
.worker-card-jobs > .active-job + .active-job { margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--border-soft); }
|
||||
.active-job-name { display: block; font-weight: 600; font-size: .95rem; line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.active-job-source { display: block; margin-top: 6px; font-size: .72rem; color: var(--muted); text-decoration: none; overflow-wrap: anywhere; }
|
||||
.active-job-source[href]:hover { color: var(--accent); text-decoration: underline; }
|
||||
.active-job-metrics { display: flex; flex-direction: column; gap: 5px; margin-top: 17px; font-size: .7rem; font-variant-numeric: tabular-nums; }
|
||||
.active-job-size { color: var(--accent); font-weight: 600; }
|
||||
.active-job-time { color: var(--faint); }
|
||||
.worker-card-empty { color: var(--faint); font-size: .82rem; min-height: 86px; padding-top: 6px; }
|
||||
.activity-warning { margin-bottom: 14px; font-size: .8rem; }
|
||||
.activity-empty { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 20px; border: 1px dashed #3c4b57; border-radius: 9px; padding: 20px; color: var(--muted); font-size: .82rem; }
|
||||
.activity-empty strong { font-weight: 550; color: var(--text); }
|
||||
.activity-empty .button { margin-left: auto; }
|
||||
.unassigned-activity { margin-top: 17px; padding: 18px 20px; border: 1px solid #65502d; border-radius: 10px; background: #211f1a; }
|
||||
.unassigned-jobs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
|
||||
.unassigned-jobs .active-job + .active-job { border-left: 1px solid #484131; padding-left: 20px; }
|
||||
.dashboard-overview { margin-bottom: 10px; }
|
||||
.dashboard-feedback { margin: 0 0 24px; }
|
||||
.dashboard-history { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 22px; }
|
||||
.recent-list { list-style: none; padding: 0; margin: 0; }
|
||||
.recent-job { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 17px 24px; border-bottom: 1px solid var(--border-soft); }
|
||||
.recent-job:last-child { border-bottom: 0; }
|
||||
.recent-primary { display: grid; gap: 5px; min-width: 0; }
|
||||
.recent-name { font-size: .83rem; font-weight: 550; overflow-wrap: anywhere; }
|
||||
.recent-primary time { font-size: .72rem; }
|
||||
.recent-empty { padding: 36px 20px; }
|
||||
.history-footnote { padding: 14px 24px; border-top: 1px solid var(--border-soft); margin: 0; }
|
||||
.queue-action-help { margin-top: 15px; }
|
||||
#queue-view > .panel-header { flex-wrap: wrap; }
|
||||
#queue-view > .panel-header > div:first-child { flex: 1 1 340px; }
|
||||
#queue-view > .panel-header > .button-group { flex: 0 1 auto; }
|
||||
.form-grid > .season-field { grid-column: 1 / -1; }
|
||||
.season-field .field-input { max-width: 145px; }
|
||||
.token-cache-status { padding: 14px 16px; background: var(--surface-input); border: 1px solid var(--border); border-radius: 8px; margin-bottom: 17px; }
|
||||
.worker-create > summary { cursor: pointer; font-size: .82rem; color: var(--muted); }
|
||||
.worker-quick-add-hint { margin: 0; padding: 17px 24px; border-top: 1px solid var(--border-soft); }
|
||||
.worker-create[open] > summary { margin-bottom: 20px; }
|
||||
.worker-create form > .button { margin-top: 15px; }
|
||||
@media (max-width: 1100px) {
|
||||
.activity-cards { grid-auto-columns: calc((100% - 14px) / 2); }
|
||||
.unassigned-jobs { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.topbar-inner { gap: 18px; }
|
||||
}
|
||||
|
||||
/* ===============================
|
||||
HEADER / NAVIGATION
|
||||
=============================== */
|
||||
|
||||
header h1 {
|
||||
font-size: 2.4rem;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
color: #8A190B; /* deep red accent */
|
||||
text-shadow: 2px 2px 4px rgba(0,0,0,0.6);
|
||||
@media (max-width: 740px) {
|
||||
.dashboard-history { grid-template-columns: minmax(0, 1fr); gap: 20px; }
|
||||
.recent-job { padding: 16px 20px; }
|
||||
.section-heading { align-items: start; }
|
||||
.unassigned-jobs { grid-template-columns: minmax(0, 1fr); }
|
||||
.unassigned-jobs .active-job + .active-job { border-left: 0; border-top: 1px solid #484131; padding-left: 0; padding-top: 16px; }
|
||||
}
|
||||
|
||||
.btn-outline-light {
|
||||
color: #E0E0E0;
|
||||
border-color: #5A5A5A;
|
||||
}
|
||||
.btn-outline-light:hover {
|
||||
background-color: #5A5A5A;
|
||||
color: #c7c7c7;
|
||||
}
|
||||
|
||||
/* ===============================
|
||||
CARDS / PANELS
|
||||
=============================== */
|
||||
|
||||
.card-dark,
|
||||
.card {
|
||||
background-color: #3A3A3A !important; /* mid-grey panels */
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
border: 1px solid #444;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
/* list group items in status.ejs */
|
||||
.list-group-item {
|
||||
background-color: #3A3A3A;
|
||||
border-color: #4A4A4A;
|
||||
color: #E0E0E0;
|
||||
}
|
||||
.list-group-item:hover {
|
||||
background-color: #4A4A4A;
|
||||
}
|
||||
|
||||
/* ===============================
|
||||
FORM ELEMENTS
|
||||
=============================== */
|
||||
|
||||
.form-text {
|
||||
color: #BEBEBE !important; /* same as form label */
|
||||
}
|
||||
|
||||
.form-label {
|
||||
color: #BEBEBE;
|
||||
}
|
||||
|
||||
.form-control,
|
||||
.form-select {
|
||||
background-color: #4A4A4A;
|
||||
color: #E0E0E0;
|
||||
border: 1px solid #5A5A5A;
|
||||
}
|
||||
|
||||
.form-control:focus,
|
||||
.form-select:focus {
|
||||
border-color: #2980B9; /* same blue accent as reference */
|
||||
box-shadow: 0 0 0 0.25rem rgba(41, 128, 185, 0.25);
|
||||
}
|
||||
|
||||
/* Toggle switch label */
|
||||
.form-check-label {
|
||||
color: #BEBEBE !important;
|
||||
}
|
||||
|
||||
::placeholder {
|
||||
color: #BEBEBE !important; /* Same as label color */
|
||||
}
|
||||
|
||||
|
||||
/* ===============================
|
||||
BUTTONS
|
||||
=============================== */
|
||||
button,
|
||||
.btn {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
/* ===== Floating Pill Toggle ===== */
|
||||
|
||||
.pill-toggle {
|
||||
position: relative;
|
||||
display: flex;
|
||||
width: 240px;
|
||||
background: #333;
|
||||
padding: 5px;
|
||||
border-radius: 30px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.pill-option {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
padding: 10px 0;
|
||||
z-index: 2;
|
||||
font-weight: 600;
|
||||
color: #aaa;
|
||||
transition: color 0.25s ease;
|
||||
}
|
||||
|
||||
.pill-option.active {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.pill-indicator {
|
||||
position: absolute;
|
||||
top: 5px;
|
||||
left: 5px;
|
||||
width: calc(50% - 5px);
|
||||
height: calc(100% - 10px);
|
||||
background: #8a190b; /* your accent red */
|
||||
border-radius: 25px;
|
||||
transition: transform 0.25s ease, background 0.25s ease;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Hover feedback */
|
||||
.pill-option:hover {
|
||||
color: #ddd;
|
||||
}
|
||||
|
||||
|
||||
/* ===============================
|
||||
ALERTS
|
||||
=============================== */
|
||||
|
||||
.alert-danger {
|
||||
background-color: #4A1C1C;
|
||||
border-color: #8A190B;
|
||||
color: #E0E0E0;
|
||||
}
|
||||
|
||||
/* ===============================
|
||||
SCROLLBAR (dark theme)
|
||||
=============================== */
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #5A5A5A;
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: #7D7D7D;
|
||||
}
|
||||
|
||||
/* ===============================
|
||||
LINKS
|
||||
=============================== */
|
||||
|
||||
a {
|
||||
color: #B04232;
|
||||
}
|
||||
a:hover {
|
||||
color: #E05D4A;
|
||||
}
|
||||
|
||||
/* ===============================
|
||||
FOOTER
|
||||
=============================== */
|
||||
|
||||
footer {
|
||||
color: #BEBEBE !important;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#logs {
|
||||
height: 60vh;
|
||||
background: #0b1220;
|
||||
color: #e6eef8;
|
||||
padding: 10px;
|
||||
font-family: monospace;
|
||||
font-size: 0.85rem;
|
||||
overflow-y: auto;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #444;
|
||||
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/* ===============================
|
||||
RESPONSIVE
|
||||
=============================== */
|
||||
|
||||
@media (max-width: 768px) {
|
||||
header h1 {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
@media (max-width: 470px) {
|
||||
.main-nav { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); min-width: 0; width: 100%; }
|
||||
.nav-link { min-width: 0; justify-content: center; align-content: center; flex-wrap: wrap; padding: 0 6px; gap: 2px 4px; font-size: .73rem; white-space: normal; text-align: center; line-height: 1.3; }
|
||||
.nav-link.is-active::after { left: 6px; right: 6px; }
|
||||
.nav-count { font-size: .63rem; min-width: 18px; padding: 1px 4px; }
|
||||
.activity-cards { grid-auto-columns: 100%; }
|
||||
.activity-section { margin-bottom: 23px; }
|
||||
.section-heading { gap: 10px; }
|
||||
.section-heading .text-link { font-size: .72rem; }
|
||||
.section-heading h2 { font-size: .94rem; }
|
||||
.unassigned-activity .section-heading { flex-direction: column; }
|
||||
.activity-empty { align-items: start; flex-direction: column; }
|
||||
.activity-empty .button { margin-left: 0; margin-top: 6px; }
|
||||
.worker-card-empty { min-height: 40px; }
|
||||
#queue-view > .panel-header > div:first-child { flex-basis: auto; }
|
||||
.recent-job { padding: 15px 18px; gap: 10px; }
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const MAX_VISIBLE_LOG_BYTES = 64 * 1024;
|
||||
const POLL_INTERVAL = 10_000;
|
||||
const LOG_PREFIX = '[Earlier log output omitted]\n';
|
||||
|
||||
function validWorkerName(name) {
|
||||
return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all';
|
||||
}
|
||||
|
||||
function boundedLog(text) {
|
||||
const encoder = new TextEncoder();
|
||||
const encoded = encoder.encode(text);
|
||||
if (encoded.length <= MAX_VISIBLE_LOG_BYTES) return text;
|
||||
let start = encoded.length - (MAX_VISIBLE_LOG_BYTES - encoder.encode(LOG_PREFIX).length);
|
||||
while (start < encoded.length && (encoded[start] & 0xc0) === 0x80) start++;
|
||||
return LOG_PREFIX + new TextDecoder().decode(encoded.subarray(start));
|
||||
}
|
||||
|
||||
function statusClass(status) {
|
||||
if (['online', 'running'].includes(status)) return 'status-online';
|
||||
if (['stopped', 'errored', 'offline'].includes(status)) return 'status-stopped';
|
||||
return 'status-pending';
|
||||
}
|
||||
|
||||
function startWorkerPage({ document, window, fetch, WebSocket, setTimeout, clearTimeout, AbortController }) {
|
||||
const get = id => document.getElementById(id);
|
||||
const list = get('process-list');
|
||||
if (!list) return null;
|
||||
|
||||
const elements = {
|
||||
output: get('control-output'), listState: get('worker-refresh-state'),
|
||||
empty: get('workers-empty'), count: get('worker-counts'),
|
||||
controls: get('control-centre'), placeholder: get('worker-placeholder'),
|
||||
createForm: get('create-worker-form'), nameInput: get('worker-name'),
|
||||
logs: get('logs'), follow: get('follow-logs'), connection: get('log-connection-state'),
|
||||
reconnect: get('reconnect-logs'), refresh: get('refresh-list'),
|
||||
quickAdd: get('btn-quick-add'),
|
||||
};
|
||||
const rows = new Map();
|
||||
const records = new Map();
|
||||
let selectedKey = null;
|
||||
let commandInFlight = false;
|
||||
let listRequest = null;
|
||||
let pollTimer = null;
|
||||
let socket = null;
|
||||
let socketGeneration = 0;
|
||||
let connectionTimer = null;
|
||||
let connecting = false;
|
||||
let disposed = false;
|
||||
|
||||
const keyFor = worker => `${worker.pm_id}:${worker.name}`;
|
||||
const selected = () => selectedKey ? records.get(selectedKey) : null;
|
||||
const string = value => value == null ? '—' : String(value);
|
||||
|
||||
function text(id, value) { get(id).textContent = string(value); }
|
||||
|
||||
function showResult(message, state = '') {
|
||||
elements.output.textContent = message;
|
||||
elements.output.hidden = !message;
|
||||
elements.output.classList.toggle('is-error', state === 'error');
|
||||
elements.output.classList.toggle('is-success', state === 'success');
|
||||
}
|
||||
|
||||
function updateButtons() {
|
||||
const worker = selected();
|
||||
const online = worker && ['online', 'running', 'launching'].includes(worker.status);
|
||||
get('btn-create').disabled = commandInFlight;
|
||||
elements.quickAdd.disabled = commandInFlight;
|
||||
elements.nameInput.disabled = commandInFlight;
|
||||
get('clear-selection').disabled = commandInFlight;
|
||||
elements.refresh.disabled = commandInFlight || !!listRequest;
|
||||
for (const cmd of ['start', 'stop', 'restart', 'delete']) {
|
||||
get(`btn-${cmd}`).disabled = commandInFlight || !worker
|
||||
|| (cmd === 'start' && online) || (cmd === 'stop' && worker.status === 'stopped');
|
||||
}
|
||||
for (const [key, row] of rows) {
|
||||
row.disabled = commandInFlight || !validWorkerName(records.get(key)?.name);
|
||||
row.classList.toggle('is-selected', key === selectedKey);
|
||||
row.setAttribute('aria-pressed', String(key === selectedKey));
|
||||
}
|
||||
elements.reconnect.disabled = !worker || connecting;
|
||||
}
|
||||
|
||||
function populateControls() {
|
||||
const worker = selected();
|
||||
elements.controls.hidden = !worker;
|
||||
elements.placeholder.hidden = !!worker;
|
||||
if (worker) {
|
||||
text('cc-name', worker.name);
|
||||
text('cc-sub', `PM2 ${worker.pm_id} · ${worker.status}`);
|
||||
for (const [id, field] of Object.entries({
|
||||
'detail-pmid': 'pm_id', 'detail-pid': 'pid', 'detail-status': 'status',
|
||||
'detail-cpu': 'cpu', 'detail-mem': 'memoryMB', 'detail-uptime': 'uptime', 'detail-exec': 'execPath',
|
||||
})) text(id, worker[field]);
|
||||
}
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
function appendLog(message) {
|
||||
const value = String(message ?? '');
|
||||
const line = `[${new Date().toLocaleTimeString()}] ${value}${value.endsWith('\n') ? '' : '\n'}`;
|
||||
elements.logs.textContent = boundedLog(elements.logs.textContent + line);
|
||||
if (elements.follow.checked) elements.logs.scrollTop = elements.logs.scrollHeight;
|
||||
}
|
||||
|
||||
function closeSocket() {
|
||||
socketGeneration++;
|
||||
clearTimeout(connectionTimer);
|
||||
connectionTimer = null;
|
||||
connecting = false;
|
||||
const previous = socket;
|
||||
socket = null;
|
||||
if (!previous) return;
|
||||
try {
|
||||
if (previous.readyState === WebSocket.OPEN) previous.send(JSON.stringify({ type: 'stop-logs' }));
|
||||
previous.close();
|
||||
} catch { /* The old connection is already closed. */ }
|
||||
}
|
||||
|
||||
function openLogs(clear = false) {
|
||||
closeSocket();
|
||||
const worker = selected();
|
||||
if (!worker || disposed) return;
|
||||
const generation = socketGeneration;
|
||||
const workerKey = selectedKey;
|
||||
if (clear) elements.logs.textContent = `Connecting to ${worker.name}…\n`;
|
||||
connecting = true;
|
||||
elements.connection.textContent = 'Connecting…';
|
||||
updateButtons();
|
||||
let current;
|
||||
try {
|
||||
current = new WebSocket(`${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}`);
|
||||
} catch {
|
||||
connecting = false;
|
||||
elements.connection.textContent = 'Log connection unavailable';
|
||||
updateButtons();
|
||||
return;
|
||||
}
|
||||
socket = current;
|
||||
const active = () => !disposed && socket === current && socketGeneration === generation && selectedKey === workerKey;
|
||||
connectionTimer = setTimeout(() => {
|
||||
if (!active() || current.readyState === WebSocket.OPEN) return;
|
||||
closeSocket();
|
||||
elements.connection.textContent = 'Connection timed out — reconnect to try again';
|
||||
updateButtons();
|
||||
}, 10_000);
|
||||
current.addEventListener('open', () => {
|
||||
if (!active()) return;
|
||||
clearTimeout(connectionTimer);
|
||||
connecting = false;
|
||||
try {
|
||||
current.send(JSON.stringify({ type: 'logs', name: worker.name }));
|
||||
elements.connection.textContent = `Connected to ${worker.name}`;
|
||||
} catch {
|
||||
elements.connection.textContent = 'Log request could not be sent — reconnect to try again';
|
||||
}
|
||||
updateButtons();
|
||||
});
|
||||
current.addEventListener('message', event => {
|
||||
if (!active()) return;
|
||||
let payload;
|
||||
try { payload = JSON.parse(event.data); } catch { return; }
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return;
|
||||
if (['stdout', 'stderr'].includes(payload.type)) appendLog(payload.data || '');
|
||||
else if (payload.type === 'info') appendLog(`[info] ${payload.message || ''}`);
|
||||
else if (payload.type === 'error') {
|
||||
elements.connection.textContent = 'Log stream unavailable — reconnect to try again';
|
||||
appendLog(`[error] ${payload.error || 'The log stream failed.'}`);
|
||||
} else if (payload.type === 'close') {
|
||||
elements.connection.textContent = 'Log stream ended — reconnect to continue';
|
||||
appendLog('[Log stream ended]');
|
||||
}
|
||||
});
|
||||
const disconnected = () => {
|
||||
if (!active()) return;
|
||||
clearTimeout(connectionTimer);
|
||||
connecting = false;
|
||||
elements.connection.textContent = 'Disconnected — reconnect to continue';
|
||||
updateButtons();
|
||||
};
|
||||
current.addEventListener('close', disconnected);
|
||||
current.addEventListener('error', disconnected);
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedKey = null;
|
||||
closeSocket();
|
||||
elements.connection.textContent = 'No worker selected';
|
||||
elements.logs.textContent = 'Select a worker to view its logs.';
|
||||
populateControls();
|
||||
}
|
||||
|
||||
function selectWorker(key) {
|
||||
if (commandInFlight || !records.has(key) || !validWorkerName(records.get(key).name)) return;
|
||||
if (selectedKey === key) return;
|
||||
selectedKey = key;
|
||||
populateControls();
|
||||
openLogs(true);
|
||||
}
|
||||
|
||||
function makeElement(tag, className, value) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (value !== undefined) node.textContent = string(value);
|
||||
return node;
|
||||
}
|
||||
|
||||
function createRow(worker) {
|
||||
const item = makeElement('li', 'worker-list-item');
|
||||
const row = makeElement('button', 'worker-row');
|
||||
row.type = 'button';
|
||||
const heading = makeElement('span', 'worker-row-heading');
|
||||
heading.append(makeElement('strong', 'worker-name'));
|
||||
const badge = makeElement('span', 'badge');
|
||||
badge.dataset.workerStatus = '';
|
||||
heading.append(badge);
|
||||
const meta = makeElement('span', 'worker-row-meta');
|
||||
meta.dataset.workerMetrics = '';
|
||||
row.append(heading, meta);
|
||||
item.append(row);
|
||||
row.dataset.key = keyFor(worker);
|
||||
row.addEventListener('click', () => selectWorker(row.dataset.key));
|
||||
list.append(item);
|
||||
return row;
|
||||
}
|
||||
|
||||
function renderWorkers(workers) {
|
||||
const present = new Set();
|
||||
for (const worker of workers) {
|
||||
const key = keyFor(worker);
|
||||
present.add(key);
|
||||
records.set(key, worker);
|
||||
let row = rows.get(key);
|
||||
if (!row) { row = createRow(worker); rows.set(key, row); }
|
||||
row.dataset.name = string(worker.name);
|
||||
row.querySelector('.worker-name').textContent = string(worker.name);
|
||||
const badge = row.querySelector('[data-worker-status]');
|
||||
badge.textContent = string(worker.status);
|
||||
badge.className = `badge ${statusClass(worker.status)}`;
|
||||
row.querySelector('[data-worker-metrics]').textContent = `CPU ${string(worker.cpu)} · ${string(worker.memoryMB)} · ${string(worker.uptime)}`;
|
||||
}
|
||||
for (const [key, row] of rows) {
|
||||
if (!present.has(key)) {
|
||||
row.parentElement.remove();
|
||||
rows.delete(key);
|
||||
records.delete(key);
|
||||
}
|
||||
}
|
||||
elements.empty.hidden = workers.length > 0;
|
||||
const online = workers.filter(worker => ['online', 'running'].includes(worker.status)).length;
|
||||
elements.count.textContent = `${online} online · ${workers.length} total`;
|
||||
if (selectedKey && !records.has(selectedKey)) {
|
||||
clearSelection();
|
||||
if (!commandInFlight) showResult('The selected worker is no longer available. Choose another worker.');
|
||||
}
|
||||
populateControls();
|
||||
}
|
||||
|
||||
async function requestJson(url, options = {}, timeout = 12_000) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeout);
|
||||
try {
|
||||
const response = await fetch(url, { ...options, cache: 'no-store', signal: controller.signal });
|
||||
const result = await response.json();
|
||||
return { response, result };
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
|
||||
function schedulePoll() {
|
||||
clearTimeout(pollTimer);
|
||||
if (!disposed && !document.hidden) {
|
||||
pollTimer = setTimeout(async () => {
|
||||
if (!commandInFlight) await refreshList();
|
||||
schedulePoll();
|
||||
}, POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshList() {
|
||||
if (disposed) return Promise.resolve(false);
|
||||
if (listRequest) return listRequest;
|
||||
listRequest = (async () => {
|
||||
try {
|
||||
const { response, result } = await requestJson('/pm2/list-json');
|
||||
if (!response.ok || !result?.ok || !Array.isArray(result.processes)) throw new Error('List unavailable');
|
||||
if (disposed) return false;
|
||||
renderWorkers(result.processes);
|
||||
elements.listState.textContent = `Updated ${new Date().toLocaleTimeString()}`;
|
||||
return true;
|
||||
} catch {
|
||||
if (!disposed) elements.listState.textContent = 'Could not refresh workers. Showing the last available list.';
|
||||
return false;
|
||||
} finally {
|
||||
listRequest = null;
|
||||
if (!disposed) updateButtons();
|
||||
}
|
||||
})();
|
||||
updateButtons();
|
||||
return listRequest;
|
||||
}
|
||||
|
||||
async function execCommand(command, name) {
|
||||
const automatic = command === 'quick-add';
|
||||
const creating = automatic || command === 'create';
|
||||
if (disposed || commandInFlight || (!automatic && !validWorkerName(name))) return false;
|
||||
commandInFlight = true;
|
||||
updateButtons();
|
||||
showResult(automatic ? 'Creating the next numbered worker…' : `${creating ? 'Creating' : 'Updating'} ${name}…`);
|
||||
try {
|
||||
// Let any earlier read finish before mutating so stale list responses
|
||||
// cannot replace the result of this command.
|
||||
if (listRequest) await listRequest;
|
||||
if (disposed) return false;
|
||||
const { response, result } = await requestJson(automatic ? '/pm2/quick-add' : '/pm2/command', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(automatic ? {} : { cmd: command, name }),
|
||||
}, automatic ? 45_000 : 15_000);
|
||||
if (disposed) return false;
|
||||
if (!response.ok || !result?.ok) {
|
||||
showResult(String(result?.error || result?.message || 'The worker command could not be completed.').slice(0, 500), 'error');
|
||||
return false;
|
||||
}
|
||||
if (automatic) {
|
||||
if (!validWorkerName(result.name) || !/^proxer-worker-\d+$/.test(result.name)) {
|
||||
showResult('The worker command completed, but its name could not be confirmed. Refresh the worker list before trying again.', 'error');
|
||||
await refreshList();
|
||||
return false;
|
||||
}
|
||||
name = result.name;
|
||||
}
|
||||
showResult(command === 'delete' ? `${name} was deleted.`
|
||||
: creating ? `${name} was created and started.` : `${name}: ${command} completed.`, 'success');
|
||||
const refreshed = await refreshList();
|
||||
if (!refreshed) showResult('The command completed, but the worker list could not be refreshed. Refresh it before your next action.', 'error');
|
||||
if (creating && refreshed) {
|
||||
const created = [...records.entries()].find(([, worker]) => worker.name === name);
|
||||
if (created) {
|
||||
selectedKey = created[0];
|
||||
populateControls();
|
||||
openLogs(true);
|
||||
}
|
||||
if (!automatic) elements.nameInput.value = '';
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
if (!disposed) showResult('Could not confirm the worker command. Refresh the worker list before trying again.', 'error');
|
||||
return false;
|
||||
} finally {
|
||||
commandInFlight = false;
|
||||
if (!disposed) updateButtons();
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of list.querySelectorAll('.worker-row')) {
|
||||
const data = row.dataset;
|
||||
const worker = { name: data.name, pm_id: data.pmid, pid: data.pid, status: data.status,
|
||||
cpu: data.cpu, memoryMB: data.memory, uptime: data.uptime, execPath: data.exec };
|
||||
const key = keyFor(worker);
|
||||
records.set(key, worker);
|
||||
rows.set(key, row);
|
||||
row.addEventListener('click', () => selectWorker(key));
|
||||
}
|
||||
elements.createForm.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (commandInFlight) return;
|
||||
const name = elements.nameInput.value.trim();
|
||||
elements.nameInput.value = name;
|
||||
const inUse = [...records.values()].some(worker => worker.name === name);
|
||||
elements.nameInput.setCustomValidity(!validWorkerName(name)
|
||||
? 'Use 1–64 letters, numbers, underscores or hyphens, starting with a letter or number. “all” is reserved.'
|
||||
: inUse ? 'A worker with that name already exists.' : '');
|
||||
if (!elements.createForm.reportValidity()) return;
|
||||
await execCommand('create', name);
|
||||
});
|
||||
elements.nameInput.addEventListener('input', () => elements.nameInput.setCustomValidity(''));
|
||||
elements.quickAdd.addEventListener('click', () => execCommand('quick-add'));
|
||||
|
||||
const confirmations = {
|
||||
stop: name => `Stop ${name}? An active download may be interrupted.`,
|
||||
restart: name => `Restart ${name}? An active download may be interrupted.`,
|
||||
delete: name => `Delete ${name} from the worker list? This stops the worker and may interrupt an active download. Downloaded files are kept.`,
|
||||
};
|
||||
for (const command of ['start', 'stop', 'restart', 'delete']) {
|
||||
get(`btn-${command}`).addEventListener('click', () => {
|
||||
const worker = selected();
|
||||
if (!worker || commandInFlight) return;
|
||||
if (confirmations[command] && !window.confirm(confirmations[command](worker.name))) return;
|
||||
execCommand(command, worker.name);
|
||||
});
|
||||
}
|
||||
get('clear-selection').addEventListener('click', () => { if (!commandInFlight) clearSelection(); });
|
||||
elements.refresh.addEventListener('click', () => { refreshList(); });
|
||||
elements.reconnect.addEventListener('click', () => openLogs(false));
|
||||
get('clear-logs').addEventListener('click', () => { elements.logs.textContent = ''; });
|
||||
elements.follow.addEventListener('change', () => {
|
||||
if (elements.follow.checked) elements.logs.scrollTop = elements.logs.scrollHeight;
|
||||
});
|
||||
elements.logs.addEventListener('scroll', () => {
|
||||
if (elements.logs.scrollHeight - elements.logs.scrollTop - elements.logs.clientHeight > 40) elements.follow.checked = false;
|
||||
});
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
clearTimeout(pollTimer);
|
||||
if (!document.hidden) {
|
||||
if (!commandInFlight) refreshList();
|
||||
schedulePoll();
|
||||
}
|
||||
});
|
||||
function dispose() {
|
||||
disposed = true;
|
||||
clearTimeout(pollTimer);
|
||||
closeSocket();
|
||||
}
|
||||
window.addEventListener('pagehide', dispose);
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (event.persisted) window.location.reload();
|
||||
});
|
||||
populateControls();
|
||||
schedulePoll();
|
||||
return { refreshList, execCommand, selectWorker, clearSelection, appendLog, dispose };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = { startWorkerPage, validWorkerName, boundedLog, statusClass, MAX_VISIBLE_LOG_BYTES };
|
||||
}
|
||||
if (typeof document !== 'undefined' && document.getElementById('process-list')) {
|
||||
startWorkerPage({ document, window, fetch: window.fetch.bind(window), WebSocket: window.WebSocket,
|
||||
setTimeout: window.setTimeout.bind(window), clearTimeout: window.clearTimeout.bind(window),
|
||||
AbortController: window.AbortController });
|
||||
}
|
||||
})();
|
||||
+12
-6
@@ -5,6 +5,7 @@ const { config } = require('./lib/config');
|
||||
const { getDb, closeDb } = require('./lib/mongo');
|
||||
const { ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget, cookieToken } = require('./lib/jobValidation');
|
||||
const { LOG_LIMIT, sanitizeLog, createLineSanitizer } = require('./lib/logging');
|
||||
const { createWorkerIdentity, toPublicWorkerIdentity } = require('./lib/workerIdentity');
|
||||
|
||||
const RESULT_PREFIX = 'PROXER_RESULT ';
|
||||
const ERROR_CATEGORIES = new Set(['validation', 'authentication', 'resolution', 'network', 'source', 'storage', 'configuration', 'unknown']);
|
||||
@@ -177,7 +178,7 @@ async function processClaimedJob(job, { db, execute = executeJob, now = () => ne
|
||||
// Preserve the complete request for a later worker start; never consume the
|
||||
// queue because an interpreter, dependency or media mount is unavailable.
|
||||
await db.collection('queue').updateOne({ _id: job._id, processing: true },
|
||||
{ $unset: { processing: '', started_at: '' } });
|
||||
{ $unset: { processing: '', started_at: '', worker: '' } });
|
||||
if (result.infrastructureFailure) throw new Error('Worker infrastructure is unavailable. The job remains queued.');
|
||||
return result;
|
||||
}
|
||||
@@ -188,6 +189,8 @@ async function processClaimedJob(job, { db, execute = executeJob, now = () => ne
|
||||
created_at: job.created_at,
|
||||
output_log: sanitizeLog(result.output, jobSecrets(job)),
|
||||
};
|
||||
const worker = toPublicWorkerIdentity(job.worker);
|
||||
if (worker) common.worker = worker;
|
||||
|
||||
if (result.ok) {
|
||||
// History must be durable before removing the queue record. Full atomic job
|
||||
@@ -214,7 +217,7 @@ async function processClaimedJob(job, { db, execute = executeJob, now = () => ne
|
||||
// Preserve the original request and credential for a deliberate retry. The
|
||||
// attempt stays visible in history, while the job remains queued and paused.
|
||||
const release = await db.collection('queue').updateOne({ _id: job._id, processing: true },
|
||||
{ $unset: { processing: '', started_at: '' } });
|
||||
{ $unset: { processing: '', started_at: '', worker: '' } });
|
||||
if (release?.acknowledged !== true) throw new Error('The claim release could not be confirmed. Check the paused queue before resuming.');
|
||||
} else {
|
||||
// Ordinary failures become history rather than looping or pausing all jobs.
|
||||
@@ -230,24 +233,27 @@ async function downloadsPaused(db) {
|
||||
return global?.captcha_blocked === true;
|
||||
}
|
||||
|
||||
async function claimNextJob(db, { shouldStop = () => false, now = () => new Date() } = {}) {
|
||||
async function claimNextJob(db, { shouldStop = () => false, now = () => new Date(), workerIdentity } = {}) {
|
||||
if (shouldStop() || await downloadsPaused(db) || shouldStop()) return null;
|
||||
const worker = toPublicWorkerIdentity(workerIdentity);
|
||||
const job = await db.collection('queue').findOneAndUpdate(
|
||||
{ processing: { $ne: true } },
|
||||
{ $set: { processing: true, started_at: now() } },
|
||||
{ $set: { processing: true, started_at: now(), ...(worker ? { worker } : {}) },
|
||||
...(!worker ? { $unset: { worker: '' } } : {}) },
|
||||
{ sort: { created_at: 1 }, returnDocument: 'after' },
|
||||
);
|
||||
if (!job) return null;
|
||||
if (await downloadsPaused(db) || shouldStop()) {
|
||||
// A concurrent worker paused after our initial read. No child has started.
|
||||
await db.collection('queue').updateOne({ _id: job._id, processing: true },
|
||||
{ $unset: { processing: '', started_at: '' } });
|
||||
{ $unset: { processing: '', started_at: '', worker: '' } });
|
||||
return null;
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const workerIdentity = createWorkerIdentity();
|
||||
const db = await getDb();
|
||||
let stopping = false;
|
||||
let child = null;
|
||||
@@ -262,7 +268,7 @@ async function main() {
|
||||
|
||||
try {
|
||||
while (!stopping) {
|
||||
const job = await claimNextJob(db, { shouldStop: () => stopping });
|
||||
const job = await claimNextJob(db, { shouldStop: () => stopping, workerIdentity });
|
||||
if (!job) { if (!stopping) await delay(1000); continue; }
|
||||
const result = await processClaimedJob(job, { db,
|
||||
execute: (request) => executeJob(request, {
|
||||
|
||||
+17
-58
@@ -1,75 +1,34 @@
|
||||
// routes/index.js
|
||||
"use strict";
|
||||
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const queue = require("../controllers/queueController");
|
||||
const dashboard = require("../controllers/dashboardController");
|
||||
const pm2 = require("../controllers/pm2Controller");
|
||||
const { getDb } = require("../lib/mongo");
|
||||
|
||||
// =======================
|
||||
// HOME PAGE
|
||||
// =======================
|
||||
router.get("/", (req, res) =>
|
||||
res.render("index", { title: "Proxer Downloader" })
|
||||
);
|
||||
|
||||
// =======================
|
||||
// QUEUE REQUEST
|
||||
// =======================
|
||||
router.get("/", (req, res, next) => {
|
||||
// Preserve bookmarks to the former download form's no-JavaScript mode links.
|
||||
if (["series", "video"].includes(req.query.mode)) return res.redirect(`/download?mode=${req.query.mode}`);
|
||||
return dashboard.dashboard(req, res, next);
|
||||
});
|
||||
router.get("/dashboard-data", dashboard.dashboardData);
|
||||
router.get("/download", queue.home);
|
||||
router.post("/queue", queue.enqueue);
|
||||
|
||||
// =======================
|
||||
// STATUS (SSR RENDER)
|
||||
// =======================
|
||||
router.get("/status", queue.status);
|
||||
|
||||
// =======================
|
||||
// STATUS JSON API
|
||||
// =======================
|
||||
router.get("/status-data", queue.statusData);
|
||||
|
||||
// =======================
|
||||
// CAPTCHA CLEAR
|
||||
// =======================
|
||||
router.get("/status-summary", queue.statusSummary);
|
||||
router.post("/clear-captcha", queue.clearCaptcha);
|
||||
|
||||
router.post("/clear-failed", async (req, res) => {
|
||||
const db = await getDb();
|
||||
await db
|
||||
.collection("failed")
|
||||
.deleteMany({}) //delete all
|
||||
|
||||
// Redirect to status, controller fetches everything
|
||||
res.redirect("/status");
|
||||
});
|
||||
|
||||
router.post("/clear-done", async (req, res) => {
|
||||
const db = await getDb();
|
||||
await db
|
||||
.collection("done")
|
||||
.deleteMany({}) //delete all
|
||||
|
||||
// Redirect to status, controller fetches everything
|
||||
res.redirect("/status");
|
||||
});
|
||||
|
||||
// Keep the legacy URL, but never release a job that may still have a live child process.
|
||||
router.post("/clear-state", queue.clearState);
|
||||
for (const state of ["queued", "done", "failed"]) {
|
||||
router.post(`/clear-${state}`, (req, res, next) => queue.clearState(req, res, next, state));
|
||||
}
|
||||
// Retain the legacy URL without releasing a possibly live download.
|
||||
router.post("/clear-processing", queue.clearProcessing);
|
||||
|
||||
router.post("/clear-queued", async (req, res) => {
|
||||
const db = await getDb();
|
||||
await db
|
||||
.collection("queue")
|
||||
.deleteMany({ processing: { $ne: true } }) //delete all not currently processing
|
||||
|
||||
// Redirect to status, controller fetches everything
|
||||
res.redirect("/status");
|
||||
});
|
||||
|
||||
// =======================
|
||||
// PM2 MANAGEMENT
|
||||
// =======================
|
||||
router.get("/pm2", pm2.getManage);
|
||||
router.get("/pm2/list-json", pm2.listJson);
|
||||
router.post("/pm2/command", pm2.postCommand);
|
||||
router.post("/pm2/quick-add", pm2.quickAdd);
|
||||
|
||||
module.exports = router;
|
||||
@@ -22,7 +22,7 @@ function handleHttpError(error, req, res, next) {
|
||||
const message = tooLarge
|
||||
? 'Request too large. The maximum request size is 32 KiB.'
|
||||
: invalid ? 'Invalid request body.' : 'The request could not be completed. Check the server configuration and try again.';
|
||||
if (req.is?.('application/json') || req.path?.startsWith('/pm2/') || req.path === '/status-data') {
|
||||
if (req.is?.('application/json') || req.path?.startsWith('/pm2/') || ['/status-data', '/status-summary', '/dashboard-data'].includes(req.path)) {
|
||||
return res.status(status).json({ ok: false, error: message });
|
||||
}
|
||||
return res.status(status).render('error', { title: 'Request failed', message, details: null });
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
"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 { createWorkerIdentity, toPublicWorkerIdentity } = require("../lib/workerIdentity");
|
||||
const {
|
||||
readActivity, createInventoryReader, readActiveFileSize,
|
||||
ACTIVE_JOB_LIMIT, WORKER_LIMIT, ACTIVITY_READ_PROJECTION,
|
||||
} = require("../lib/activity");
|
||||
const { createDashboardController, RECENT_LIMIT } = require("../controllers/dashboardController");
|
||||
const { STATUS_READ_PROJECTION } = require("../lib/jobValidation");
|
||||
const { QUERY_TIMEOUT_MS } = require("../lib/statusQuery");
|
||||
|
||||
const HOST = "download-host";
|
||||
const START = "2026-01-01T12:00:00.000Z";
|
||||
const CLAIM = "2026-01-01T12:01:00.000Z";
|
||||
const RUN_ID = "7b3c9e3a-8b0b-41c6-988c-8e9e01dbbf4a";
|
||||
const identity = (changes = {}) => ({
|
||||
name: "proxer-worker-1", pid: 1234, host: HOST, run_id: RUN_ID, started_at: START, ...changes,
|
||||
});
|
||||
const processRecord = (changes = {}) => ({
|
||||
name: "proxer-worker-1", pid: 1234, pm_id: "1", status: "online", startedAtISO: START, ...changes,
|
||||
});
|
||||
const activeRecord = (changes = {}) => ({
|
||||
_id: "job-1", filename: "ExampleS001E001_engsub", processing: true, created_at: START,
|
||||
started_at: CLAIM, url: "https://proxer.me/watch/42/1/engsub", worker: identity(), ...changes,
|
||||
});
|
||||
|
||||
function activityDatabase(records = [], failure) {
|
||||
const reads = [];
|
||||
const db = { collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return { find(filter, options) {
|
||||
const read = { filter, options };
|
||||
reads.push(read);
|
||||
const cursor = {
|
||||
sort(value) { read.sort = value; return cursor; },
|
||||
limit(value) { read.limit = value; return cursor; },
|
||||
async toArray() { if (failure) throw failure; return records.slice(0, read.limit); },
|
||||
};
|
||||
return cursor;
|
||||
} };
|
||||
} };
|
||||
return { db, reads };
|
||||
}
|
||||
|
||||
async function activityFixture(records, processes = [processRecord()], options = {}) {
|
||||
const fixture = activityDatabase(records);
|
||||
const fileChecks = [];
|
||||
const result = await readActivity(fixture.db, {
|
||||
host: HOST, listWorkers: async () => processes,
|
||||
readFileSize: async job => { fileChecks.push(job._id); return 123; }, ...options,
|
||||
});
|
||||
return { ...fixture, result, fileChecks };
|
||||
}
|
||||
|
||||
test("worker identity is immutable, names are safe, and each actual process run has a unique ID", () => {
|
||||
const explicit = createWorkerIdentity({
|
||||
env: { PROXER_WORKER_NAME: "proxer-worker-9", name: "proxer-worker-1" },
|
||||
pid: 1234, host: HOST, uuid: () => RUN_ID, now: () => new Date(START),
|
||||
});
|
||||
assert.equal(Object.isFrozen(explicit), true);
|
||||
assert.throws(() => { explicit.pid = 5; }, TypeError);
|
||||
assert.deepEqual(explicit, identity({ name: "proxer-worker-9" }));
|
||||
const unsafe = createWorkerIdentity({
|
||||
env: { PROXER_WORKER_NAME: "<script>private</script>", name: "bad name" },
|
||||
pid: 1234, host: HOST, uuid: () => RUN_ID, now: () => new Date(START),
|
||||
});
|
||||
assert.equal(unsafe.name, "worker-1234");
|
||||
const actual = createWorkerIdentity({ env: {} });
|
||||
assert.equal(actual.pid, process.pid);
|
||||
assert.equal(actual.host, os.hostname());
|
||||
assert.equal(actual.name, `worker-${process.pid}`);
|
||||
assert.notEqual(actual.run_id, createWorkerIdentity({ env: {} }).run_id);
|
||||
});
|
||||
|
||||
test("worker identity DTO drops extra fields and rejects incomplete or unsafe legacy metadata", () => {
|
||||
assert.deepEqual(toPublicWorkerIdentity({ ...identity(), token: "secret", env: { PRIVATE: "value" } }), identity());
|
||||
for (const value of [
|
||||
null, [], {}, { name: "proxer-worker-1", pid: 1234 },
|
||||
identity({ pid: "1234" }), identity({ pid: 0 }), identity({ pid: NaN }),
|
||||
identity({ name: "<script>" }), identity({ host: "https://host/secret" }),
|
||||
identity({ run_id: "not-a-run-id" }), identity({ started_at: "2026-02-31T12:00:00.000Z" }),
|
||||
]) assert.equal(toPublicWorkerIdentity(value), null);
|
||||
});
|
||||
|
||||
test("activity connects a verified local claim to its managed worker and includes idle and stopped workers", async () => {
|
||||
const { result } = await activityFixture([activeRecord()], [
|
||||
processRecord({ name: "renamed-worker" }),
|
||||
processRecord({ pm_id: "2", pid: 2345, name: "proxer-worker-2" }),
|
||||
processRecord({ pm_id: "3", pid: 0, name: "proxer-worker-3", status: "stopped" }),
|
||||
]);
|
||||
assert.equal(result.available, true);
|
||||
assert.equal(result.workers.length, 3);
|
||||
assert.equal(result.workers[0].name, "renamed-worker");
|
||||
assert.equal(result.workers[0].jobs[0]._id, "job-1");
|
||||
assert.deepEqual(result.workers[0].jobs[0].worker, identity());
|
||||
assert.equal(result.workers[0].jobs[0].fileSize, 123);
|
||||
assert.deepEqual(result.workers[1].jobs, []);
|
||||
assert.equal(result.workers[1].activityUnknown, false);
|
||||
assert.equal(result.workers[2].status, "stopped");
|
||||
assert.equal(result.workers[2].pid, null);
|
||||
assert.deepEqual(result.unassigned, []);
|
||||
});
|
||||
|
||||
test("pre-update active jobs stay unassigned and do not falsely imply that known workers are idle", async () => {
|
||||
const { result } = await activityFixture([
|
||||
activeRecord({ worker: undefined }), activeRecord({ _id: "job-2", worker: { name: "proxer-worker-1", pid: 1234 } }),
|
||||
]);
|
||||
assert.deepEqual(result.workers[0].jobs, []);
|
||||
assert.equal(result.workers[0].activityUnknown, true);
|
||||
assert.equal(result.unassigned.length, 2);
|
||||
for (const job of result.unassigned) {
|
||||
assert.equal(job.worker, null);
|
||||
assert.equal(job.assignmentReason, "unknown-worker");
|
||||
}
|
||||
});
|
||||
|
||||
test("PID reuse, other hosts, missing launch time, and ambiguous inventory never attach a claim to a current worker", async () => {
|
||||
const cases = [
|
||||
["stale-worker", activeRecord(), [processRecord({ startedAtISO: "2026-01-01T12:02:00.000Z" })]],
|
||||
["remote-worker", activeRecord({ worker: identity({ host: "other-host" }) }), [processRecord()]],
|
||||
["unverified-worker", activeRecord(), [processRecord({ startedAtISO: null })]],
|
||||
["unverified-worker", activeRecord({ started_at: "2026-01-01T11:59:00.000Z" }), [processRecord()]],
|
||||
["ambiguous-worker", activeRecord(), [processRecord(), processRecord({ pm_id: "2", name: "another-worker" })]],
|
||||
["worker-not-running", activeRecord(), [processRecord({ pid: 4321 })]],
|
||||
["worker-not-running", activeRecord(), [processRecord({ status: "stopped" })]],
|
||||
];
|
||||
for (const [reason, job, processes] of cases) {
|
||||
const { result } = await activityFixture([job], processes);
|
||||
assert.ok(result.workers.every(worker => worker.jobs.length === 0), reason);
|
||||
assert.equal(result.unassigned[0].assignmentReason, reason);
|
||||
}
|
||||
});
|
||||
|
||||
test("unavailable PM2 preserves active jobs and their saved identity while a database read failure propagates", async () => {
|
||||
const unavailable = async () => { throw new Error("private supervisor failure"); };
|
||||
const { result } = await activityFixture([activeRecord()], [], { listWorkers: unavailable });
|
||||
assert.equal(result.available, false);
|
||||
assert.deepEqual(result.workers, []);
|
||||
assert.equal(result.unassigned[0].assignmentReason, "supervisor-unavailable");
|
||||
assert.deepEqual(result.unassigned[0].worker, identity());
|
||||
assert.doesNotMatch(JSON.stringify(result), /private supervisor failure/);
|
||||
const failure = new Error("database unavailable");
|
||||
const broken = activityDatabase([], failure);
|
||||
await assert.rejects(readActivity(broken.db, { listWorkers: unavailable }), error => error === failure);
|
||||
});
|
||||
|
||||
test("active reads and filesystem checks are bounded and truncation cannot mark unobserved workers idle", async () => {
|
||||
const records = Array.from({ length: ACTIVE_JOB_LIMIT + 10 }, (_, index) => activeRecord({ _id: `job-${index}` }));
|
||||
const { result, reads, fileChecks } = await activityFixture(records);
|
||||
assert.deepEqual(reads, [{
|
||||
filter: { processing: true }, options: { projection: ACTIVITY_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS },
|
||||
sort: { created_at: 1, _id: 1 }, limit: ACTIVE_JOB_LIMIT + 1,
|
||||
}]);
|
||||
assert.equal(result.truncated, true);
|
||||
assert.equal(result.workers[0].activityUnknown, true);
|
||||
assert.equal(result.workers[0].jobs.length, ACTIVE_JOB_LIMIT);
|
||||
assert.equal(fileChecks.length, ACTIVE_JOB_LIMIT);
|
||||
});
|
||||
|
||||
test("worker inventory is bounded while duplicates outside the visible page remain ambiguous", async () => {
|
||||
const processes = Array.from({ length: WORKER_LIMIT + 1 }, (_, index) => processRecord({
|
||||
pm_id: String(index + 1), name: `proxer-worker-${index + 1}`, pid: 1234 + index,
|
||||
}));
|
||||
processes.push(processRecord({ pm_id: "99", name: "duplicate-beyond-page", pid: 1234 }));
|
||||
const { result } = await activityFixture([activeRecord()], processes);
|
||||
assert.equal(result.workers.length, WORKER_LIMIT);
|
||||
assert.equal(result.workersTruncated, true);
|
||||
assert.equal(result.unassigned[0].assignmentReason, "ambiguous-worker");
|
||||
assert.ok(result.workers.every(worker => worker.activityUnknown));
|
||||
});
|
||||
|
||||
test("activity DTOs remove credentials, signed URLs, raw supervisor metadata, and unknown worker fields", async () => {
|
||||
const { result } = await activityFixture([activeRecord({
|
||||
token: "session=private-cookie-value",
|
||||
url: "https://media.example/file.mp4?signature=private-signature",
|
||||
output_log: "credential private-cookie-value https://media.example/file.mp4?signature=private-signature",
|
||||
worker: { ...identity(), env: { PRIVATE: "private-env" }, token: "private-worker-token" },
|
||||
})], [processRecord({ execPath: "/private-host-path", pm2_env: { SECRET: "private-pm2-env" } })]);
|
||||
const publicText = JSON.stringify(result);
|
||||
assert.doesNotMatch(publicText, /private-cookie-value|private-signature|private-env|private-worker-token|private-host-path|private-pm2-env/);
|
||||
assert.equal(result.workers[0].jobs[0].url, "Source URL unavailable");
|
||||
assert.equal(result.workers[0].jobs[0].token, undefined);
|
||||
});
|
||||
|
||||
test("inventory caching shares concurrent PM2 reads and expires after ten seconds", async () => {
|
||||
let clock = 0;
|
||||
let calls = 0;
|
||||
let finish;
|
||||
const gate = new Promise(resolve => { finish = resolve; });
|
||||
const readInventory = createInventoryReader(async () => { calls += 1; await gate; return [processRecord()]; }, { now: () => clock });
|
||||
const first = readInventory();
|
||||
const second = readInventory();
|
||||
assert.equal(calls, 1);
|
||||
finish();
|
||||
assert.equal((await first).available, true);
|
||||
assert.equal((await second).available, true);
|
||||
await readInventory();
|
||||
assert.equal(calls, 1);
|
||||
clock = 10000;
|
||||
await readInventory();
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test("a supervisor failure is briefly cached but can recover at the next inventory refresh", async () => {
|
||||
let clock = 0;
|
||||
let fail = true;
|
||||
let calls = 0;
|
||||
const readInventory = createInventoryReader(async () => {
|
||||
calls += 1;
|
||||
if (fail) throw new Error("unavailable");
|
||||
return [processRecord()];
|
||||
}, { now: () => clock });
|
||||
assert.equal((await readInventory()).available, false);
|
||||
fail = false;
|
||||
assert.equal((await readInventory()).available, false);
|
||||
assert.equal(calls, 1);
|
||||
clock = 10000;
|
||||
assert.equal((await readInventory()).available, true);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test("active filesize lookup never follows links or unsafe filenames", async t => {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-activity-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
await fs.writeFile(path.join(outputDir, "regular.mp4"), "fixture");
|
||||
await fs.symlink(path.join(outputDir, "regular.mp4"), path.join(outputDir, "link.mp4"));
|
||||
assert.equal(await readActiveFileSize({ filename: "regular" }, { outputDir }), 7);
|
||||
for (const filename of ["link", "missing", "../regular"]) {
|
||||
assert.equal(await readActiveFileSize({ filename }, { outputDir }), null);
|
||||
}
|
||||
});
|
||||
|
||||
function dashboardDatabase({ failure } = {}) {
|
||||
const reads = [];
|
||||
const db = { collection(name) {
|
||||
return {
|
||||
async countDocuments(filter, options) {
|
||||
reads.push({ type: "count", name, filter, options });
|
||||
if (failure) throw failure;
|
||||
return name === "queue" ? (filter.processing === true ? 2 : 3) : 8;
|
||||
},
|
||||
async findOne(filter, options) {
|
||||
reads.push({ type: "global", name, filter, options });
|
||||
return { captcha_blocked: true, pause_reason: "resolution", private: "private-global" };
|
||||
},
|
||||
find(filter, options) {
|
||||
const read = { type: "recent", name, filter, options };
|
||||
reads.push(read);
|
||||
const cursor = {
|
||||
sort(value) { read.sort = value; return cursor; },
|
||||
limit(value) { read.limit = value; return cursor; },
|
||||
async toArray() {
|
||||
return Array.from({ length: 8 }, (_, index) => ({
|
||||
_id: `${name}-${index}`, filename: `Episode ${index}`, token: "cookie=private-history-cookie",
|
||||
output_log: "legacy private-history-cookie", [name === "done" ? "finished_at" : "failed_at"]: CLAIM,
|
||||
})).slice(0, read.limit);
|
||||
},
|
||||
};
|
||||
return cursor;
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, reads };
|
||||
}
|
||||
|
||||
test("dashboard returns bounded recent history, counts, pause state, and activity without exposing raw records", async () => {
|
||||
const fixture = dashboardDatabase();
|
||||
const activity = { workers: [], unassigned: [], truncated: false, workersTruncated: false, available: true };
|
||||
const settings = { outputDir: "/fixture/output" };
|
||||
const controller = createDashboardController({
|
||||
getDb: async () => fixture.db, config: settings,
|
||||
readActivity: async (db, options) => { assert.equal(db, fixture.db); assert.equal(options.settings, settings); return activity; },
|
||||
});
|
||||
const result = await controller.readDashboard();
|
||||
assert.deepEqual(result.counts, { queued: 3, processing: 2, done: 8, failed: 8 });
|
||||
assert.deepEqual(result.global, { captcha_blocked: true, pause_reason: "resolution" });
|
||||
assert.equal(result.activity, activity);
|
||||
for (const state of ["done", "failed"]) {
|
||||
assert.equal(result.recent[state].length, RECENT_LIMIT);
|
||||
assert.equal(result.recent[state][0].fileSize, undefined);
|
||||
}
|
||||
assert.doesNotMatch(JSON.stringify(result), /private-history-cookie|private-global/);
|
||||
const recentReads = fixture.reads.filter(read => read.type === "recent");
|
||||
assert.equal(recentReads.length, 2);
|
||||
for (const read of recentReads) {
|
||||
assert.deepEqual(read.options, { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS });
|
||||
assert.equal(read.limit, RECENT_LIMIT);
|
||||
assert.deepEqual(read.sort, { [read.name === "done" ? "finished_at" : "failed_at"]: -1, _id: -1 });
|
||||
}
|
||||
const countReads = fixture.reads.filter(read => read.type === "count");
|
||||
assert.equal(countReads.length, 4);
|
||||
assert.ok(countReads.every(read => read.options.maxTimeMS === QUERY_TIMEOUT_MS));
|
||||
});
|
||||
|
||||
test("dashboard page and JSON disable caching, and database errors reach the generic error handler", async () => {
|
||||
const fixture = dashboardDatabase();
|
||||
const controller = createDashboardController({ getDb: async () => fixture.db, readActivity: async () => ({ workers: [] }) });
|
||||
for (const [method, render] of [["dashboard", true], ["dashboardData", false]]) {
|
||||
const headers = {};
|
||||
let payload, template;
|
||||
const response = {
|
||||
set(name, value) { headers[name] = value; return response; },
|
||||
render(name, value) { template = name; payload = value; return response; },
|
||||
json(value) { payload = value; return response; },
|
||||
};
|
||||
await controller[method]({}, response, error => { throw error; });
|
||||
assert.equal(headers["Cache-Control"], "no-store");
|
||||
if (render) { assert.equal(template, "dashboard"); assert.equal(payload.activePage, "dashboard"); }
|
||||
else assert.equal(payload.counts.processing, 2);
|
||||
}
|
||||
const failure = new Error("private database detail");
|
||||
const broken = dashboardDatabase({ failure });
|
||||
const unavailable = createDashboardController({ getDb: async () => broken.db, readActivity: async () => ({ workers: [] }) });
|
||||
let received;
|
||||
await unavailable.dashboardData({}, { set() {}, json() { assert.fail("Must not report an empty dashboard on failure"); } }, error => { received = error; });
|
||||
assert.equal(received, failure);
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createConfig } = require('../lib/config');
|
||||
const { createPm2Controller, normalizeProcess } = require('../controllers/pm2Controller');
|
||||
|
||||
const settings = createConfig({ MONGO_URI: 'mongodb://fixture.invalid/unused' });
|
||||
const SEQUENCE_ID = 'worker-name-sequence';
|
||||
|
||||
function response() {
|
||||
return { statusCode: 200,
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
json(body) { this.body = body; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
function processRecord(name, managed = true, id = 0) {
|
||||
return { name, pid: 1000 + id, pm_id: id, pm2_env: {
|
||||
name, status: 'online', pm_exec_path: managed ? settings.workerScript : '/unrelated/server.js',
|
||||
pm_uptime: Date.UTC(2026, 9, 23, 10), TOKEN: 'PRIVATE_PM2_ENV',
|
||||
} };
|
||||
}
|
||||
|
||||
function database(initial) {
|
||||
const state = { value: initial, calls: [], initializationRace: false, acknowledged: true };
|
||||
const collection = {
|
||||
async updateOne(filter, update, options) {
|
||||
state.calls.push({ method: 'updateOne', filter, update, options });
|
||||
assert.deepEqual(filter, { _id: SEQUENCE_ID });
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
assert.deepEqual(Object.keys(update), ['$max']);
|
||||
if (state.value === undefined || state.value < update.$max.value) state.value = update.$max.value;
|
||||
if (state.initializationRace && options.upsert) {
|
||||
state.initializationRace = false;
|
||||
const error = new Error('PRIVATE_MONGO_ERROR');
|
||||
error.code = 11000;
|
||||
throw error;
|
||||
}
|
||||
return { acknowledged: state.acknowledged };
|
||||
},
|
||||
async findOneAndUpdate(filter, update, options) {
|
||||
state.calls.push({ method: 'findOneAndUpdate', filter, update, options });
|
||||
assert.deepEqual(filter, { _id: SEQUENCE_ID, value: { $gte: 0, $lt: Number.MAX_SAFE_INTEGER } });
|
||||
assert.deepEqual(update, { $inc: { value: 1 } });
|
||||
assert.equal(options.returnDocument, 'after');
|
||||
assert.equal(options.includeResultMetadata, false);
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
assert.deepEqual(options.projection, { value: 1 });
|
||||
if (typeof state.value !== 'number' || state.value < 0 || state.value >= Number.MAX_SAFE_INTEGER) return null;
|
||||
return { _id: SEQUENCE_ID, value: ++state.value };
|
||||
},
|
||||
};
|
||||
const db = { collection(name) { assert.equal(name, 'settings'); return collection; } };
|
||||
return { db, state, collection };
|
||||
}
|
||||
|
||||
function supervisor(existing = [], db = database(), commandResult = {}) {
|
||||
const calls = [];
|
||||
const run = async args => {
|
||||
calls.push([...args]);
|
||||
if (args[0] === 'jlist') return { code: 0, stdout: JSON.stringify(existing) };
|
||||
return { code: 0, stdout: 'PRIVATE_PM2_OUTPUT', ...commandResult };
|
||||
};
|
||||
return { controller: createPm2Controller({ settings, run, getDb: async () => db.db }), calls, db, run };
|
||||
}
|
||||
|
||||
test('quick add chooses the next number above managed and unrelated PM2 names', async () => {
|
||||
const f = supervisor([
|
||||
processRecord('proxer-worker-2'), processRecord('proxer-worker-012', false),
|
||||
processRecord('unrelated-worker-999', false), processRecord('proxer-worker-latest', false),
|
||||
]);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({ body: {} }, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(res.body.name, 'proxer-worker-13');
|
||||
assert.equal(res.body.ok, true);
|
||||
assert.deepEqual(f.calls, [['jlist'], ['start', settings.workerScript, '--name', 'proxer-worker-13',
|
||||
'--cwd', settings.projectRoot, '--interpreter', process.execPath, '--kill-timeout', '10000']]);
|
||||
assert.equal(f.db.state.calls[0].update.$max.value, 12);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_|stdout|pm2_env/);
|
||||
});
|
||||
|
||||
test('quick add starts at one and keeps increasing after process deletion and controller restart', async () => {
|
||||
const db = database();
|
||||
for (const expected of [1, 2, 3]) {
|
||||
const f = supervisor([], db);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.body.name, `proxer-worker-${expected}`);
|
||||
}
|
||||
assert.equal(db.state.value, 3);
|
||||
});
|
||||
|
||||
test('concurrent quick-add requests across controllers reserve distinct persistent numbers', async () => {
|
||||
const db = database();
|
||||
const requests = Array.from({ length: 8 }, () => supervisor([processRecord('proxer-worker-5')], db));
|
||||
const results = await Promise.all(requests.map(async f => {
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
return res.body.name;
|
||||
}));
|
||||
assert.equal(new Set(results).size, 8);
|
||||
assert.deepEqual(results.map(name => Number(name.split('-').at(-1))).sort((a, b) => a - b), [6, 7, 8, 9, 10, 11, 12, 13]);
|
||||
assert.equal(db.state.value, 13);
|
||||
});
|
||||
|
||||
test('a duplicate-key initialization race retries seeding without another upsert', async () => {
|
||||
const db = database();
|
||||
db.state.initializationRace = true;
|
||||
const f = supervisor([processRecord('proxer-worker-7')], db);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.body.name, 'proxer-worker-8');
|
||||
assert.equal(db.state.calls.length, 3);
|
||||
assert.equal(db.state.calls[0].options.upsert, true);
|
||||
assert.equal(db.state.calls[1].options.upsert, undefined);
|
||||
});
|
||||
|
||||
test('quick add does not accept a client-selected name, command or script', async () => {
|
||||
const f = supervisor();
|
||||
for (const body of [{ name: 'all' }, { scriptPath: '/unrelated.js' }, { cmd: 'delete' }, [], 'bad']) {
|
||||
const res = response();
|
||||
await f.controller.quickAdd({ body }, res);
|
||||
assert.equal(res.statusCode, 400);
|
||||
}
|
||||
assert.equal(f.calls.length, 0);
|
||||
assert.equal(f.db.state.calls.length, 0);
|
||||
});
|
||||
|
||||
test('failed starts consume their reserved number and expose no supervisor output', async () => {
|
||||
const f = supervisor([], database(), { code: 1 });
|
||||
const failed = response();
|
||||
await f.controller.quickAdd({}, failed);
|
||||
assert.equal(failed.statusCode, 502);
|
||||
assert.equal(failed.body.ok, false);
|
||||
assert.equal(failed.body.name, 'proxer-worker-1');
|
||||
const next = supervisor([], f.db);
|
||||
const created = response();
|
||||
await next.controller.quickAdd({}, created);
|
||||
assert.equal(created.body.name, 'proxer-worker-2');
|
||||
assert.doesNotMatch(JSON.stringify(failed.body), /PRIVATE_/);
|
||||
});
|
||||
|
||||
test('unconfirmed starts keep their reserved number and request refresh before retrying', async () => {
|
||||
const db = database();
|
||||
const controller = createPm2Controller({ settings, getDb: async () => db.db,
|
||||
run: async args => {
|
||||
if (args[0] === 'jlist') return { code: 0, stdout: '[]' };
|
||||
throw new Error('PRIVATE_PM2_FAILURE');
|
||||
},
|
||||
});
|
||||
const res = response();
|
||||
await controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 503);
|
||||
assert.equal(res.body.name, 'proxer-worker-1');
|
||||
assert.match(res.body.error, /Refresh the worker list/);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_/);
|
||||
assert.equal(db.state.value, 1);
|
||||
});
|
||||
|
||||
test('database failures and unacknowledged reservations never start a process', async () => {
|
||||
for (const mode of ['connect', 'seed', 'reserve', 'acknowledge']) {
|
||||
const db = database();
|
||||
if (mode === 'acknowledge') db.state.acknowledged = false;
|
||||
if (mode === 'seed') db.collection.updateOne = async () => { throw new Error('PRIVATE_DATABASE_FAILURE'); };
|
||||
if (mode === 'reserve') db.collection.findOneAndUpdate = async () => { throw new Error('PRIVATE_DATABASE_FAILURE'); };
|
||||
const calls = [];
|
||||
const controller = createPm2Controller({ settings,
|
||||
getDb: async () => { if (mode === 'connect') throw new Error('PRIVATE_DATABASE_FAILURE'); return db.db; },
|
||||
run: async args => { calls.push(args); return { code: 0, stdout: '[]' }; },
|
||||
});
|
||||
const res = response();
|
||||
await controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 503, mode);
|
||||
assert.deepEqual(calls, [['jlist']], mode);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_/);
|
||||
}
|
||||
});
|
||||
|
||||
test('unsafe, exhausted and corrupt saved counters cannot create guessed or duplicate names', async () => {
|
||||
for (const value of [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER + 1, 'corrupt-counter', 0.5]) {
|
||||
const f = supervisor([], database(value));
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 409);
|
||||
assert.deepEqual(f.calls, [['jlist']]);
|
||||
}
|
||||
const f = supervisor([processRecord('proxer-worker-9007199254740992', false)]);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 409);
|
||||
assert.equal(f.db.state.calls.length, 0);
|
||||
assert.deepEqual(f.calls, [['jlist']]);
|
||||
});
|
||||
|
||||
test('managed worker inventory includes validated absolute start time and excludes environments', async () => {
|
||||
const f = supervisor([processRecord('proxer-worker-1'), processRecord('unrelated', false, 4)]);
|
||||
const workers = await f.controller.listManagedProcesses();
|
||||
assert.equal(workers.length, 1);
|
||||
assert.equal(workers[0].startedAtISO, '2026-10-23T10:00:00.000Z');
|
||||
assert.doesNotMatch(JSON.stringify(workers), /PRIVATE_|pm2_env/);
|
||||
for (const value of [undefined, null, 0, -1, Infinity, '178234', 1e20]) {
|
||||
const record = processRecord('proxer-worker-1');
|
||||
record.pm2_env.pm_uptime = value;
|
||||
assert.equal(normalizeProcess(record).startedAtISO, null);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
"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));
|
||||
});
|
||||
@@ -284,7 +284,7 @@ test('normalized PM2 data retains process ID zero and excludes raw environments'
|
||||
assert.equal(normalized.pm_id, '0');
|
||||
assert.equal(normalized.cpu, '2.5%');
|
||||
assert.equal(normalized.memoryMB, '8 MB');
|
||||
assert.deepEqual(Object.keys(normalized).sort(), ['name', 'pid', 'pm_id', 'status', 'cpu', 'memoryMB', 'uptime', 'execPath'].sort());
|
||||
assert.deepEqual(Object.keys(normalized).sort(), ['name', 'pid', 'pm_id', 'status', 'cpu', 'memoryMB', 'uptime', 'startedAtISO', 'execPath'].sort());
|
||||
assert.doesNotMatch(JSON.stringify(normalized), /NOT_A_REAL_|MONGO_URI|pm2_env|"raw"/);
|
||||
});
|
||||
|
||||
|
||||
+15
-62
@@ -7,7 +7,6 @@ const { Duplex } = require('node:stream');
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const express = require('express');
|
||||
const WebSocket = require('ws');
|
||||
const { config } = require('../lib/config');
|
||||
@@ -368,69 +367,23 @@ test('server construction does not listen and heartbeat/server close clean up lo
|
||||
assert.equal(cleared, 1);
|
||||
});
|
||||
|
||||
test('PM2 browser controls use safe DOM text, visible feedback, ready-state checks, and stop on deselect', async () => {
|
||||
class Element {
|
||||
constructor(tag = 'div') {
|
||||
this.tagName = tag;
|
||||
this.className = '';
|
||||
this.children = [];
|
||||
this.dataset = {};
|
||||
this.style = {};
|
||||
this.textContent = '';
|
||||
this.listeners = {};
|
||||
this.scrollTop = this.scrollHeight = this.clientHeight = 0;
|
||||
this.classList = {
|
||||
add: (...names) => { this.className = [...new Set([...this.className.split(' '), ...names])].join(' '); },
|
||||
remove: (...names) => { this.className = this.className.split(' ').filter(name => !names.includes(name)).join(' '); },
|
||||
};
|
||||
}
|
||||
set innerHTML(value) { assert.fail('Untrusted refreshed process fields must not use innerHTML.'); }
|
||||
addEventListener(name, callback) { (this.listeners[name] ||= []).push(callback); }
|
||||
append(...values) { this.children.push(...values); }
|
||||
appendChild(value) { this.children.push(value); return value; }
|
||||
replaceChildren(...values) { this.children = values; }
|
||||
async click() { for (const callback of this.listeners.click || []) await callback({ preventDefault() {}, currentTarget: this }); }
|
||||
}
|
||||
const elements = new Map();
|
||||
const get = id => { if (!elements.has(id)) elements.set(id, new Element()); return elements.get(id); };
|
||||
const document = {
|
||||
getElementById: get,
|
||||
createElement: tag => new Element(tag),
|
||||
querySelectorAll: () => get('process-list').children.filter(node => node.className?.split(' ').includes('pm2-row')),
|
||||
};
|
||||
let socket;
|
||||
class BrowserSocket {
|
||||
static OPEN = 1;
|
||||
constructor() { socket = this; this.readyState = 0; this.sent = []; this.listeners = {}; }
|
||||
addEventListener(name, callback) { this.listeners[name] = callback; }
|
||||
send(text) { assert.equal(this.readyState, 1); this.sent.push(JSON.parse(text)); }
|
||||
}
|
||||
const maliciousName = '<img src=x onerror=alert(1)>';
|
||||
const process = { name: maliciousName, pm_id: '0', pid: '12', status: '<script>fixture</script>', execPath: '<b>fixture</b>', uptime: '1m' };
|
||||
const context = vm.createContext({
|
||||
document,
|
||||
WebSocket: BrowserSocket,
|
||||
window: { addEventListener() {} },
|
||||
location: { protocol: 'http:', host: 'fixture.invalid' },
|
||||
fetch: async () => ({ ok: true, json: async () => ({ ok: true, processes: [process] }) }),
|
||||
test('worker view escapes process fields and exposes accessible scoped controls', async () => {
|
||||
const filename = path.join(config.projectRoot, 'views/pm2.ejs');
|
||||
const template = fs.readFileSync(filename, 'utf8');
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const rendered = await require('ejs').renderFile(filename, {
|
||||
processes: [{ name: attack, pm_id: '0', pid: '12', status: attack, execPath: attack,
|
||||
cpu: '1.2%', memoryMB: '40 MB', uptime: '1m' }],
|
||||
});
|
||||
const template = fs.readFileSync(path.join(config.projectRoot, 'views/pm2.ejs'), 'utf8');
|
||||
assert.equal(template.includes('id="btn-save"'), false);
|
||||
assert.equal(template.includes('/home/pm2/'), false);
|
||||
assert.ok(template.indexOf('id="control-output"') < template.indexOf('id="control-centre"'));
|
||||
const script = template.match(/<script>([\s\S]*?)<\/script>/)[1];
|
||||
vm.runInContext(script + '\nglobalThis.fixture = { refreshList, sendLogRequest, appendLog };', context);
|
||||
assert.equal(context.fixture.sendLogRequest({ type: 'logs', name: 'worker-one' }, false), false);
|
||||
assert.equal(socket.sent.length, 0);
|
||||
await context.fixture.refreshList();
|
||||
const row = document.querySelectorAll()[0];
|
||||
assert.equal(row.children[0].children[0].textContent, maliciousName);
|
||||
assert.equal(row.dataset.name, maliciousName);
|
||||
socket.readyState = 1;
|
||||
await row.click();
|
||||
assert.equal(socket.sent.at(-1).type, 'logs');
|
||||
await row.click();
|
||||
assert.equal(socket.sent.at(-1).type, 'stop-logs');
|
||||
context.fixture.appendLog('x'.repeat(200_000));
|
||||
assert.ok(get('logs').textContent.length < 66 * 1024);
|
||||
assert.match(template, /<script src="\/workers\.js" defer><\/script>/);
|
||||
assert.doesNotMatch(template, /<script>/);
|
||||
assert.ok(!rendered.includes(attack));
|
||||
assert.match(rendered, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.match(rendered, /type="button" class="worker-row" aria-pressed="false"/);
|
||||
assert.match(rendered, /data-pmid="0"/);
|
||||
assert.match(rendered, /for="worker-name"/);
|
||||
assert.match(rendered, /role="status" aria-live="polite"/);
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { createSessionTokenService, SessionTokenError, CACHE_ID, STATUS_PROJECTION } = require("../lib/sessionToken");
|
||||
const { ValidationError } = require("../lib/jobValidation");
|
||||
const { createProxerSessionProbe, classifyWatchResponse } = require("../lib/proxerSessionProbe");
|
||||
|
||||
const url = "https://proxer.me/watch/42/9/engsub";
|
||||
const settings = { tokenPrefix: "fixture_cookie=" };
|
||||
const checkedAt = new Date("2026-10-23T12:00:00.000Z");
|
||||
const cookie = "fixture_cookie=NOT_A_REAL_COOKIE==";
|
||||
const sourcePage = '<!doctype html><html><head><title>Episode - Proxer.Me</title></head><body><script>const stream={"code":"fixture_embed_id"};</script></body></html>';
|
||||
|
||||
function fixtureRecord(overrides = {}) {
|
||||
return {
|
||||
_id: CACHE_ID, cookie, cookie_name: "fixture_cookie", state: "ready", revision: "fixture-revision-1",
|
||||
saved_at: new Date("2026-10-22T08:00:00Z"), validated_at: new Date("2026-10-22T08:00:00Z"), ...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function database(initial = null) {
|
||||
let current = initial ? structuredClone(initial) : null;
|
||||
const reads = [];
|
||||
const writes = [];
|
||||
const collection = {
|
||||
async findOne(filter, options) {
|
||||
reads.push({ filter: structuredClone(filter), options });
|
||||
assert.deepEqual(filter, { _id: CACHE_ID });
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
if (!current) return null;
|
||||
return Object.fromEntries(Object.entries(current).filter(([key]) => key === "_id" || options.projection[key] === 1));
|
||||
},
|
||||
async updateOne(filter, update, options) {
|
||||
writes.push({ filter: structuredClone(filter), update: structuredClone(update), options });
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
const matches = current && (Object.hasOwn(filter.revision, "$eq")
|
||||
? current.revision === filter.revision.$eq : !Object.hasOwn(current, "revision"));
|
||||
if (current && !matches) {
|
||||
if (options.upsert) throw Object.assign(new Error("duplicate key"), { code: 11000 });
|
||||
return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
||||
}
|
||||
if (!current && !options.upsert) return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
||||
const inserted = !current;
|
||||
current ||= { _id: CACHE_ID };
|
||||
Object.assign(current, structuredClone(update.$set));
|
||||
for (const key of Object.keys(update.$unset || {})) delete current[key];
|
||||
return { acknowledged: true, matchedCount: inserted ? 0 : 1, upsertedCount: inserted ? 1 : 0 };
|
||||
},
|
||||
};
|
||||
return {
|
||||
db: { collection(name) { assert.equal(name, "settings"); return collection; } },
|
||||
reads, writes, collection,
|
||||
current: () => structuredClone(current),
|
||||
replace(value) { current = structuredClone(value); },
|
||||
};
|
||||
}
|
||||
|
||||
function service(store, overrides = {}) {
|
||||
return createSessionTokenService({ getDb: async () => store.db, settings, now: () => checkedAt,
|
||||
probe: async () => ({ state: "valid" }), ...overrides });
|
||||
}
|
||||
|
||||
function expectedError(code, status) {
|
||||
return error => {
|
||||
assert.ok(error instanceof SessionTokenError);
|
||||
assert.equal(error.code, code);
|
||||
if (status) assert.equal(error.httpStatus, status);
|
||||
assert.doesNotMatch(error.message, /NOT_A_REAL_|fixture_cookie|fixture_embed|PRIVATE/);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
test("a supplied token is checked against the first canonical source before being cached", async () => {
|
||||
const store = database();
|
||||
const checks = [];
|
||||
const tokens = service(store, { probe: async (...args) => {
|
||||
checks.push(args);
|
||||
assert.equal(store.current(), null, "the token must not be saved before verification");
|
||||
return { state: "valid" };
|
||||
} });
|
||||
const result = await tokens.resolveForEnqueue("NOT_A_REAL_COOKIE==", { url });
|
||||
assert.deepEqual(checks, [[cookie, { url }]]);
|
||||
assert.equal(result.cookie, cookie);
|
||||
assert.equal(result.source, "supplied");
|
||||
assert.equal(result.status.available, true);
|
||||
assert.equal(result.status.lastValidatedAt, checkedAt.toISOString());
|
||||
assert.equal(store.current().cookie, cookie);
|
||||
assert.equal(store.current().cookie_name, "fixture_cookie");
|
||||
assert.equal(store.current().state, "ready");
|
||||
assert.equal(Object.hasOwn(store.current(), "expires_at"), false);
|
||||
assert.doesNotMatch(JSON.stringify(result.status), /NOT_A_REAL_|fixture_cookie/);
|
||||
});
|
||||
|
||||
test("blank submissions reuse a saved token but validate it every time without a time-to-live shortcut", async () => {
|
||||
const store = database(fixtureRecord({ saved_at: new Date("2000-01-01"), validated_at: new Date("2000-01-01") }));
|
||||
let calls = 0;
|
||||
const tokens = service(store, { probe: async (value, input) => {
|
||||
assert.equal(value, cookie); assert.equal(input.url, url); calls++;
|
||||
return { state: "valid" };
|
||||
} });
|
||||
for (const value of ["", undefined, null]) {
|
||||
const result = await tokens.resolveForEnqueue(value, { url });
|
||||
assert.equal(result.source, "cached");
|
||||
assert.equal(result.cookie, cookie);
|
||||
}
|
||||
assert.equal(calls, 3);
|
||||
assert.equal(store.current().validated_at.toISOString(), checkedAt.toISOString());
|
||||
assert.equal(store.current().saved_at.toISOString(), "2000-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("safe cache metadata never reads or exposes the cookie or revision", async () => {
|
||||
const store = database(fixtureRecord({ PRIVATE_EXTRA: "PRIVATE_VALUE" }));
|
||||
const status = await service(store).readStatus();
|
||||
assert.deepEqual(status, { available: true, state: "saved", lastValidatedAt: "2026-10-22T08:00:00.000Z", savedAt: "2026-10-22T08:00:00.000Z" });
|
||||
assert.deepEqual(store.reads[0].options.projection, STATUS_PROJECTION);
|
||||
assert.equal(Object.hasOwn(STATUS_PROJECTION, "cookie"), false);
|
||||
assert.equal(Object.hasOwn(STATUS_PROJECTION, "revision"), false);
|
||||
assert.doesNotMatch(JSON.stringify(status), /NOT_A_REAL_|PRIVATE|fixture_cookie|revision/);
|
||||
});
|
||||
|
||||
test("missing, invalid and differently named saved cookies require new input without probing", async () => {
|
||||
for (const [record, code] of [[null, "missing"], [fixtureRecord({ state: "invalid" }), "invalid"], [fixtureRecord({ cookie_name: "different_cookie" }), "missing"]]) {
|
||||
const store = database(record);
|
||||
const tokens = service(store, { probe: async () => assert.fail("No usable cookie must not be probed") });
|
||||
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError(code, 400));
|
||||
assert.equal(store.writes.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed supplied values and unsafe source URLs fail before any database or network access", async () => {
|
||||
const tokens = createSessionTokenService({ settings,
|
||||
getDb: async () => assert.fail("Database must not be used"),
|
||||
probe: async () => assert.fail("Network must not be used"),
|
||||
});
|
||||
for (const value of [[], {}, " ", "abc; other=PRIVATE", "abc\nPRIVATE"]) {
|
||||
await assert.rejects(tokens.resolveForEnqueue(value, { url }), ValidationError);
|
||||
}
|
||||
await assert.rejects(tokens.resolveForEnqueue("fixture", { url: "https://evil.invalid/watch/42/9/engsub" }), ValidationError);
|
||||
});
|
||||
|
||||
test("definite rejection removes only the rejected cached credential and keeps an invalid marker", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
const tokens = service(store, { probe: async () => ({ state: "invalid" }) });
|
||||
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError("invalid", 400));
|
||||
assert.equal(store.current().state, "invalid");
|
||||
assert.equal(Object.hasOwn(store.current(), "cookie"), false);
|
||||
assert.notEqual(store.current().revision, "fixture-revision-1");
|
||||
assert.equal((await tokens.readStatus()).available, false);
|
||||
});
|
||||
|
||||
test("rejecting a newly supplied token preserves a different saved token", async () => {
|
||||
const original = fixtureRecord();
|
||||
const store = database(original);
|
||||
await assert.rejects(service(store, { probe: async () => ({ state: "invalid" }) })
|
||||
.resolveForEnqueue("NOT_A_REAL_BAD_REPLACEMENT", { url }), expectedError("invalid"));
|
||||
assert.deepEqual(store.current(), original);
|
||||
assert.equal(store.writes.length, 0);
|
||||
});
|
||||
|
||||
test("network, verification, missing-source and unknown checks preserve the cached token and do not claim expiry", async () => {
|
||||
for (const state of ["unavailable", "verification", "source", "unverifiable", "unexpected"]) {
|
||||
const original = fixtureRecord();
|
||||
const store = database(original);
|
||||
await assert.rejects(service(store, { probe: async () => ({ state }) }).resolveForEnqueue("", { url }), error => {
|
||||
expectedError(state === "unexpected" ? "unverifiable" : state)(error);
|
||||
assert.doesNotMatch(error.message, /expired|rejected/i);
|
||||
return true;
|
||||
});
|
||||
assert.deepEqual(store.current(), original);
|
||||
assert.equal(store.writes.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("probe exceptions and database errors cannot leak upstream response bodies or credentials", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
await assert.rejects(service(store, { probe: async () => { throw new Error(`PRIVATE ${cookie}`); } })
|
||||
.resolveForEnqueue("", { url }), expectedError("unavailable", 503));
|
||||
const broken = createSessionTokenService({ settings, getDb: async () => { throw new Error(`PRIVATE ${cookie}`); } });
|
||||
await assert.rejects(broken.readStatus(), expectedError("storage", 503));
|
||||
await assert.rejects(broken.resolveForEnqueue("fixture", { url }), expectedError("storage", 503));
|
||||
});
|
||||
|
||||
test("malformed stored credentials are invalidated locally without a request", async () => {
|
||||
for (const stored of ["wrong_name=PRIVATE", "fixture_cookie=invalid; other=PRIVATE", null]) {
|
||||
const store = database(fixtureRecord({ cookie: stored }));
|
||||
await assert.rejects(service(store, { probe: async () => assert.fail("Must not send malformed cookie") })
|
||||
.resolveForEnqueue("", { url }), expectedError("invalid"));
|
||||
assert.equal(store.current().state, "invalid");
|
||||
assert.equal(Object.hasOwn(store.current(), "cookie"), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("an old failed check cannot invalidate a newer token saved while it was in flight", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_NEW_COOKIE", revision: "newer-revision" });
|
||||
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "invalid" }; } });
|
||||
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError("invalid"));
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
assert.deepEqual(store.writes[0].filter.revision, { $eq: "fixture-revision-1" });
|
||||
});
|
||||
|
||||
test("an old successful replacement cannot overwrite a newer concurrently saved token", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_NEW_COOKIE", revision: "newer-revision" });
|
||||
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "valid" }; } });
|
||||
const result = await tokens.resolveForEnqueue("NOT_A_REAL_SLOW_REPLACEMENT", { url });
|
||||
assert.equal(result.cookie, "fixture_cookie=NOT_A_REAL_SLOW_REPLACEMENT");
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
assert.equal(result.status.available, true);
|
||||
});
|
||||
|
||||
test("an older rejected check cannot erase a cached token after a later successful revalidation", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
let releaseOldCheck;
|
||||
let oldCheckStarted;
|
||||
const started = new Promise(resolve => { oldCheckStarted = resolve; });
|
||||
const old = service(store, { probe: async () => {
|
||||
oldCheckStarted();
|
||||
return new Promise(resolve => { releaseOldCheck = resolve; });
|
||||
} });
|
||||
const oldResult = old.resolveForEnqueue("", { url });
|
||||
const rejected = assert.rejects(oldResult, expectedError("invalid"));
|
||||
await started;
|
||||
await service(store).resolveForEnqueue("", { url });
|
||||
const fresh = store.current();
|
||||
assert.notEqual(fresh.revision, "fixture-revision-1");
|
||||
releaseOldCheck({ state: "invalid" });
|
||||
await rejected;
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
assert.equal(store.current().cookie, cookie);
|
||||
});
|
||||
|
||||
test("concurrent first saves tolerate the unique-id insertion race without replacing the winner", async () => {
|
||||
const store = database();
|
||||
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_FIRST_WINNER", revision: "winner" });
|
||||
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "valid" }; } });
|
||||
const result = await tokens.resolveForEnqueue("NOT_A_REAL_SLOW_REPLACEMENT", { url });
|
||||
assert.equal(result.source, "supplied");
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
});
|
||||
|
||||
test("unacknowledged cache writes stop submission with a safe error", async () => {
|
||||
const store = database();
|
||||
store.collection.updateOne = async () => ({ acknowledged: false });
|
||||
await assert.rejects(service(store).resolveForEnqueue("fixture", { url }), expectedError("storage", 503));
|
||||
});
|
||||
|
||||
test("download-access proof requires a usable source marker instead of HTTP 200 alone", () => {
|
||||
assert.deepEqual(classifyWatchResponse(200, sourcePage), { state: "valid" });
|
||||
for (const body of ["<html>Ordinary page</html>", '<script>{"code":""}</script>', '<script>{"code":"https://evil.invalid"}</script>']) {
|
||||
assert.deepEqual(classifyWatchResponse(200, body), { state: "unverifiable" });
|
||||
}
|
||||
assert.deepEqual(classifyWatchResponse(200, sourcePage, "application/json"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(404, sourcePage), { state: "source" });
|
||||
});
|
||||
|
||||
test("challenge and access-denial responses are distinguished from token expiry and source changes", () => {
|
||||
assert.deepEqual(classifyWatchResponse(403, "<title>Attention Required! | Cloudflare</title>"), { state: "verification" });
|
||||
assert.deepEqual(classifyWatchResponse(200, '<form id="challenge-form">check</form>'), { state: "verification" });
|
||||
assert.deepEqual(classifyWatchResponse(200, "<main>Bitte logge dich ein, um diesen Bereich betreten zu können.</main>"), { state: "invalid" });
|
||||
assert.deepEqual(classifyWatchResponse(200, "<main>Bitte logge dich ein, um diesen Bereich betreten zu können.</main>"), { state: "invalid" });
|
||||
assert.deepEqual(classifyWatchResponse(401, "<main>Denied</main>"), { state: "invalid" });
|
||||
assert.deepEqual(classifyWatchResponse(403, "<main>Denied</main>"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(503, "<main>Unavailable</main>"), { state: "unavailable" });
|
||||
assert.deepEqual(classifyWatchResponse(200, "<main>Complete the CAPTCHA.</main>"), { state: "verification" });
|
||||
assert.deepEqual(classifyWatchResponse(200, '<script>const text="Bitte logge dich ein, um diesen Bereich betreten zu können.";</script>'), { state: "unverifiable" });
|
||||
});
|
||||
|
||||
test("non-HTML error statuses retain their meaning while JSON success and redirects never prove access", () => {
|
||||
const json = '{"code":"fixture_embed_id"}';
|
||||
for (const [status, expected] of [[401, "invalid"], [429, "unavailable"], [503, "unavailable"], [404, "source"], [410, "source"]]) {
|
||||
assert.deepEqual(classifyWatchResponse(status, json, "application/json"), { state: expected });
|
||||
}
|
||||
assert.deepEqual(classifyWatchResponse(200, json, "application/json"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(302, sourcePage, "text/html"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(302, json, "application/json"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(401, "<title>Attention Required! | Cloudflare</title>", "text/html"), { state: "verification" });
|
||||
});
|
||||
|
||||
test("the probe sends only the configured cookie and stream preference to a canonical HTTPS source", async () => {
|
||||
const calls = [];
|
||||
const probe = createProxerSessionProbe({ fetch: async (target, options) => {
|
||||
calls.push({ target, options });
|
||||
return new Response(sourcePage, { headers: { "Content-Type": "text/html; charset=UTF-8" } });
|
||||
} });
|
||||
assert.deepEqual(await probe(cookie, { url: "https://www.proxer.me/watch/42/9/engsub/#top" }), { state: "valid" });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].target, url);
|
||||
assert.equal(calls[0].options.headers.Cookie, `${cookie}; stream_choose=proxer-stream`);
|
||||
assert.equal(calls[0].options.redirect, "manual");
|
||||
assert.equal(calls[0].options.credentials, "omit");
|
||||
assert.equal(calls[0].options.method, "GET");
|
||||
});
|
||||
|
||||
test("redirects, unsupported sources and header injection cannot forward the cookie elsewhere", async () => {
|
||||
let calls = 0;
|
||||
const probe = createProxerSessionProbe({ fetch: async () => {
|
||||
calls++;
|
||||
return new Response("", { status: 302, headers: { Location: "https://evil.invalid/capture" } });
|
||||
} });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: "unverifiable" });
|
||||
assert.equal(calls, 1);
|
||||
for (const target of ["http://proxer.me/watch/42/9/engsub", "https://evil.invalid/watch/42/9/engsub", `${url}?token=PRIVATE`]) {
|
||||
await assert.rejects(probe(cookie, { url: target }), ValidationError);
|
||||
}
|
||||
await assert.rejects(probe(`${cookie}; evil=PRIVATE`, { url }), ValidationError);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test("oversized, truncated and non-HTML responses do not pass the access check", async () => {
|
||||
for (const response of [
|
||||
new Response(sourcePage, { headers: { "content-type": "text/html", "content-length": "1000000" } }),
|
||||
new Response("x".repeat(1000) + sourcePage, { headers: { "content-type": "text/html" } }),
|
||||
new Response(sourcePage, { headers: { "content-type": "application/json" } }),
|
||||
new Response(new ReadableStream({ start(controller) { controller.error(new Error(`PRIVATE ${cookie}`)); } }), { headers: { "content-type": "text/html" } }),
|
||||
]) {
|
||||
const probe = createProxerSessionProbe({ fetch: async () => response, maxBytes: 500 });
|
||||
const result = await probe(cookie, { url });
|
||||
assert.notEqual(result.state, "valid");
|
||||
assert.doesNotMatch(JSON.stringify(result), /NOT_A_REAL_|PRIVATE/);
|
||||
}
|
||||
});
|
||||
|
||||
test("the probe preserves explicit status for absent and oversized bodies without accepting empty success", async () => {
|
||||
for (const [status, expected] of [[401, "invalid"], [503, "unavailable"], [200, "unverifiable"]]) {
|
||||
for (const body of [null, "x".repeat(1000)]) {
|
||||
const probe = createProxerSessionProbe({ maxBytes: 128, fetch: async () => new Response(body, {
|
||||
status, headers: { "content-type": "text/html" },
|
||||
}) });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: expected });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a hard deadline aborts a stuck request without exposing fetch errors", async () => {
|
||||
let signal;
|
||||
const probe = createProxerSessionProbe({ timeoutMs: 15, fetch: async (_, options) => {
|
||||
signal = options.signal;
|
||||
return new Promise(() => {});
|
||||
} });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: "unavailable" });
|
||||
assert.equal(signal.aborted, true);
|
||||
const throwing = createProxerSessionProbe({ fetch: async () => { throw new Error(`PRIVATE ${cookie}`); } });
|
||||
assert.deepEqual(await throwing(cookie, { url }), { state: "unavailable" });
|
||||
});
|
||||
|
||||
test("a Cloudflare challenge header wins even if an HTML body happens to contain a code field", async () => {
|
||||
const probe = createProxerSessionProbe({ fetch: async () => new Response(sourcePage, {
|
||||
headers: { "content-type": "text/html", "cf-mitigated": "challenge" },
|
||||
}) });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: "verification" });
|
||||
});
|
||||
@@ -0,0 +1,310 @@
|
||||
"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 { createQueueController: createRealQueueController } = require("../controllers/queueController");
|
||||
// These tests isolate the existing form/page contracts. Dedicated activity and
|
||||
// token-controller suites exercise the added services, without live HTTP calls.
|
||||
function createQueueController(options = {}) {
|
||||
return createRealQueueController({
|
||||
...options,
|
||||
readActivity: options.readActivity || (async () => ({ workers: [], unassigned: [], available: true, truncated: false, workersTruncated: false })),
|
||||
sessionTokens: options.sessionTokens || {
|
||||
readStatus: async () => ({ available: false, state: "missing", lastValidatedAt: null, savedAt: null }),
|
||||
resolveForEnqueue: async value => ({ cookie: require("../lib/jobValidation").cookieToken(value, options.config?.tokenPrefix || "fixture=") }),
|
||||
},
|
||||
});
|
||||
}
|
||||
const { ValidationError } = require("../lib/jobValidation");
|
||||
const { parseStatusQuery, stateQuery, statusFilter, publicGlobal, QUERY_TIMEOUT_MS } = require("../lib/statusQuery");
|
||||
|
||||
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; },
|
||||
};
|
||||
}
|
||||
|
||||
function databaseFixture({ data = {}, global = null, recordReadsAllowed = true } = {}) {
|
||||
const calls = [];
|
||||
function matches(record, filter) {
|
||||
if (filter.processing === true && record.processing !== true) return false;
|
||||
if (filter.processing?.$ne === true && record.processing === true) return false;
|
||||
if (filter.filename && !new RegExp(filter.filename.$regex, filter.filename.$options).test(record.filename)) return false;
|
||||
return true;
|
||||
}
|
||||
const db = { collection(name) {
|
||||
if (name === "settings") return { findOne: async (filter, options) => {
|
||||
calls.push({ operation: "settings", filter, options });
|
||||
return global;
|
||||
} };
|
||||
return {
|
||||
countDocuments: async (filter, options) => {
|
||||
calls.push({ operation: "count", name, filter, options });
|
||||
return (data[name] || []).filter(record => matches(record, filter)).length;
|
||||
},
|
||||
find(filter, options) {
|
||||
assert.ok(recordReadsAllowed, "summary must not read job records");
|
||||
const call = { operation: "find", name, filter, options };
|
||||
calls.push(call);
|
||||
return {
|
||||
sort(sort) { call.sort = sort; return this; },
|
||||
skip(skip) { call.skip = skip; return this; },
|
||||
limit(limit) { call.limit = limit; return this; },
|
||||
async toArray() {
|
||||
assert.ok(Number.isInteger(call.skip) && call.skip >= 0, "skip is set before materialization");
|
||||
assert.ok([10, 25, 50].includes(call.limit), "bounded limit is set before materialization");
|
||||
const rows = (data[name] || []).filter(record => matches(record, filter));
|
||||
rows.sort((a, b) => {
|
||||
for (const [key, direction] of Object.entries(call.sort)) {
|
||||
if (a[key] < b[key]) return -direction;
|
||||
if (a[key] > b[key]) return direction;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
return rows.slice(call.skip, call.skip + call.limit).map(record =>
|
||||
Object.fromEntries(Object.entries(record).filter(([key]) => options.projection[key] === 1)));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, calls };
|
||||
}
|
||||
|
||||
async function temporaryConfig(t, extras = {}) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-status-query-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
return { outputDir, tokenPrefix: "fixture=", maxSeriesEpisodes: 500, ...extras };
|
||||
}
|
||||
|
||||
test("queue filters default safely and accept bounded scalar pagination", () => {
|
||||
assert.deepEqual(parseStatusQuery(), { state: "queued", q: "", page: 1, pageSize: 25 });
|
||||
assert.deepEqual(parseStatusQuery({ state: "done", q: " Episode 🎬 ", page: "100000", pageSize: "50" }), {
|
||||
state: "done", q: "Episode 🎬", page: 100000, pageSize: 50,
|
||||
});
|
||||
assert.deepEqual(parseStatusQuery({ q: " ", pageSize: "10", ignored: "anything" }), {
|
||||
state: "queued", q: "", page: 1, pageSize: 10,
|
||||
});
|
||||
});
|
||||
|
||||
test("query parsing rejects arrays, objects, malformed Unicode and unbounded numbers", () => {
|
||||
const invalid = [null, [], "string", { state: "all" }, { state: ["queued", "done"] }, { q: { $ne: "" } },
|
||||
{ q: "x".repeat(101) }, { q: "line\nbreak" }, { q: "bad\u0085control" }, { q: "bad\uD800" },
|
||||
{ page: "0" }, { page: "1.5" }, { page: "1e3" }, { page: "01" }, { page: "100001" },
|
||||
{ page: "9".repeat(300) }, { page: 2 }, { pageSize: "500" }, { pageSize: "025" }, { pageSize: ["10"] }];
|
||||
for (const query of invalid) assert.throws(() => parseStatusQuery(query), ValidationError, JSON.stringify(query));
|
||||
});
|
||||
|
||||
test("filename search escapes every regex operator and never accepts arbitrary Mongo fields", () => {
|
||||
const text = "Episode [1].*(a|b)?+$^{}\\";
|
||||
const filter = statusFilter("queued", text);
|
||||
assert.deepEqual(filter.processing, { $ne: true });
|
||||
assert.deepEqual(Object.keys(filter).sort(), ["filename", "processing"]);
|
||||
assert.equal(filter.filename.$options, "i");
|
||||
const regex = new RegExp(filter.filename.$regex, "i");
|
||||
assert.ok(regex.test(`Prefix ${text} suffix`));
|
||||
assert.equal(regex.test("Episode 1 and everything else"), false);
|
||||
assert.deepEqual(statusFilter("failed", ""), {});
|
||||
});
|
||||
|
||||
test("each status sort has a deterministic id tie breaker", () => {
|
||||
for (const state of ["queued", "processing", "done", "failed"]) {
|
||||
const selected = stateQuery(state);
|
||||
assert.equal(Object.keys(selected.sort).at(-1), "_id");
|
||||
assert.equal(selected.sort._id, ["queued", "processing"].includes(state) ? 1 : -1);
|
||||
}
|
||||
assert.throws(() => stateQuery("settings"), ValidationError);
|
||||
});
|
||||
|
||||
test("summary counts states without loading records, logs, credentials or file metadata", async () => {
|
||||
const { db, calls } = databaseFixture({
|
||||
data: { queue: [{ processing: false }, {}, { processing: true }], done: [{}, {}], failed: [{}] },
|
||||
global: { captcha_blocked: true, pause_reason: "resolution", token: "private-settings" },
|
||||
recordReadsAllowed: false,
|
||||
});
|
||||
const controller = createQueueController({ getDb: async () => db });
|
||||
const result = response();
|
||||
await controller.statusSummary({}, result, error => { throw error; });
|
||||
assert.deepEqual(result.data, { counts: { queued: 2, processing: 1, done: 2, failed: 1 },
|
||||
global: { captcha_blocked: true, pause_reason: "resolution" } });
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(calls.filter(call => call.operation === "count").length, 4);
|
||||
assert.ok(calls.every(call => call.options.maxTimeMS === QUERY_TIMEOUT_MS));
|
||||
assert.deepEqual(calls.find(call => call.operation === "settings").options.projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
});
|
||||
|
||||
test("paginated status reads only one selected collection page with an internal redaction projection", async () => {
|
||||
const queue = Array.from({ length: 72 }, (_, index) => ({
|
||||
_id: String(index).padStart(3, "0"), filename: `Episode ${index}`, created_at: new Date("2026-01-01"),
|
||||
processing: false, token: "session=internal-credential==", output_log: "Captured internal-credential==",
|
||||
private_field: "private-data",
|
||||
}));
|
||||
queue.push({ _id: "active", processing: true });
|
||||
const { db, calls } = databaseFixture({ data: { queue, done: [{ _id: "history" }] } });
|
||||
const controller = createQueueController({ getDb: async () => db });
|
||||
const result = response();
|
||||
await controller.statusData({ query: { state: "queued", page: "2", pageSize: "25" } }, result, error => { throw error; });
|
||||
assert.equal(result.data.items.length, 25);
|
||||
assert.equal(result.data.items[0]._id, "025");
|
||||
assert.equal(result.data.items.at(-1)._id, "049");
|
||||
assert.deepEqual(result.data.counts, { queued: 72, processing: 1, done: 1, failed: 0 });
|
||||
assert.deepEqual(result.data.pagination, { page: 2, pageSize: 25, total: 72, totalPages: 3 });
|
||||
assert.deepEqual(result.data.filters, { state: "queued", q: "" });
|
||||
const reads = calls.filter(call => call.operation === "find");
|
||||
assert.equal(reads.length, 1);
|
||||
assert.equal(reads[0].name, "queue");
|
||||
assert.equal(reads[0].skip, 25);
|
||||
assert.equal(reads[0].limit, 25);
|
||||
assert.equal(reads[0].options.projection.token, 1);
|
||||
assert.equal(reads[0].options.maxTimeMS, QUERY_TIMEOUT_MS);
|
||||
assert.match(result.data.items[0].output_log, /\[redacted\]/);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /internal-credential|private-data|private_field|"token"/);
|
||||
assert.equal(Object.hasOwn(result.data, "queued"), false);
|
||||
assert.equal(Object.hasOwn(result.data, "done"), false);
|
||||
});
|
||||
|
||||
test("literal search changes the selected total while keeping global state counts intact", async () => {
|
||||
const { db, calls } = databaseFixture({ data: { failed: [
|
||||
{ _id: "one", filename: "Episode [01]", failed_at: "2026-01-01" },
|
||||
{ _id: "two", filename: "Episode 0", failed_at: "2026-01-02" },
|
||||
{ _id: "three", filename: "episode [01] repeat", failed_at: "2026-01-03" },
|
||||
] } });
|
||||
const controller = createQueueController({ getDb: async () => db });
|
||||
const result = response();
|
||||
await controller.statusData({ query: { state: "failed", q: " [01] " } }, result, error => { throw error; });
|
||||
assert.deepEqual(result.data.items.map(job => job._id), ["three", "one"]);
|
||||
assert.equal(result.data.counts.failed, 3);
|
||||
assert.equal(result.data.pagination.total, 2);
|
||||
assert.equal(result.data.filters.q, "[01]");
|
||||
const extraCount = calls.filter(call => call.operation === "count" && call.filter.filename);
|
||||
assert.equal(extraCount.length, 1);
|
||||
assert.deepEqual(extraCount[0].filter, calls.find(call => call.operation === "find").filter);
|
||||
});
|
||||
|
||||
test("pages clamp after records disappear and an empty state remains on page one", async () => {
|
||||
for (const amount of [0, 12]) {
|
||||
const { db, calls } = databaseFixture({ data: { queue: Array.from({ length: amount }, (_, index) => ({
|
||||
_id: String(index), filename: `Episode ${index}`,
|
||||
})) } });
|
||||
const result = response();
|
||||
await createQueueController({ getDb: async () => db }).statusData({ query: { page: "999", pageSize: "10" } }, result, error => { throw error; });
|
||||
assert.equal(result.data.pagination.page, amount ? 2 : 1);
|
||||
assert.equal(result.data.pagination.totalPages, amount ? 2 : 1);
|
||||
assert.equal(result.data.items.length, amount ? 2 : 0);
|
||||
assert.equal(calls.find(call => call.operation === "find").skip, amount ? 10 : 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed filters produce safe 400s before any database access", async () => {
|
||||
const controller = createQueueController({ getDb: () => { throw new Error("database must not be read"); } });
|
||||
for (const method of ["status", "statusData"]) {
|
||||
const result = response();
|
||||
await controller[method]({ query: { q: { $where: "private-input" } } }, result, error => { throw error; });
|
||||
assert.equal(result.statusCode, 400);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /private-input|\$where/);
|
||||
if (method === "status") assert.equal(result.template, "error");
|
||||
else assert.equal(result.data.ok, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("history file sizes are restricted to visible regular files and refuse links", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
await fs.writeFile(path.join(config.outputDir, "Episode.mp4"), "fixture-bytes");
|
||||
await fs.symlink(path.join(config.outputDir, "Episode.mp4"), path.join(config.outputDir, "Link.mp4"));
|
||||
const { db } = databaseFixture({ data: { done: [
|
||||
{ _id: "one", filename: "Episode" }, { _id: "two", filename: "Link" }, { _id: "three", filename: "../outside" },
|
||||
] } });
|
||||
const result = response();
|
||||
await createQueueController({ config, getDb: async () => db }).statusData({ query: { state: "done" } }, result, error => { throw error; });
|
||||
const sizes = Object.fromEntries(result.data.items.map(job => [job.filename, job.fileSize]));
|
||||
assert.equal(sizes.Episode, 13);
|
||||
assert.equal(sizes.Link, null);
|
||||
assert.equal(sizes["../outside"], null);
|
||||
});
|
||||
|
||||
test("global status keeps only the known pause flag and reasons", () => {
|
||||
assert.deepEqual(publicGlobal(null), { captcha_blocked: false, pause_reason: null });
|
||||
assert.deepEqual(publicGlobal({ captcha_blocked: "true", pause_reason: "<script>" }), { captcha_blocked: false, pause_reason: null });
|
||||
for (const reason of ["authentication", "resolution"]) assert.deepEqual(publicGlobal({ captcha_blocked: true, pause_reason: reason }), {
|
||||
captcha_blocked: true, pause_reason: reason,
|
||||
});
|
||||
});
|
||||
|
||||
test("the download form receives configured bounds and a safe initial mode with safe cache metadata", async () => {
|
||||
const controller = createQueueController({ config: { outputDir: "/mnt/media/WIP", maxSeriesEpisodes: 12 },
|
||||
getDb: () => { throw new Error("must not connect"); } });
|
||||
for (const mode of ["video", "series", ["video"], "<script>"]) {
|
||||
const result = response();
|
||||
await controller.home({ query: { mode } }, result);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.data.values.mode, mode === "video" ? "video" : "series");
|
||||
assert.equal(result.data.maxSeriesEpisodes, 12);
|
||||
assert.equal(result.data.outputDir, "/mnt/media/WIP");
|
||||
assert.equal(result.data.formError, null);
|
||||
assert.equal(Object.hasOwn(result.data.values, "token"), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("validation errors preserve bounded non-secret form fields and clear credentials", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
const controller = createQueueController({ config, getDb: () => { throw new Error("must not connect"); } });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: {
|
||||
mode: "series", id: "42", episode_from: "4", episode_to: "1", language: "gerdub",
|
||||
name: "Series fixture-secret", token: "fixture-secret", private_field: "hidden-field",
|
||||
} }, result);
|
||||
assert.equal(result.statusCode, 400);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.values, { mode: "series", id: "42", episode_from: "4", episode_to: "1",
|
||||
language: "gerdub", season: "1", name: "Series [redacted]", url: "" });
|
||||
assert.match(result.data.formError, /Last episode/);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /fixture-secret|hidden-field|"token"/);
|
||||
});
|
||||
|
||||
test("successful submissions report the actual inserted count in their queue redirect", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
let inserted;
|
||||
const controller = createQueueController({ config, getDb: async () => ({ collection: () => ({
|
||||
bulkWrite: async operations => { inserted = operations; return { isOk: () => true, insertedCount: operations.length }; },
|
||||
}) }) });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: { mode: "series", id: "42", episode_from: "3", episode_to: "5",
|
||||
language: "engsub", name: "Series", token: "credential" } }, result);
|
||||
assert.equal(inserted.length, 3);
|
||||
assert.equal(result.location, "/status?state=queued&added=3");
|
||||
});
|
||||
|
||||
test("SSR notices accept only bounded numeric added counts without reflecting arbitrary text", async () => {
|
||||
const { db } = databaseFixture();
|
||||
const controller = createQueueController({ config: { maxSeriesEpisodes: 500 }, getDb: async () => db });
|
||||
for (const added of ["3", "0", "501", "<script>", ["1"], undefined]) {
|
||||
const result = response();
|
||||
await controller.status({ query: { added } }, result, error => { throw error; });
|
||||
assert.equal(result.data.added, added === "3" ? 3 : 0);
|
||||
assert.equal(result.data.activePage, "queue");
|
||||
assert.equal(result.data.title, "Queue");
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /<script>/);
|
||||
}
|
||||
});
|
||||
|
||||
test("database failures propagate to the shared generic error handler without raw error JSON", async () => {
|
||||
const expected = new Error("private connection details");
|
||||
const controller = createQueueController({ getDb: async () => { throw expected; } });
|
||||
for (const method of ["status", "statusData", "statusSummary"]) {
|
||||
const result = response();
|
||||
let caught;
|
||||
await controller[method]({}, result, error => { caught = error; });
|
||||
assert.equal(caught, expected);
|
||||
assert.equal(result.data, undefined);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,329 @@
|
||||
"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 ejs = require("ejs");
|
||||
const { createQueueController } = require("../controllers/queueController");
|
||||
const { createSessionTokenService, CACHE_ID, STATUS_PROJECTION } = require("../lib/sessionToken");
|
||||
|
||||
const CHECKED = new Date("2026-10-23T12:00:00.000Z");
|
||||
const PRIVATE_TOKEN = "PRIVATE_CONTROLLER_TOKEN==";
|
||||
const COOKIE = `fixture_cookie=${PRIVATE_TOKEN}`;
|
||||
|
||||
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; },
|
||||
};
|
||||
}
|
||||
|
||||
function requestBody(changes = {}) {
|
||||
return {
|
||||
mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engsub",
|
||||
season: "2", name: "A series title", token: PRIVATE_TOKEN, ...changes,
|
||||
};
|
||||
}
|
||||
|
||||
function cachedToken(changes = {}) {
|
||||
return {
|
||||
_id: CACHE_ID, cookie: COOKIE, cookie_name: "fixture_cookie", state: "ready", revision: "PRIVATE_REVISION",
|
||||
saved_at: new Date("2026-01-01T12:00:00Z"), validated_at: new Date("2026-01-01T12:00:00Z"),
|
||||
PRIVATE_FIELD: "PRIVATE_METADATA", ...changes,
|
||||
};
|
||||
}
|
||||
|
||||
function memoryDatabase({ initial = null, queueError, metadataError } = {}) {
|
||||
let cache = initial ? structuredClone(initial) : null;
|
||||
const queue = [];
|
||||
const reads = [];
|
||||
const events = [];
|
||||
const db = { collection(name) {
|
||||
if (name === "settings") return {
|
||||
async findOne(filter, options) {
|
||||
events.push("settings.read"); reads.push({ filter, options });
|
||||
if (metadataError) throw metadataError;
|
||||
if (!cache) return null;
|
||||
return Object.fromEntries(Object.entries(cache).filter(([key]) => key === "_id" || options.projection[key] === 1));
|
||||
},
|
||||
async updateOne(filter, update, options = {}) {
|
||||
events.push("settings.write");
|
||||
const matches = cache && (Object.hasOwn(filter.revision, "$eq")
|
||||
? cache.revision === filter.revision.$eq : !Object.hasOwn(cache, "revision"));
|
||||
if ((cache && !matches) || (!cache && !options.upsert)) return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
||||
const inserted = !cache;
|
||||
cache ||= { _id: CACHE_ID };
|
||||
Object.assign(cache, structuredClone(update.$set || {}));
|
||||
for (const key of Object.keys(update.$unset || {})) delete cache[key];
|
||||
return { acknowledged: true, matchedCount: inserted ? 0 : 1, upsertedCount: inserted ? 1 : 0 };
|
||||
},
|
||||
};
|
||||
assert.equal(name, "queue");
|
||||
return {
|
||||
async insertOne(document) {
|
||||
events.push("queue.insertOne");
|
||||
if (queueError) throw queueError;
|
||||
queue.push(structuredClone(document));
|
||||
return { acknowledged: true, insertedId: "fixture-job" };
|
||||
},
|
||||
async bulkWrite(operations) {
|
||||
events.push("queue.bulkWrite");
|
||||
if (queueError) throw queueError;
|
||||
queue.push(...operations.map(operation => structuredClone(operation.insertOne.document)));
|
||||
return { ok: 1, insertedCount: operations.length, isOk: () => true };
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, queue, reads, events, cache: () => structuredClone(cache) };
|
||||
}
|
||||
|
||||
async function integratedFixture(t, { state = "valid", probeError, ...databaseOptions } = {}) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-token-controller-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
const settings = { outputDir, tokenPrefix: "fixture_cookie=", maxSeriesEpisodes: 500 };
|
||||
const store = memoryDatabase(databaseOptions);
|
||||
const probes = [];
|
||||
let connections = 0;
|
||||
const connect = async () => { connections += 1; return store.db; };
|
||||
const sessionTokens = createSessionTokenService({
|
||||
getDb: connect, settings, now: () => CHECKED,
|
||||
probe: async (cookie, options) => {
|
||||
probes.push({ cookie, options }); store.events.push("probe");
|
||||
if (probeError) throw probeError;
|
||||
return { state };
|
||||
},
|
||||
});
|
||||
const controller = createQueueController({
|
||||
getDb: connect, config: settings, now: () => CHECKED, sessionTokens,
|
||||
});
|
||||
return { store, probes, controller, settings, sessionTokens, connections: () => connections };
|
||||
}
|
||||
|
||||
test("controller plans a series then verifies its first source before caching and inserting the verified cookie", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: requestBody() }, result);
|
||||
assert.equal(result.location, "/status?state=queued&added=2");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(fixture.probes, [{ cookie: COOKIE, options: { url: "https://proxer.me/watch/42/9/engsub" } }]);
|
||||
assert.deepEqual(fixture.store.queue.map(job => job.filename), ["A series titleS002E009_engsub", "A series titleS002E010_engsub"]);
|
||||
assert.ok(fixture.store.queue.every(job => job.token === COOKIE && job.created_at.toISOString() === CHECKED.toISOString()));
|
||||
assert.equal(fixture.store.cache().cookie, COOKIE);
|
||||
assert.ok(fixture.store.events.indexOf("probe") < fixture.store.events.indexOf("settings.write"));
|
||||
assert.ok(fixture.store.events.indexOf("probe") < fixture.store.events.indexOf("queue.bulkWrite"));
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN|fixture_cookie=/);
|
||||
});
|
||||
|
||||
test("a blank-token single download revalidates the cached cookie and inserts the canonical source", async t => {
|
||||
const fixture = await integratedFixture(t, { initial: cachedToken() });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: {
|
||||
mode: "video", url: "https://www.proxer.me:443/watch/42/9/engsub/#player", name: "Single episode", token: "",
|
||||
} }, result);
|
||||
assert.equal(result.location, "/status?state=queued&added=1");
|
||||
assert.deepEqual(fixture.probes, [{ cookie: COOKIE, options: { url: "https://proxer.me/watch/42/9/engsub" } }]);
|
||||
assert.deepEqual(fixture.store.queue, [{
|
||||
url: "https://proxer.me/watch/42/9/engsub", filename: "Single episode", created_at: CHECKED, token: COOKIE,
|
||||
}]);
|
||||
assert.ok(fixture.store.events.indexOf("probe") < fixture.store.events.indexOf("queue.insertOne"));
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN|PRIVATE_REVISION/);
|
||||
});
|
||||
|
||||
test("the controller uses the session service's verified cookie rather than rebuilding it from submitted text", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
const calls = [];
|
||||
const controller = createQueueController({
|
||||
config: fixture.settings, getDb: async () => fixture.store.db,
|
||||
sessionTokens: {
|
||||
readStatus: async () => ({ available: true, state: "saved" }),
|
||||
resolveForEnqueue: async (...args) => { calls.push(args); return { cookie: "fixture_cookie=VERIFIED_SERVICE_VALUE" }; },
|
||||
},
|
||||
});
|
||||
const result = response();
|
||||
await controller.enqueue({ body: requestBody({ token: "UNVERIFIED_SUBMITTED_VALUE" }) }, result);
|
||||
assert.deepEqual(calls, [["UNVERIFIED_SUBMITTED_VALUE", { url: "https://proxer.me/watch/42/9/engsub" }]]);
|
||||
assert.ok(fixture.store.queue.every(job => job.token === "fixture_cookie=VERIFIED_SERVICE_VALUE"));
|
||||
assert.equal(result.location, "/status?state=queued&added=2");
|
||||
});
|
||||
|
||||
test("GET download renders only token metadata, leaves the password input empty, and disables caching", async t => {
|
||||
const fixture = await integratedFixture(t, { initial: cachedToken() });
|
||||
const result = response();
|
||||
await fixture.controller.home({ query: { mode: "series", token: PRIVATE_TOKEN } }, result);
|
||||
assert.equal(result.statusCode, 200);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.tokenStatus, {
|
||||
available: true, state: "saved", lastValidatedAt: "2026-01-01T12:00:00.000Z", savedAt: "2026-01-01T12:00:00.000Z",
|
||||
});
|
||||
assert.equal(result.data.values.season, "1");
|
||||
assert.equal(result.data.values.token, undefined);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
assert.deepEqual(fixture.store.reads[0].options.projection, STATUS_PROJECTION);
|
||||
const html = await ejs.renderFile(path.resolve(__dirname, "../views/index.ejs"), result.data);
|
||||
assert.doesNotMatch(JSON.stringify(result.data) + html, /PRIVATE_CONTROLLER_TOKEN|PRIVATE_REVISION|PRIVATE_METADATA/);
|
||||
const input = html.match(/<input\b[^>]*\bid="download-token"[^>]*>/)?.[0];
|
||||
assert.ok(input);
|
||||
assert.doesNotMatch(input, /\bvalue\s*=/i);
|
||||
assert.match(html, /Token saved/);
|
||||
});
|
||||
|
||||
test("token rejection, missing credentials, verification, and network errors render safe warnings without queue writes", async t => {
|
||||
const cases = [
|
||||
{ state: "invalid", status: 400, message: /rejected/i },
|
||||
{ state: "verification", status: 409, message: /verification/i },
|
||||
{ state: "unavailable", status: 503, message: /could not reach|timed out/i },
|
||||
{ state: "source", status: 409, message: /unavailable/i },
|
||||
{ state: "unverifiable", status: 409, message: /could not be resolved/i },
|
||||
{ state: "valid", token: "", status: 400, message: /No saved token/i },
|
||||
{ state: "valid", probeError: new Error(`PRIVATE_UPSTREAM ${COOKIE}`), status: 503, message: /could not reach|timed out/i },
|
||||
];
|
||||
for (const scenario of cases) {
|
||||
const fixture = await integratedFixture(t, scenario);
|
||||
const body = requestBody({ token: scenario.token ?? PRIVATE_TOKEN, season: "12", language: "gerdub", name: "Retained title" });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body }, result);
|
||||
assert.equal(result.statusCode, scenario.status, scenario.state);
|
||||
assert.equal(result.template, "index");
|
||||
assert.match(result.data.formError, scenario.message);
|
||||
assert.equal(result.data.values.id, "42");
|
||||
assert.equal(result.data.values.name, "Retained title");
|
||||
assert.equal(result.data.values.season, "12");
|
||||
assert.equal(result.data.values.language, "gerdub");
|
||||
assert.equal(result.data.values.episode_from, "9");
|
||||
assert.equal(result.data.values.episode_to, "10");
|
||||
assert.equal(result.data.values.token, undefined);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.deepEqual(fixture.store.queue, []);
|
||||
assert.ok(fixture.store.events.every(event => !event.startsWith("queue.")));
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN|PRIVATE_UPSTREAM|fixture_cookie=/);
|
||||
if (scenario.token === "") assert.equal(fixture.probes.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("a submitted token accidentally pasted into another field is removed from the retry form", async t => {
|
||||
const fixture = await integratedFixture(t, { state: "verification" });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: requestBody({ name: `A title ${PRIVATE_TOKEN}`, season: "3" }) }, result);
|
||||
assert.equal(result.statusCode, 409);
|
||||
assert.equal(result.data.values.name, "A title [redacted]");
|
||||
assert.equal(result.data.values.season, "3");
|
||||
const html = await ejs.renderFile(path.resolve(__dirname, "../views/index.ejs"), result.data);
|
||||
assert.doesNotMatch(html + JSON.stringify(result.data), /PRIVATE_CONTROLLER_TOKEN/);
|
||||
assert.match(html, /Download not added/);
|
||||
assert.equal(result.location, undefined);
|
||||
});
|
||||
|
||||
test("invalid sources and malformed season values fail before token checks or database access", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
for (const body of [
|
||||
requestBody({ season: "not-a-season" }),
|
||||
requestBody({ season: { $ne: "1" } }),
|
||||
{ mode: "video", url: `https://evil.invalid/watch/42/9/engsub?token=${PRIVATE_TOKEN}`, token: PRIVATE_TOKEN },
|
||||
{ mode: "video", url: "https://proxer.me/watch/42/9/engsub?token=private-source-query", token: PRIVATE_TOKEN },
|
||||
]) {
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body }, result);
|
||||
assert.equal(result.statusCode, 400);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN/);
|
||||
}
|
||||
assert.equal(fixture.connections(), 0);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
assert.equal(fixture.store.queue.length, 0);
|
||||
});
|
||||
|
||||
test("a queue database failure after successful token verification returns a safe failure without claiming success", async t => {
|
||||
for (const mode of ["series", "video"]) {
|
||||
const fixture = await integratedFixture(t, { queueError: new Error(`PRIVATE_DATABASE ${COOKIE} https://private.invalid/?signed=secret`) });
|
||||
const body = mode === "series" ? requestBody() : {
|
||||
mode: "video", url: "https://proxer.me/watch/42/9/engsub", name: "Single episode", token: PRIVATE_TOKEN,
|
||||
};
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body }, result);
|
||||
assert.equal(fixture.probes.length, 1);
|
||||
assert.equal(result.statusCode, 500);
|
||||
assert.equal(result.template, "error");
|
||||
assert.equal(result.data.details, null);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.deepEqual(fixture.store.queue, []);
|
||||
assert.match(result.data.message, /submission could not be confirmed/i);
|
||||
assert.match(result.data.message, /check the queue before retrying/i);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_DATABASE|PRIVATE_CONTROLLER_TOKEN|private.invalid|signed=secret/);
|
||||
}
|
||||
});
|
||||
|
||||
test("uncertain insertion acknowledgements or partial batch counts never produce an added-to-queue redirect", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
const singleResults = [undefined, null, {}, { acknowledged: false }, { acknowledged: "true" }];
|
||||
const batchResults = [undefined, null, {}, { ok: 1, insertedCount: 2 },
|
||||
{ isOk: () => false, insertedCount: 2 },
|
||||
{ isOk: () => true, insertedCount: 0 }, { isOk: () => true, insertedCount: 1 },
|
||||
{ isOk: () => true, insertedCount: 3 }, { isOk: () => true, insertedCount: "2" }];
|
||||
for (const [mode, outcomes] of [["video", singleResults], ["series", batchResults]]) {
|
||||
for (const outcome of outcomes) {
|
||||
let attempted = 0;
|
||||
const controller = createQueueController({
|
||||
config: fixture.settings,
|
||||
sessionTokens: { resolveForEnqueue: async () => ({ cookie: COOKIE }) },
|
||||
getDb: async () => ({ collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return {
|
||||
async insertOne() { attempted += 1; return outcome; },
|
||||
async bulkWrite() { attempted += 1; return outcome; },
|
||||
};
|
||||
} }),
|
||||
});
|
||||
const body = mode === "series" ? requestBody() : {
|
||||
mode: "video", url: "https://proxer.me/watch/42/9/engsub", name: "Single episode", token: PRIVATE_TOKEN,
|
||||
};
|
||||
const result = response();
|
||||
await controller.enqueue({ body }, result);
|
||||
assert.equal(attempted, 1);
|
||||
assert.equal(result.statusCode, 500, mode);
|
||||
assert.equal(result.template, "error");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.match(result.data.message, /submission could not be confirmed/i);
|
||||
assert.match(result.data.message, /check the queue before retrying/i);
|
||||
assert.equal(result.data.details, null);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a token-storage failure stops enqueue without a second metadata database request", async t => {
|
||||
const fixture = await integratedFixture(t, { metadataError: new Error(`PRIVATE_STORAGE_FAILURE ${COOKIE}`) });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: requestBody() }, result);
|
||||
assert.equal(result.statusCode, 503);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.equal(fixture.store.reads.length, 1);
|
||||
assert.equal(fixture.connections(), 1);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
assert.deepEqual(fixture.store.queue, []);
|
||||
assert.deepEqual(result.data.tokenStatus, { available: false, state: "unavailable" });
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_STORAGE_FAILURE|PRIVATE_CONTROLLER_TOKEN/);
|
||||
});
|
||||
|
||||
test("an unavailable metadata read still renders the form without exposing database errors or cookies", async t => {
|
||||
const fixture = await integratedFixture(t, { initial: cachedToken(), metadataError: new Error(`PRIVATE_METADATA_FAILURE ${COOKIE}`) });
|
||||
const result = response();
|
||||
await fixture.controller.home({ query: { mode: "video" } }, result);
|
||||
assert.equal(result.statusCode, 200);
|
||||
assert.equal(result.template, "index");
|
||||
assert.deepEqual(result.data.tokenStatus, { available: false, state: "unavailable" });
|
||||
assert.equal(result.data.values.mode, "video");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_METADATA_FAILURE|PRIVATE_CONTROLLER_TOKEN/);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
});
|
||||
+105
-56
@@ -9,7 +9,19 @@ const {
|
||||
ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob, MAX_LOG_BYTES,
|
||||
} = require("../lib/jobValidation");
|
||||
const { createQueueController } = require("../controllers/queueController");
|
||||
const { createQueueController: createRealQueueController } = require("../controllers/queueController");
|
||||
// These tests isolate the existing form/page contracts. Dedicated activity and
|
||||
// token-controller suites exercise the added services, without live HTTP calls.
|
||||
function createQueueController(options = {}) {
|
||||
return createRealQueueController({
|
||||
...options,
|
||||
readActivity: options.readActivity || (async () => ({ workers: [], unassigned: [], available: true, truncated: false, workersTruncated: false })),
|
||||
sessionTokens: options.sessionTokens || {
|
||||
readStatus: async () => ({ available: false, state: "missing", lastValidatedAt: null, savedAt: null }),
|
||||
resolveForEnqueue: async value => ({ cookie: require("../lib/jobValidation").cookieToken(value, options.config?.tokenPrefix || "fixture=") }),
|
||||
},
|
||||
});
|
||||
}
|
||||
const fixtures = require("./fixtures/legacy-contracts.json");
|
||||
|
||||
const repository = path.resolve(__dirname, "..");
|
||||
@@ -32,6 +44,19 @@ function response() {
|
||||
};
|
||||
}
|
||||
|
||||
function paginatedCursor(records) {
|
||||
let offset = 0, pageSize;
|
||||
return {
|
||||
sort() { return this; },
|
||||
skip(value) { offset = value; return this; },
|
||||
limit(value) { pageSize = value; return this; },
|
||||
async toArray() {
|
||||
assert.ok([10, 25, 50].includes(pageSize), "status records must be bounded before retrieval");
|
||||
return records.slice(offset, offset + pageSize);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("legacy web naming fixtures stay compatible", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
for (const fixture of fixtures.namingCases.filter(entry => entry.entrypoint.startsWith("web-"))) {
|
||||
@@ -132,6 +157,10 @@ test("invalid submissions do not connect or insert, and failure responses never
|
||||
await controller.enqueue({ body: { mode: "video", url: "https://evil.test/file", token: "fixture-secret" } }, bad);
|
||||
assert.equal(bad.statusCode, 400);
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(bad.template, "index");
|
||||
assert.equal(bad.data.values.mode, "video");
|
||||
assert.equal(Object.hasOwn(bad.data.values, "token"), false);
|
||||
assert.ok(bad.data.formError);
|
||||
assert.equal(bad.data.details, null);
|
||||
assert.doesNotMatch(JSON.stringify(bad.data), /fixture-secret|Error:|stack/);
|
||||
|
||||
@@ -142,16 +171,16 @@ test("invalid submissions do not connect or insert, and failure responses never
|
||||
assert.doesNotMatch(JSON.stringify(unavailable.data), /database fixture secret|fixture-secret|Error:/);
|
||||
});
|
||||
|
||||
test("enqueue inserts all validated episode jobs in one batch and redirects to existing status URL", async t => {
|
||||
test("enqueue inserts all validated episode jobs in one batch and redirects to the queued view with its count", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
let inserted;
|
||||
const controller = createQueueController({ config, getDb: async () => ({ collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return { bulkWrite: async operations => { inserted = operations; } };
|
||||
return { bulkWrite: async operations => { inserted = operations; return { isOk: () => true, insertedCount: operations.length }; } };
|
||||
} }) });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: { mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engdub", name: "Series", token: "fixture" } }, result);
|
||||
assert.equal(result.location, "/status");
|
||||
assert.equal(result.location, "/status?state=queued&added=2");
|
||||
assert.deepEqual(inserted.map(operation => operation.insertOne.document.filename), ["SeriesE09_engdub", "SeriesE10_engdub"]);
|
||||
});
|
||||
|
||||
@@ -189,21 +218,21 @@ test("status endpoints use projections, exclude secret settings and refuse symli
|
||||
assert.deepEqual(options.projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
return { captcha_blocked: true, secret: "settings-secret" };
|
||||
} };
|
||||
return { find(filter, options) {
|
||||
return {
|
||||
countDocuments: async filter => name === "queue" && filter.processing === true ? 1 : 0,
|
||||
find(filter, options) {
|
||||
assert.equal(options.projection.token, 1, "tokens are internal inputs to exact-value log redaction");
|
||||
return { sort() { return this; }, async toArray() {
|
||||
return name === "queue" && filter.processing === true
|
||||
return paginatedCursor(name === "queue" && filter.processing === true
|
||||
? [{ _id: "active", filename: "link", url: sourceUrl, token: "fixture-secret", private_field: true }]
|
||||
: [];
|
||||
} };
|
||||
: []);
|
||||
} };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
const result = response();
|
||||
await controller.statusData({}, result, error => { throw error; });
|
||||
await controller.statusData({ query: { state: "processing" } }, result, error => { throw error; });
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.global, { captcha_blocked: true, pause_reason: null });
|
||||
assert.equal(result.data.processing[0].fileSize, null);
|
||||
assert.equal(result.data.items[0].fileSize, null);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /fixture-secret|settings-secret|private_field/);
|
||||
});
|
||||
|
||||
@@ -220,31 +249,32 @@ test("projected queued and history logs redact known cookies without exposing th
|
||||
}));
|
||||
const database = { collection(name) {
|
||||
if (name === "settings") return { findOne: async () => ({ captcha_blocked: false }) };
|
||||
return { find(filter, { projection }) {
|
||||
return { countDocuments: async () => 1, find(filter, { projection }) {
|
||||
const group = name === "queue" ? (filter.processing === true ? "processing" : "queued") : name;
|
||||
assert.equal(projection.token, 1);
|
||||
// Apply the real inclusion projection so this test cannot accidentally
|
||||
// redact a token which MongoDB would have omitted from the response.
|
||||
const projected = Object.fromEntries(Object.entries(records[group]).filter(([key]) => projection[key] === 1));
|
||||
return { sort() { return this; }, async toArray() { return [projected]; } };
|
||||
return paginatedCursor([projected]);
|
||||
} };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
const jsonResponse = response();
|
||||
await controller.statusData({}, jsonResponse, error => { throw error; });
|
||||
const viewResponse = response();
|
||||
await controller.status({}, viewResponse, error => { throw error; });
|
||||
for (const snapshot of [jsonResponse.data, viewResponse.data]) {
|
||||
for (const group of groups) {
|
||||
const job = snapshot[group][0];
|
||||
for (const method of ["statusData", "status"]) {
|
||||
const result = response();
|
||||
await controller[method]({ query: { state: group } }, result, error => { throw error; });
|
||||
const snapshot = result.data;
|
||||
assert.equal(snapshot.filters.state, group);
|
||||
assert.equal(snapshot.items.length, 1);
|
||||
const job = snapshot.items[0];
|
||||
assert.equal(Object.hasOwn(job, "token"), false);
|
||||
assert.equal(Object.hasOwn(job, "private_field"), false);
|
||||
assert.match(job.output_log, /\[redacted\]/);
|
||||
assert.ok(!job.output_log.includes(`${group}-exact-credential==`));
|
||||
assert.ok(!job.output_log.includes("custom_cookie="));
|
||||
}
|
||||
assert.doesNotMatch(JSON.stringify(snapshot), /exact-credential|must never reach the view/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("public global status exposes only allowlisted pause reasons and resolution job errors", async t => {
|
||||
@@ -255,10 +285,10 @@ test("public global status exposes only allowlisted pause reasons and resolution
|
||||
assert.deepEqual(projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
return { captcha_blocked: true, pause_reason: reason, token: "private-settings-token" };
|
||||
} };
|
||||
return { find() { return { sort() { return this; }, async toArray() { return []; } }; } };
|
||||
return { countDocuments: async () => 0, find() { return paginatedCursor([]); } };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
for (const method of ["statusData", "status"]) {
|
||||
for (const method of ["statusData", "status", "statusSummary"]) {
|
||||
const result = response();
|
||||
await controller[method]({}, result, error => { throw error; });
|
||||
assert.deepEqual(result.data.global, {
|
||||
@@ -287,7 +317,7 @@ test("resume clears both the existing global pause flag and its reason before re
|
||||
assert.equal(result.location, "/status");
|
||||
});
|
||||
|
||||
test("verification banner distinguishes resolution failures without claiming a confirmed CAPTCHA", async () => {
|
||||
test("verification banner and shared status updates distinguish resolution failures without claiming a confirmed CAPTCHA", async () => {
|
||||
const header = path.join(repository, "views/partials/header.ejs");
|
||||
const rendered = await ejs.renderFile(header, { global: { captcha_blocked: true, pause_reason: "resolution" } });
|
||||
const message = rendered.match(/<span id="captcha-message">([\s\S]*?)<\/span>/)[1];
|
||||
@@ -296,55 +326,74 @@ test("verification banner distinguishes resolution failures without claiming a c
|
||||
assert.match(rendered, /Resume after verification/);
|
||||
assert.doesNotMatch(message, /CAPTCHA triggered|CAPTCHA confirmed/);
|
||||
|
||||
const script = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)][0][1];
|
||||
const elements = { "captcha-alert": { style: {} }, "captcha-message": { textContent: "" } };
|
||||
let globalState = { captcha_blocked: true, pause_reason: "resolution" };
|
||||
assert.match(rendered, /<script src="\/app\.js" defer><\/script>/);
|
||||
const script = await fs.readFile(path.join(repository, "public/app.js"), "utf8");
|
||||
const listeners = new Map();
|
||||
const classes = new Set();
|
||||
const elements = {
|
||||
"main-content": { dataset: { page: "queue" } },
|
||||
"captcha-alert": { hidden: true },
|
||||
"captcha-message": { textContent: "" },
|
||||
"global-status": {
|
||||
classList: {
|
||||
add(value) { classes.add(value); }, remove(value) { classes.delete(value); },
|
||||
toggle(value, enabled) { if (enabled) classes.add(value); else classes.delete(value); },
|
||||
},
|
||||
removeAttribute() {},
|
||||
},
|
||||
"global-status-text": { textContent: "" },
|
||||
"nav-queue-count": { textContent: "", hidden: true },
|
||||
};
|
||||
const context = {
|
||||
document: { getElementById: id => elements[id] },
|
||||
fetch: async () => ({ json: async () => ({ global: globalState }) }),
|
||||
setInterval: () => {}, console,
|
||||
document: { getElementById: id => elements[id], addEventListener: (name, handler) => listeners.set(name, handler) },
|
||||
window: { addEventListener() {} },
|
||||
fetch: async () => { throw new Error("the queue page must not perform duplicate summary polling"); },
|
||||
setTimeout: () => 0, clearTimeout() {}, console,
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(script, context);
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["captcha-alert"].style.display, "block");
|
||||
const update = global => listeners.get("proxer:status")({ detail: {
|
||||
global, counts: { queued: 2, processing: 1, done: 4, failed: 1 },
|
||||
} });
|
||||
update({ captcha_blocked: true, pause_reason: "resolution" });
|
||||
assert.equal(elements["captcha-alert"].hidden, false);
|
||||
assert.match(elements["captcha-message"].textContent, /unavailable video/);
|
||||
globalState = { captcha_blocked: true, pause_reason: "authentication" };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["global-status-text"].textContent, "Downloads paused");
|
||||
assert.ok(classes.has("is-paused"));
|
||||
assert.equal(elements["nav-queue-count"].textContent, "3");
|
||||
update({ captcha_blocked: true, pause_reason: "authentication" });
|
||||
assert.match(elements["captcha-message"].textContent, /Authentication or access needs verification/);
|
||||
globalState = { captcha_blocked: true, pause_reason: "<img onerror=evil>" };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
update({ captcha_blocked: true, pause_reason: "<img onerror=evil>" });
|
||||
assert.doesNotMatch(elements["captcha-message"].textContent, /<img|evil/);
|
||||
globalState = { captcha_blocked: false, pause_reason: null };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["captcha-alert"].style.display, "none");
|
||||
listeners.get("proxer:status-error")();
|
||||
assert.equal(elements["captcha-alert"].hidden, false, "an unavailable refresh must not hide a known pause");
|
||||
assert.match(elements["global-status-text"].textContent, /Paused.*unavailable/);
|
||||
update({ captcha_blocked: false, pause_reason: null });
|
||||
assert.equal(elements["captcha-alert"].hidden, true);
|
||||
assert.equal(elements["global-status-text"].textContent, "Queue ready");
|
||||
assert.ok(classes.has("is-ready"));
|
||||
assert.equal(classes.has("is-stale"), false);
|
||||
});
|
||||
|
||||
test("server-rendered and refreshed status escape HTML-like filenames, IDs and logs", async () => {
|
||||
test("paginated status views escape HTML-like filenames, IDs, logs and search text in every state", async () => {
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const job = { _id: `id" onmouseover="alert(2)`, filename: attack, url: attack, output_log: attack, created_at: "2026-01-01T00:00:00Z" };
|
||||
for (const state of ["queued", "processing", "done", "failed"]) {
|
||||
const rendered = await ejs.renderFile(path.join(repository, "views/status.ejs"), {
|
||||
queued: [job], processing: [job], finished: [{ ...job, finished_at: job.created_at }],
|
||||
failed: [{ ...job, failed_at: job.created_at }], global: { captcha_blocked: false },
|
||||
items: [job, { ...job, _id: "safe", filename: "A normal episode", url: sourceUrl }],
|
||||
counts: { queued: 2, processing: 2, done: 2, failed: 2 },
|
||||
pagination: { page: 1, pageSize: 25, total: 2, totalPages: 1 },
|
||||
filters: { state, q: attack }, global: { captcha_blocked: false },
|
||||
});
|
||||
assert.ok(!rendered.includes(attack));
|
||||
assert.match(rendered, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.doesNotMatch(rendered, /action="\/clear-processing"/);
|
||||
const scripts = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)];
|
||||
const statusScript = scripts.find(match => match[1].includes("function refreshStatus"))[1];
|
||||
const context = {
|
||||
document: { querySelectorAll: () => [] },
|
||||
fetch: async () => ({ json: async () => ({ queued: [job], processing: [job], done: [job], failed: [job] }) }),
|
||||
setInterval: () => {}, console,
|
||||
queuedList: {}, processingList: {}, doneList: {}, failedList: {},
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(statusScript, context);
|
||||
await vm.runInContext("refreshStatus()", context);
|
||||
for (const key of ["queuedList", "processingList", "doneList", "failedList"]) {
|
||||
assert.ok(!context[key].innerHTML.includes(attack));
|
||||
assert.match(context[key].innerHTML, /<img/);
|
||||
assert.doesNotMatch(context[key].innerHTML, /data-id="[^\n]*" onmouseover=/);
|
||||
assert.doesNotMatch(rendered, /data-job-id="id" onmouseover=/);
|
||||
assert.match(rendered, /data-job-id="id" onmouseover="alert\(2\)"/);
|
||||
assert.match(rendered, /Source unavailable/);
|
||||
assert.match(rendered, /Series 42 · Episode 2 · English sub/);
|
||||
assert.match(rendered, /href="https:\/\/proxer\.me\/watch\/42\/2\/engsub" target="_blank" rel="noopener noreferrer"/);
|
||||
assert.match(rendered, /<script src="\/status\.js" defer><\/script>/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+44
-7
@@ -7,6 +7,7 @@ const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { executeJob, processClaimedJob, claimNextJob, RESULT_PREFIX } = require('../queue_worker');
|
||||
const { LOG_LIMIT } = require('../lib/logging');
|
||||
const { createWorkerIdentity } = require('../lib/workerIdentity');
|
||||
|
||||
const now = new Date('2026-01-01T12:00:00.000Z');
|
||||
const successfulResult = `${RESULT_PREFIX}${JSON.stringify({ version: 1, status: 'completed' })}\n`;
|
||||
@@ -14,6 +15,10 @@ const makeJob = (changes = {}) => ({
|
||||
_id: 'fixture-job', filename: 'Fixture Episode', url: 'https://proxer.me/watch/42/1/engsub',
|
||||
token: 'fixture_cookie=fixture-secret==', created_at: now, processing: true, ...changes,
|
||||
});
|
||||
const workerIdentity = createWorkerIdentity({
|
||||
env: { name: 'proxer-worker-7' }, pid: 12345, host: 'download-host', now: () => now,
|
||||
uuid: () => '7b3c9e3a-8b0b-41c6-988c-8e9e01dbbf4a',
|
||||
});
|
||||
|
||||
async function temporarySettings(t) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-worker-'));
|
||||
@@ -267,7 +272,7 @@ test('the final pause gate releases a never-started claim without history or del
|
||||
assert.equal(result.errorCategory, 'paused');
|
||||
assert.equal(spawns, 0);
|
||||
assert.deepEqual(operations, [{ collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: 'fixture-job', processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
args: [{ _id: 'fixture-job', processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
||||
}]);
|
||||
});
|
||||
|
||||
@@ -449,7 +454,7 @@ test('authentication and resolution pause the pool before history and preserve t
|
||||
assert.doesNotMatch(operations[1].args[0].output_log, /fixture-secret/);
|
||||
assert.equal(operations[1].args[0].token, undefined);
|
||||
assert.deepEqual(operations[2].args, [
|
||||
{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } },
|
||||
{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } },
|
||||
]);
|
||||
assert.equal(job.token, 'fixture_cookie=fixture-secret==');
|
||||
}
|
||||
@@ -496,6 +501,7 @@ test('unacknowledged attention writes halt without consuming the request', async
|
||||
|
||||
function claimDatabase({ pauseReads = [false, false], readFailureAt = -1, afterClaim = () => {} } = {}) {
|
||||
const operations = [];
|
||||
const claims = [];
|
||||
let readCount = 0;
|
||||
const job = makeJob();
|
||||
const db = { collection(name) {
|
||||
@@ -507,18 +513,49 @@ function claimDatabase({ pauseReads = [false, false], readFailureAt = -1, afterC
|
||||
} };
|
||||
assert.equal(name, 'queue');
|
||||
return {
|
||||
findOneAndUpdate: async () => { operations.push('queue.claim'); afterClaim(); return job; },
|
||||
findOneAndUpdate: async (...args) => { operations.push('queue.claim'); claims.push(args); afterClaim(); return job; },
|
||||
updateOne: async (filter, update) => {
|
||||
operations.push('queue.release');
|
||||
assert.deepEqual(filter, { _id: job._id, processing: true });
|
||||
assert.deepEqual(update, { $unset: { processing: '', started_at: '' } });
|
||||
assert.deepEqual(update, { $unset: { processing: '', started_at: '', worker: '' } });
|
||||
return { acknowledged: true };
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, operations, job };
|
||||
return { db, operations, job, claims };
|
||||
}
|
||||
|
||||
test('a worker identity is recorded in the atomic claim alongside its start time', async () => {
|
||||
const fixture = claimDatabase();
|
||||
await claimNextJob(fixture.db, { workerIdentity: { ...workerIdentity, token: 'must-not-be-copied' }, now: () => now });
|
||||
assert.deepEqual(fixture.claims, [[
|
||||
{ processing: { $ne: true } },
|
||||
{ $set: { processing: true, started_at: now, worker: workerIdentity } },
|
||||
{ sort: { created_at: 1 }, returnDocument: 'after' },
|
||||
]]);
|
||||
});
|
||||
|
||||
test('a claim without valid identity cannot retain stale worker telemetry from an earlier attempt', async () => {
|
||||
const fixture = claimDatabase();
|
||||
await claimNextJob(fixture.db, { workerIdentity: { ...workerIdentity, pid: '12345' }, now: () => now });
|
||||
assert.deepEqual(fixture.claims[0][1], {
|
||||
$set: { processing: true, started_at: now }, $unset: { worker: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('history retains only validated worker metadata without changing claim transitions', async () => {
|
||||
for (const ok of [true, false]) {
|
||||
const { db, operations } = recordingDatabase();
|
||||
await processClaimedJob(makeJob({ worker: { ...workerIdentity, token: 'private-worker-data' } }), {
|
||||
db, execute: async () => ({ ok, exitCode: ok ? 0 : 1, errorCategory: 'resolution', output: 'fixture' }),
|
||||
});
|
||||
const history = operations.find(entry => entry.method === 'insertOne').args[0];
|
||||
assert.deepEqual(history.worker, workerIdentity);
|
||||
assert.doesNotMatch(JSON.stringify(history), /private-worker-data/);
|
||||
if (!ok) assert.deepEqual(operations.at(-1).args[1], { $unset: { processing: '', started_at: '', worker: '' } });
|
||||
}
|
||||
});
|
||||
|
||||
test('a paused pool does not claim a new job', async () => {
|
||||
const fixture = claimDatabase({ pauseReads: [true] });
|
||||
assert.equal(await claimNextJob(fixture.db), null);
|
||||
@@ -567,7 +604,7 @@ test('interrupted jobs release only their own claim without creating history or
|
||||
assert.equal(result.errorCategory, 'interrupted');
|
||||
assert.deepEqual(operations, [{
|
||||
collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
||||
}]);
|
||||
});
|
||||
|
||||
@@ -580,7 +617,7 @@ test('infrastructure failures preserve the request, release its claim, and rejec
|
||||
}) }), /infrastructure is unavailable.*remains queued/);
|
||||
assert.deepEqual(operations, [{
|
||||
collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
||||
}]);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { startWorkerPage, validWorkerName, boundedLog, MAX_VISIBLE_LOG_BYTES } = require('../public/workers');
|
||||
|
||||
class Element {
|
||||
constructor(tag = 'div') {
|
||||
this.tagName = tag;
|
||||
this.className = '';
|
||||
this.children = [];
|
||||
this.dataset = {};
|
||||
this.attributes = {};
|
||||
this.listeners = {};
|
||||
this.textContent = '';
|
||||
this.value = '';
|
||||
this.hidden = this.disabled = false;
|
||||
this.scrollTop = this.scrollHeight = this.clientHeight = 0;
|
||||
this.classList = { toggle: (name, enabled) => {
|
||||
const names = new Set(this.className.split(' ').filter(Boolean));
|
||||
if (enabled) names.add(name); else names.delete(name);
|
||||
this.className = [...names].join(' ');
|
||||
} };
|
||||
}
|
||||
set innerHTML(_value) { assert.fail('Worker data must never be written as HTML.'); }
|
||||
addEventListener(type, listener) { (this.listeners[type] ||= []).push(listener); }
|
||||
async dispatch(type, values = {}) {
|
||||
for (const listener of this.listeners[type] || []) await listener({ preventDefault() {}, ...values });
|
||||
}
|
||||
setAttribute(name, value) { this.attributes[name] = String(value); }
|
||||
setCustomValidity(value) { this.validationMessage = value; }
|
||||
append(...nodes) {
|
||||
for (const node of nodes) { node.parentElement = this; this.children.push(node); }
|
||||
}
|
||||
remove() {
|
||||
if (this.parentElement) this.parentElement.children = this.parentElement.children.filter(node => node !== this);
|
||||
this.parentElement = null;
|
||||
}
|
||||
querySelectorAll(selector) {
|
||||
const matches = node => selector.startsWith('.')
|
||||
? node.className.split(' ').includes(selector.slice(1))
|
||||
: Object.hasOwn(node.dataset, selector.slice(6, -1).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()));
|
||||
return this.children.flatMap(node => [...(matches(node) ? [node] : []), ...node.querySelectorAll(selector)]);
|
||||
}
|
||||
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
|
||||
}
|
||||
|
||||
const worker = (name = 'proxer-worker-1', pm_id = '0') => ({
|
||||
name, pm_id, pid: '122', status: 'online', cpu: '1.2%', memoryMB: '40 MB', uptime: '5m', execPath: '/fixture/queue_worker.js',
|
||||
});
|
||||
|
||||
function fixture(initial = [worker()]) {
|
||||
const nodes = new Map();
|
||||
const get = id => {
|
||||
if (!nodes.has(id)) nodes.set(id, new Element());
|
||||
return nodes.get(id);
|
||||
};
|
||||
const document = new Element();
|
||||
document.hidden = false;
|
||||
document.getElementById = get;
|
||||
document.createElement = tag => new Element(tag);
|
||||
get('follow-logs').checked = true;
|
||||
get('create-worker-form').reportValidity = () => !get('worker-name').validationMessage;
|
||||
const sockets = [];
|
||||
class BrowserSocket extends Element {
|
||||
static OPEN = 1;
|
||||
constructor(url) { super(); this.url = url; this.readyState = 0; this.sent = []; sockets.push(this); }
|
||||
send(value) { assert.equal(this.readyState, 1, 'Never send on a connecting/closed socket.'); this.sent.push(JSON.parse(value)); }
|
||||
close() { this.readyState = 3; this.closed = true; this.dispatch('close'); }
|
||||
async open() { this.readyState = 1; await this.dispatch('open'); }
|
||||
async message(payload) { await this.dispatch('message', { data: JSON.stringify(payload) }); }
|
||||
}
|
||||
const window = new Element();
|
||||
let reloads = 0;
|
||||
window.location = { protocol: 'https:', host: 'fixture.invalid', reload: () => reloads++ };
|
||||
window.confirmations = [];
|
||||
window.allowConfirm = true;
|
||||
window.confirm = message => { window.confirmations.push(message); return window.allowConfirm; };
|
||||
const requests = [];
|
||||
const timers = new Map();
|
||||
let nextTimer = 1;
|
||||
const state = { workers: initial, handler: null };
|
||||
const response = result => ({ ok: true, json: async () => result });
|
||||
const page = startWorkerPage({
|
||||
document, window, WebSocket: BrowserSocket, AbortController,
|
||||
setTimeout: (callback, delay) => { const id = nextTimer++; timers.set(id, { callback, delay }); return id; },
|
||||
clearTimeout: id => timers.delete(id),
|
||||
fetch: async (url, options) => {
|
||||
requests.push({ url, options });
|
||||
if (state.handler) return state.handler(url, options);
|
||||
return response(url === '/pm2/list-json' ? { ok: true, processes: state.workers } : { ok: true });
|
||||
},
|
||||
});
|
||||
return { page, get, state, document, window, requests, sockets, timers, response, reloads: () => reloads };
|
||||
}
|
||||
|
||||
test('worker logs enforce a 64 KiB UTF-8 bound without splitting Unicode text', () => {
|
||||
const result = boundedLog('🚀漢字'.repeat(30_000) + '\nLATEST LINE');
|
||||
assert.ok(Buffer.byteLength(result, 'utf8') <= MAX_VISIBLE_LOG_BYTES);
|
||||
assert.match(result, /^\[Earlier log output omitted\]/);
|
||||
assert.ok(result.endsWith('\nLATEST LINE'));
|
||||
assert.doesNotMatch(result, /\uFFFD/);
|
||||
assert.equal(boundedLog('short output'), 'short output');
|
||||
});
|
||||
|
||||
test('worker form name rules match managed command restrictions', () => {
|
||||
for (const name of ['worker-1', '2_worker', 'a'.repeat(64)]) assert.equal(validWorkerName(name), true);
|
||||
for (const name of ['', 'all', 'ALL', '-worker', 'a/b', 'worker name', '<img>', 'a'.repeat(65)]) {
|
||||
assert.equal(validWorkerName(name), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('worker refresh preserves row identity and selection while rendering unsafe fields only as text', async () => {
|
||||
const f = fixture([worker(), { ...worker('<img onerror=attack>', '2'), status: '<b>offline</b>' }]);
|
||||
await f.page.refreshList();
|
||||
const row = f.get('process-list').querySelectorAll('.worker-row')[0];
|
||||
const unsafe = f.get('process-list').querySelectorAll('.worker-row')[1];
|
||||
assert.equal(unsafe.querySelector('.worker-name').textContent, '<img onerror=attack>');
|
||||
assert.equal(unsafe.querySelector('[data-worker-status]').textContent, '<b>offline</b>');
|
||||
assert.equal(unsafe.disabled, true);
|
||||
await row.dispatch('click');
|
||||
assert.equal(f.sockets.length, 1);
|
||||
f.state.workers = [{ ...worker(), cpu: '5.1%', execPath: '<script>ignored</script>' }];
|
||||
await f.page.refreshList();
|
||||
assert.equal(f.get('process-list').querySelectorAll('.worker-row')[0], row);
|
||||
assert.equal(row.attributes['aria-pressed'], 'true');
|
||||
assert.equal(f.get('detail-cpu').textContent, '5.1%');
|
||||
assert.equal(f.get('detail-exec').textContent, '<script>ignored</script>');
|
||||
assert.equal(f.sockets.length, 1, 'Polling must not reconnect the selected log stream.');
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('log selection waits for connection readiness, rejects stale streams and closes on deselect', async () => {
|
||||
const f = fixture([worker(), worker('proxer-worker-2', '1')]);
|
||||
await f.page.refreshList();
|
||||
f.page.selectWorker('0:proxer-worker-1');
|
||||
const first = f.sockets[0];
|
||||
assert.equal(first.url, 'wss://fixture.invalid');
|
||||
assert.equal(first.sent.length, 0);
|
||||
await first.open();
|
||||
assert.deepEqual(first.sent, [{ type: 'logs', name: 'proxer-worker-1' }]);
|
||||
f.page.selectWorker('1:proxer-worker-2');
|
||||
assert.equal(first.closed, true);
|
||||
assert.deepEqual(first.sent.at(-1), { type: 'stop-logs' });
|
||||
await first.message({ type: 'stdout', data: 'STALE WORKER OUTPUT' });
|
||||
assert.doesNotMatch(f.get('logs').textContent, /STALE/);
|
||||
const second = f.sockets[1];
|
||||
await second.open();
|
||||
await second.message({ type: 'stdout', data: '<img onerror=attack>' });
|
||||
assert.match(f.get('logs').textContent, /<img onerror=attack>/);
|
||||
f.page.clearSelection();
|
||||
assert.deepEqual(second.sent.at(-1), { type: 'stop-logs' });
|
||||
assert.equal(second.closed, true);
|
||||
assert.equal(f.get('control-centre').hidden, true);
|
||||
assert.equal(f.get('reconnect-logs').disabled, true);
|
||||
await second.message({ type: 'stderr', data: 'LATE PACKET' });
|
||||
assert.doesNotMatch(f.get('logs').textContent, /LATE/);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('concurrent list reads coalesce and commands wait for older reads before refreshing', async () => {
|
||||
const f = fixture();
|
||||
let resolveFirst;
|
||||
const firstRead = new Promise(resolve => { resolveFirst = resolve; });
|
||||
let reads = 0;
|
||||
f.state.handler = (url, options) => {
|
||||
if (url === '/pm2/list-json') {
|
||||
reads++;
|
||||
return reads === 1 ? firstRead : f.response({ ok: true, processes: [{ ...worker(), status: 'stopped' }] });
|
||||
}
|
||||
assert.deepEqual(JSON.parse(options.body), { cmd: 'stop', name: 'proxer-worker-1' });
|
||||
return f.response({ ok: true });
|
||||
};
|
||||
const a = f.page.refreshList();
|
||||
assert.equal(f.page.refreshList(), a);
|
||||
const command = f.page.execCommand('stop', 'proxer-worker-1');
|
||||
assert.equal(await f.page.execCommand('stop', 'proxer-worker-1'), false, 'Duplicate commands must not be sent.');
|
||||
assert.equal(f.get('btn-create').disabled, true);
|
||||
assert.equal(f.get('btn-quick-add').disabled, true);
|
||||
assert.equal(f.requests.length, 1);
|
||||
resolveFirst(f.response({ ok: true, processes: [worker()] }));
|
||||
assert.equal(await command, true);
|
||||
assert.deepEqual(f.requests.map(request => request.url), ['/pm2/list-json', '/pm2/command', '/pm2/list-json']);
|
||||
assert.equal(f.get('btn-create').disabled, false);
|
||||
assert.equal(f.get('btn-quick-add').disabled, false);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('destructive worker controls honor cancellation and name validation blocks reserved names', async () => {
|
||||
const f = fixture();
|
||||
await f.page.refreshList();
|
||||
f.page.selectWorker('0:proxer-worker-1');
|
||||
f.window.allowConfirm = false;
|
||||
for (const action of ['stop', 'restart', 'delete']) await f.get(`btn-${action}`).dispatch('click');
|
||||
assert.equal(f.requests.filter(request => request.url === '/pm2/command').length, 0);
|
||||
assert.equal(f.window.confirmations.length, 3);
|
||||
assert.ok(f.window.confirmations.every(message => /interrupt/i.test(message)));
|
||||
f.get('worker-name').value = 'all';
|
||||
await f.get('create-worker-form').dispatch('submit');
|
||||
assert.match(f.get('worker-name').validationMessage, /reserved/);
|
||||
assert.equal(f.requests.filter(request => request.url === '/pm2/command').length, 0);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('named worker creation submits only managed inputs and selects the returned worker', async () => {
|
||||
const f = fixture([]);
|
||||
f.state.handler = (url, options) => {
|
||||
if (url === '/pm2/command') {
|
||||
assert.deepEqual(JSON.parse(options.body), { cmd: 'create', name: 'media-worker-3' });
|
||||
f.state.workers = [worker('media-worker-3', '3')];
|
||||
return f.response({ ok: true });
|
||||
}
|
||||
return f.response({ ok: true, processes: f.state.workers });
|
||||
};
|
||||
f.get('worker-name').value = ' media-worker-3 ';
|
||||
await f.get('create-worker-form').dispatch('submit');
|
||||
assert.equal(f.get('cc-name').textContent, 'media-worker-3');
|
||||
assert.equal(f.get('worker-name').value, '');
|
||||
assert.equal(f.get('control-centre').hidden, false);
|
||||
assert.equal(f.sockets.length, 1);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('quick add sends no client-selected name and selects the server-assigned worker', async () => {
|
||||
const f = fixture([]);
|
||||
f.get('worker-name').value = 'unfinished-custom-name';
|
||||
f.state.handler = (url, options) => {
|
||||
if (url === '/pm2/quick-add') {
|
||||
assert.equal(options.method, 'POST');
|
||||
assert.deepEqual(JSON.parse(options.body), {});
|
||||
f.state.workers = [worker('proxer-worker-14', '12')];
|
||||
return f.response({ ok: true, name: 'proxer-worker-14' });
|
||||
}
|
||||
assert.equal(url, '/pm2/list-json');
|
||||
return f.response({ ok: true, processes: f.state.workers });
|
||||
};
|
||||
await f.get('btn-quick-add').dispatch('click');
|
||||
assert.equal(f.get('cc-name').textContent, 'proxer-worker-14');
|
||||
assert.equal(f.get('control-centre').hidden, false);
|
||||
assert.equal(f.get('worker-name').value, 'unfinished-custom-name');
|
||||
assert.match(f.get('control-output').textContent, /proxer-worker-14 was created and started/);
|
||||
assert.equal(f.sockets.length, 1);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('quick add shares the command lock and refuses to invent a name from an invalid response', async () => {
|
||||
const f = fixture([]);
|
||||
let resolveCreation;
|
||||
const pending = new Promise(resolve => { resolveCreation = resolve; });
|
||||
f.state.handler = url => url === '/pm2/quick-add' ? pending : f.response({ ok: true, processes: [] });
|
||||
const creation = f.page.execCommand('quick-add');
|
||||
assert.equal(f.get('btn-quick-add').disabled, true);
|
||||
assert.equal(await f.page.execCommand('quick-add'), false);
|
||||
assert.equal(await f.page.execCommand('create', 'another-worker'), false);
|
||||
resolveCreation(f.response({ ok: true, name: '<script>bad response</script>' }));
|
||||
assert.equal(await creation, false);
|
||||
assert.equal(f.get('btn-quick-add').disabled, false);
|
||||
assert.equal(f.get('control-centre').hidden, true);
|
||||
assert.match(f.get('control-output').textContent, /name could not be confirmed/);
|
||||
assert.equal(f.requests.filter(request => request.url === '/pm2/quick-add').length, 1);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('failed refresh and uncertain commands keep their last state and show distinct feedback', async () => {
|
||||
const f = fixture();
|
||||
await f.page.refreshList();
|
||||
const row = f.get('process-list').querySelector('.worker-row');
|
||||
f.state.handler = () => { throw new Error('offline'); };
|
||||
assert.equal(await f.page.refreshList(), false);
|
||||
assert.equal(f.get('process-list').querySelector('.worker-row'), row);
|
||||
assert.match(f.get('worker-refresh-state').textContent, /last available list/);
|
||||
assert.equal(await f.page.execCommand('restart', 'proxer-worker-1'), false);
|
||||
assert.match(f.get('control-output').textContent, /Could not confirm.*Refresh the worker list/);
|
||||
assert.equal(f.get('btn-create').disabled, false);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('worker polling pauses in hidden pages and page lifecycle cleans up and recovers on browser back', async () => {
|
||||
const f = fixture();
|
||||
assert.equal(f.timers.size, 1);
|
||||
f.document.hidden = true;
|
||||
await f.document.dispatch('visibilitychange');
|
||||
assert.equal(f.timers.size, 0);
|
||||
f.document.hidden = false;
|
||||
await f.document.dispatch('visibilitychange');
|
||||
await f.page.refreshList();
|
||||
f.page.selectWorker('0:proxer-worker-1');
|
||||
await f.sockets[0].open();
|
||||
await f.window.dispatch('pagehide');
|
||||
assert.equal(f.timers.size, 0);
|
||||
assert.equal(f.sockets[0].closed, true);
|
||||
await f.window.dispatch('pageshow', { persisted: true });
|
||||
assert.equal(f.reloads(), 1);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
<%- include('partials/header', { title: 'Dashboard', activePage: 'dashboard' }) %>
|
||||
<%
|
||||
const overview = {
|
||||
queued: ['Waiting', 'Ready for a worker'], processing: ['Active', 'Claimed downloads'],
|
||||
done: ['Completed', 'Successful downloads'], failed: ['Failed attempts', 'Review attempt history']
|
||||
};
|
||||
const recentRows = typeof recent === 'object' && recent ? recent : { done: [], failed: [] };
|
||||
%>
|
||||
<div class="page-heading">
|
||||
<div><p class="eyebrow">DOWNLOAD OVERVIEW</p><h1 class="page-title">Dashboard</h1><p class="page-description">Your workers, current downloads and latest results in one place.</p></div>
|
||||
<div class="button-group"><button type="button" class="button button-secondary" id="dashboard-refresh">Refresh</button><a class="button button-primary" href="/download">New download <span aria-hidden="true">→</span></a></div>
|
||||
</div>
|
||||
<%- include('partials/active-downloads') %>
|
||||
<nav class="queue-overview dashboard-overview" aria-label="Open queue or history">
|
||||
<% Object.entries(overview).forEach(([state, info]) => { %>
|
||||
<a class="queue-stat" href="/status?state=<%= state %>"><span class="queue-stat-label"><%= info[0] %></span><strong class="queue-stat-count" data-dashboard-count="<%= state %>"><%= counts[state].toLocaleString('en') %></strong><span class="queue-stat-note"><%= info[1] %> <span aria-hidden="true">↗</span></span></a>
|
||||
<% }) %>
|
||||
</nav>
|
||||
<p class="dashboard-feedback field-hint" id="dashboard-feedback" role="status" aria-live="polite">Updates every 10 seconds while this page is visible.</p>
|
||||
<div class="dashboard-history">
|
||||
<% ['done', 'failed'].forEach(state => { %>
|
||||
<section class="panel" aria-labelledby="recent-<%= state %>-title">
|
||||
<div class="panel-header"><div><h2 id="recent-<%= state %>-title"><%= state === 'done' ? 'Recently completed' : 'Recent failed attempts' %></h2><p class="field-hint">Latest five records</p></div><a class="text-link" href="/status?state=<%= state %>">View history <span aria-hidden="true">↗</span></a></div>
|
||||
<ul class="recent-list" id="recent-<%= state %>"><% recentRows[state].forEach(job => { const stamp = job[state === 'done' ? 'finished_at' : 'failed_at'] || job.created_at; %>
|
||||
<li class="recent-job" data-recent-id="<%= job._id %>"><div class="recent-primary"><strong class="recent-name"><%= job.filename %></strong><time class="muted"<% if (stamp) { %> datetime="<%= stamp %>"<% } %>><%= stamp ? new Date(stamp).toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' }) : 'Time not recorded' %></time></div><span class="badge <%= state === 'done' ? 'badge-success' : 'badge-danger' %>"><%= state === 'done' ? 'Completed' : job.error_category || 'Failed' %></span></li>
|
||||
<% }) %></ul>
|
||||
<div class="empty-state recent-empty" id="recent-<%= state %>-empty"<%- recentRows[state].length ? ' hidden' : '' %>><strong><%= state === 'done' ? 'No completed downloads yet' : 'No failed attempts recorded' %></strong><p><%= state === 'done' ? 'Completed episodes will appear here.' : 'Any failed attempts will appear here for review.' %></p></div>
|
||||
<% if (state === 'failed') { %><p class="history-footnote field-hint">An earlier failed attempt may belong to an episode that later completed.</p><% } %>
|
||||
</section>
|
||||
<% }) %>
|
||||
</div>
|
||||
<script src="/dashboard.js" defer></script>
|
||||
<%- include('partials/footer') %>
|
||||
+5
-13
@@ -1,13 +1,5 @@
|
||||
<%- include("partials/header") %>
|
||||
|
||||
<div class="alert alert-danger mt-4">
|
||||
<h4>Error</h4>
|
||||
|
||||
<p>
|
||||
<%= message %>
|
||||
</p>
|
||||
|
||||
<a href="/" class="btn btn-danger mt-3">Return to Home</a>
|
||||
</div>
|
||||
|
||||
<%- include("partials/footer") %>
|
||||
<%- include('partials/header') %>
|
||||
<section class="panel error-panel" aria-labelledby="error-title">
|
||||
<div class="panel-body"><p class="eyebrow">REQUEST NEEDS ATTENTION</p><h1 class="page-title" id="error-title"><%= typeof title === 'string' && title ? title : 'Unable to complete this request' %></h1><p class="page-description"><%= typeof message === 'string' ? message : 'Please try again.' %></p><div class="button-group"><a href="/download" class="button button-primary">New download</a><a href="/status" class="button button-secondary">View queue</a></div></div>
|
||||
</section>
|
||||
<%- include('partials/footer') %>
|
||||
+72
-143
@@ -1,153 +1,82 @@
|
||||
<%- include("partials/header") %>
|
||||
<%
|
||||
const formValues = typeof values === 'object' && values ? values : {};
|
||||
const selectedMode = formValues.mode === 'video' ? 'video' : 'series';
|
||||
const isSeries = selectedMode === 'series';
|
||||
const episodeLimit = typeof maxSeriesEpisodes === 'number' ? maxSeriesEpisodes : 500;
|
||||
const destination = typeof outputDir === 'string' ? outputDir : 'Configured media folder';
|
||||
const submissionError = typeof formError === 'string' ? formError : '';
|
||||
const savedToken = typeof tokenStatus === 'object' && tokenStatus ? tokenStatus : { available: false, state: 'unknown' };
|
||||
const languages = [['engsub', 'English subtitles'], ['engdub', 'English dub'], ['gersub', 'German subtitles'], ['gerdub', 'German dub']];
|
||||
%>
|
||||
<%- include('partials/header', { activePage: 'download' }) %>
|
||||
|
||||
<div class="card card-dark p-4">
|
||||
<!-- MODE TOGGLE -->
|
||||
<div class="d-flex justify-content-center mb-4">
|
||||
<div class="pill-toggle">
|
||||
<div class="pill-option active" id="pillSeries">Series</div>
|
||||
<div class="pill-option" id="pillVideo">Video</div>
|
||||
<div class="pill-indicator" id="pillIndicator"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="/queue" id="jobForm">
|
||||
<input type="hidden" name="mode" id="modeInput" value="series" />
|
||||
|
||||
<!-- ===================== -->
|
||||
<!-- 1. ID / URL -->
|
||||
<!-- ===================== -->
|
||||
|
||||
<!-- SERIES: ID -->
|
||||
<div id="seriesFields">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">ID</label>
|
||||
<input
|
||||
class="form-control"
|
||||
name="id"
|
||||
type="number"
|
||||
placeholder="ID"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- VIDEO: URL -->
|
||||
<div id="videoFields" style="display: none">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">URL</label>
|
||||
<input
|
||||
class="form-control"
|
||||
name="url"
|
||||
placeholder="https://proxer.me/watch/..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===================== -->
|
||||
<!-- 2. TITEL (shared) -->
|
||||
<!-- ===================== -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Title / filename</label>
|
||||
<input
|
||||
class="form-control"
|
||||
name="name"
|
||||
placeholder="Title S01E01"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ===================== -->
|
||||
<!-- 3. LANGUAGE (shared) -->
|
||||
<!-- ===================== -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Language</label>
|
||||
<select class="form-select" name="language">
|
||||
<option value="engsub">EngSub</option>
|
||||
<option value="engdub">EngDub</option>
|
||||
<option value="gersub">GerSub</option>
|
||||
<option value="gerdub">GerDub</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- ===================== -->
|
||||
<!-- 4. EPISODES (series only) -->
|
||||
<!-- ===================== -->
|
||||
<div id="seriesEpisodes">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Episodes</label>
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<input
|
||||
class="form-control"
|
||||
name="episode_from"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="From"
|
||||
/>
|
||||
</div>
|
||||
<div class="col">
|
||||
<input
|
||||
class="form-control"
|
||||
name="episode_to"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="To"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===================== -->
|
||||
<!-- 5. TOKEN (shared) -->
|
||||
<!-- ===================== -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Token</label>
|
||||
<input
|
||||
class="form-control"
|
||||
name="token"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
required
|
||||
placeholder="Token"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ACTIONS -->
|
||||
<div class="d-flex justify-content-between">
|
||||
<button class="btn btn-danger">Queue Download</button>
|
||||
<a class="btn btn-outline-light" href="/status">View Queue</a>
|
||||
</div>
|
||||
</form>
|
||||
<div class="page-heading">
|
||||
<div><p class="eyebrow">YOUR DOWNLOAD LIBRARY</p><h1 class="page-title">New download</h1><p class="page-description">Queue a series or a single episode. Your workers take it from here.</p></div>
|
||||
<a class="button button-secondary" href="/status">View queue <span aria-hidden="true">↗</span></a>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const indicator = document.getElementById("pillIndicator");
|
||||
const btnSeries = document.getElementById("pillSeries");
|
||||
const btnVideo = document.getElementById("pillVideo");
|
||||
<div class="download-layout">
|
||||
<section class="panel">
|
||||
<div class="panel-header"><h2>Download details</h2><span class="muted small">Fields marked * are required</span></div>
|
||||
<form method="POST" action="/queue" id="jobForm" class="panel-body download-form" data-max-episodes="<%= episodeLimit %>">
|
||||
<% if (submissionError) { %>
|
||||
<div id="form-error" class="inline-notice notice-warning" role="alert" tabindex="-1"><strong>Download not added</strong><p><%= submissionError %></p><p class="small">Your download details are kept below. Token values are never shown again; leave the field blank to try the saved token or paste a replacement.</p></div>
|
||||
<% } %>
|
||||
|
||||
const modeInput = document.getElementById("modeInput");
|
||||
const seriesFields = document.getElementById("seriesFields");
|
||||
const seriesEpisodes = document.getElementById("seriesEpisodes");
|
||||
const videoFields = document.getElementById("videoFields");
|
||||
<fieldset class="mode-switch" id="download-mode" hidden>
|
||||
<legend class="visually-hidden">Download mode</legend>
|
||||
<label class="mode-choice"><input type="radio" name="mode" value="series" aria-controls="series-fields"<%- isSeries ? ' checked' : '' %>><span><strong>Series</strong><small>A range of episodes</small></span></label>
|
||||
<label class="mode-choice"><input type="radio" name="mode" value="video" aria-controls="video-fields"<%- !isSeries ? ' checked' : '' %>><span><strong>Single episode</strong><small>One Proxer watch URL</small></span></label>
|
||||
</fieldset>
|
||||
<noscript><div class="inline-notice">Current mode: <strong><%= isSeries ? 'Series' : 'Single episode' %></strong>. Switch to <a href="/download?mode=series">Series</a> or <a href="/download?mode=video">Single episode</a> before filling out this form.</div></noscript>
|
||||
|
||||
function updateMode(mode) {
|
||||
const isSeries = mode === "series";
|
||||
<fieldset id="series-fields" class="form-section"<%- isSeries ? '' : ' hidden disabled' %>>
|
||||
<legend class="section-label">01 <span>Choose your episodes</span></legend>
|
||||
<div class="form-grid">
|
||||
<div class="field"><label class="field-label" for="series-id">Series ID <span aria-hidden="true">*</span></label><input class="field-input" id="series-id" name="id" type="number" inputmode="numeric" min="1" max="9007199254740991" step="1" value="<%= formValues.id || '' %>" placeholder="e.g. 12345" required aria-describedby="series-id-hint"><p class="field-hint" id="series-id-hint">The numeric ID in the Proxer series or watch URL.</p></div>
|
||||
<div class="field"><label class="field-label" for="language">Language <span aria-hidden="true">*</span></label><select class="field-input" id="language" name="language" required><% languages.forEach(([value, label]) => { %><option value="<%= value %>"<%- (formValues.language || 'engsub') === value ? ' selected' : '' %>><%= label %></option><% }) %></select></div>
|
||||
<div class="field season-field"><label class="field-label" for="series-season">Season <span aria-hidden="true">*</span></label><input class="field-input" id="series-season" name="season" type="number" inputmode="numeric" min="0" max="9007199254740991" step="1" value="<%= formValues.season ?? '1' %>" required aria-describedby="season-hint"><p class="field-hint" id="season-hint">Used in the filename only. Use 0 for specials. Episode numbers still follow the Proxer source.</p></div>
|
||||
<div class="field"><label class="field-label" for="episode-from">First episode <span aria-hidden="true">*</span></label><input class="field-input" id="episode-from" name="episode_from" type="number" inputmode="numeric" min="1" max="9007199254740991" step="1" value="<%= formValues.episode_from || '' %>" placeholder="1" required></div>
|
||||
<div class="field"><label class="field-label" for="episode-to">Last episode <span aria-hidden="true">*</span></label><input class="field-input" id="episode-to" name="episode_to" type="number" inputmode="numeric" min="1" max="9007199254740991" step="1" value="<%= formValues.episode_to || '' %>" placeholder="12" required aria-describedby="episode-limit"><p class="field-hint" id="episode-limit">Both ends included. Up to <%= episodeLimit.toLocaleString('en') %> episodes per submission.</p></div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
indicator.style.transform = isSeries
|
||||
? "translateX(0)"
|
||||
: "translateX(100%)";
|
||||
<fieldset id="video-fields" class="form-section"<%- isSeries ? ' hidden disabled' : '' %>>
|
||||
<legend class="section-label">01 <span>Choose your episode</span></legend>
|
||||
<div class="field"><label class="field-label" for="episode-url">Proxer episode URL <span aria-hidden="true">*</span></label><input class="field-input" id="episode-url" name="url" type="url" inputmode="url" value="<%= formValues.url || '' %>" maxlength="2048" placeholder="https://proxer.me/watch/12345/1/engsub" spellcheck="false" required aria-describedby="episode-url-hint"><p class="field-hint" id="episode-url-hint">Use the HTTPS watch URL. The episode and language are taken from this link.</p></div>
|
||||
</fieldset>
|
||||
|
||||
btnSeries.classList.toggle("active", isSeries);
|
||||
btnVideo.classList.toggle("active", !isSeries);
|
||||
<section class="form-section" aria-labelledby="filename-heading">
|
||||
<h3 class="section-label" id="filename-heading">02 <span>Name your files</span></h3>
|
||||
<div class="field"><label class="field-label" for="download-name"><span id="name-label"><%= isSeries ? 'Series title' : 'Filename' %></span> <span class="optional">Optional</span></label><input class="field-input" id="download-name" name="name" value="<%= formValues.name || '' %>" maxlength="255" placeholder="<%= isSeries ? 'e.g. My Series' : 'e.g. My SeriesS001E001_engsub' %>" aria-describedby="name-hint"><p class="field-hint" id="name-hint"><%= isSeries ? 'Enter the title without season or episode numbers. Season, episode and language are added automatically. Leave blank to use the series ID.' : 'Enter a filename without .mp4. Leave blank to use the series ID, episode and language.' %></p></div>
|
||||
</section>
|
||||
|
||||
modeInput.value = mode;
|
||||
<section class="form-section" aria-labelledby="access-heading">
|
||||
<h3 class="section-label" id="access-heading">03 <span>Provide access</span></h3>
|
||||
<div class="token-cache-status" id="token-cache-status" data-state="<%= savedToken.state %>">
|
||||
<span class="badge <%= savedToken.available ? 'badge-success' : savedToken.state === 'invalid' ? 'badge-warning' : 'badge-neutral' %>"><%= savedToken.available ? 'Token saved' : savedToken.state === 'invalid' ? 'Replacement needed' : savedToken.state === 'missing' ? 'No token saved' : 'Saved token checked on submission' %></span>
|
||||
<p class="field-hint"><%= savedToken.available ? 'Leave the field blank to reuse it. Download access is checked again every time you add to the queue.' : savedToken.state === 'invalid' ? 'The saved token was rejected. Paste a fresh token to continue.' : savedToken.state === 'missing' ? 'Paste a token once. After a successful access check, it is saved for future submissions.' : savedToken.state === 'unavailable' ? 'Saved-token status is unavailable. Submission will retry the check before adding any jobs.' : 'Leave blank to try the saved token, or paste a replacement.' %></p>
|
||||
<% if (savedToken.lastValidatedAt && Number.isFinite(new Date(savedToken.lastValidatedAt).getTime())) { %><p class="field-hint">Last access check: <time datetime="<%= savedToken.lastValidatedAt %>" id="token-checked-at"><%= new Date(savedToken.lastValidatedAt).toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' }) %></time></p><% } %>
|
||||
</div>
|
||||
<div class="field"><label class="field-label" for="download-token">Session token <span class="optional">Leave blank to reuse saved token</span></label><div class="input-with-action"><input class="field-input" id="download-token" name="token" type="password" autocomplete="off" autocapitalize="none" spellcheck="false" maxlength="8192" placeholder="Paste a new token value" aria-describedby="token-hint"><button type="button" class="input-action" id="toggle-token" aria-pressed="false" aria-controls="download-token" hidden>Show</button></div><p class="field-hint" id="token-hint">Paste the cookie value only. A working token is stored in MongoDB and is never sent back to the browser. The first episode's source is checked before any jobs are added.</p></div>
|
||||
</section>
|
||||
|
||||
seriesFields.style.display = isSeries ? "" : "none";
|
||||
seriesEpisodes.style.display = isSeries ? "" : "none";
|
||||
videoFields.style.display = isSeries ? "none" : "";
|
||||
}
|
||||
<div class="form-actions"><button class="button button-primary" type="submit" id="queue-download">Add to queue <span aria-hidden="true">→</span></button><span class="muted small">Downloads start when a worker is available.</span></div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
btnSeries.onclick = () => updateMode("series");
|
||||
btnVideo.onclick = () => updateMode("video");
|
||||
</script>
|
||||
|
||||
<%- include("partials/footer") %>
|
||||
<aside class="download-sidebar" aria-label="Download preview">
|
||||
<section class="panel preview-panel">
|
||||
<div class="panel-header"><h2>At a glance</h2><span class="badge badge-neutral" id="preview-mode"><%= isSeries ? 'Series' : 'Single episode' %></span></div>
|
||||
<div class="panel-body">
|
||||
<p class="preview-count"><strong id="preview-count">—</strong><span id="preview-count-label">episodes to queue</span></p>
|
||||
<div class="preview-section"><h3>Filename preview</h3><p class="preview-filename" id="filename-preview">Fill in the episode details to see your filenames.</p><p class="field-hint" id="preview-last" hidden></p></div>
|
||||
<div class="preview-section"><h3>Save location</h3><p class="destination-path"><%= destination %></p><p class="field-hint">Files are saved as MP4.</p></div>
|
||||
<p class="preview-validation" id="preview-validation" aria-live="polite"></p>
|
||||
</div>
|
||||
</section>
|
||||
<section class="help-card"><span class="help-icon" aria-hidden="true">i</span><div><h2>If verification is needed</h2><p>Downloads pause and keep the affected episode in the queue. Complete verification on Proxer, then use <strong>Resume after verification</strong> to retry.</p></div></section>
|
||||
</aside>
|
||||
</div>
|
||||
<script src="/download.js" defer></script>
|
||||
<%- include('partials/footer') %>
|
||||
@@ -0,0 +1,38 @@
|
||||
<%
|
||||
const live = typeof activity === 'object' && activity ? activity : { workers: [], unassigned: [], available: false };
|
||||
const paused = typeof global === 'object' && global?.captcha_blocked === true;
|
||||
const currentWorkers = Array.isArray(live.workers) ? live.workers : [];
|
||||
const unknownJobs = Array.isArray(live.unassigned) ? live.unassigned : [];
|
||||
const liveSource = value => typeof value === 'string' && /^https:\/\/proxer\.me\/watch\/[1-9]\d*\/[1-9]\d*\/(engsub|engdub|gersub|gerdub)$/.test(value) ? value : '';
|
||||
const liveBytes = value => {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return 'Size unavailable';
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
||||
const n = value ? Math.min(Math.floor(Math.log(value) / Math.log(1024)), 4) : 0;
|
||||
return (value / 1024 ** n).toFixed(n ? 1 : 0) + ' ' + units[n] + ' on disk';
|
||||
};
|
||||
const workerState = worker => worker.jobs.length ? 'Active' : worker.status !== 'online'
|
||||
? (worker.status === 'errored' ? 'Error' : worker.status === 'stopped' ? 'Stopped' : 'Not ready')
|
||||
: worker.activityUnknown ? 'Activity unknown' : paused ? 'Paused' : 'Idle';
|
||||
%>
|
||||
<section class="activity-section" id="current-downloads" aria-labelledby="activity-title">
|
||||
<div class="section-heading"><div><h2 id="activity-title">Current downloads</h2><p class="field-hint" id="activity-freshness">Current claims by worker · refreshes with this page</p></div><a class="text-link" href="/pm2" id="activity-manage">Manage workers <span aria-hidden="true">↗</span></a></div>
|
||||
<p class="inline-notice notice-warning activity-warning" id="activity-warning"<%- live.available && !live.truncated && !live.workersTruncated ? ' hidden' : '' %>><%= !live.available ? 'Worker status is unavailable. Saved active claims are still shown below.' : 'Showing up to 50 workers and 50 active claims. Open the Active queue for the full list; empty cards may have unlisted activity.' %></p>
|
||||
<ul class="activity-cards" id="activity-workers" aria-label="Current download per worker. Scroll horizontally to view more workers." tabindex="0">
|
||||
<% currentWorkers.forEach(worker => { const state = workerState(worker); %>
|
||||
<li class="worker-card" data-worker-key="<%= worker.key %>">
|
||||
<div class="worker-card-heading"><strong class="worker-card-name"><%= worker.name %></strong><span class="worker-card-state badge <%= state === 'Active' ? 'badge-info' : ['Paused', 'Activity unknown'].includes(state) ? 'badge-warning' : state === 'Idle' ? 'badge-success' : 'badge-neutral' %>"><%= state %></span></div>
|
||||
<ul class="worker-card-jobs">
|
||||
<% worker.jobs.forEach(job => { %><%- include('active-job', { job, liveSource, liveBytes }) %><% }) %>
|
||||
</ul>
|
||||
<p class="worker-card-empty"<%- worker.jobs.length ? ' hidden' : '' %>><%= worker.activityUnknown && worker.status === 'online' ? 'No current job could be reliably linked to this worker.' : worker.status !== 'online' ? 'Start the worker to take queued episodes.' : paused ? 'Waiting for verification to clear.' : 'Ready for the next queued episode.' %></p>
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
<p class="field-hint activity-scroll-hint" id="activity-scroll-hint" hidden>Scroll sideways to view all <%= currentWorkers.length %> workers.</p>
|
||||
<div class="activity-empty" id="activity-empty"<%- currentWorkers.length ? ' hidden' : '' %>><strong><%= live.available ? 'No managed workers yet' : 'Worker inventory unavailable' %></strong><span><%= live.available ? 'Quick-add a worker to start taking queued episodes.' : 'Check the worker supervisor, then refresh.' %></span><a class="button button-secondary button-small" href="/pm2">Open workers</a></div>
|
||||
<section class="unassigned-activity" id="activity-unassigned" aria-labelledby="unassigned-title"<%- unknownJobs.length ? '' : ' hidden' %>>
|
||||
<div class="section-heading"><div><h3 id="unassigned-title">Active claims without a confirmed worker</h3><p class="field-hint">Older jobs and unavailable or restarted workers can appear here. These claims stay protected.</p></div><a class="text-link" href="/status?state=processing">View active queue</a></div>
|
||||
<ul class="unassigned-jobs" id="activity-unassigned-jobs"><% unknownJobs.forEach(job => { %><%- include('active-job', { job, liveSource, liveBytes, unassigned: true }) %><% }) %></ul>
|
||||
</section>
|
||||
</section>
|
||||
<script src="/activity.js" defer></script>
|
||||
@@ -0,0 +1,7 @@
|
||||
<% const source = liveSource(job.url); const parts = source.split('/'); const unconfirmed = typeof unassigned === 'boolean' && unassigned; %>
|
||||
<li class="active-job" data-active-job-id="<%= job._id %>">
|
||||
<strong class="active-job-name"><%= job.filename %></strong>
|
||||
<a class="active-job-source"<% if (source) { %> href="<%= source %>" target="_blank" rel="noopener noreferrer"<% } %>><%= source ? 'Series ' + parts[4] + ' · Episode ' + parts[5] + ' · ' + parts[6] : 'Source unavailable' %></a>
|
||||
<div class="active-job-metrics"><span class="active-job-size"><%= liveBytes(job.fileSize) %></span><span class="active-job-time" data-started-at="<%= job.started_at || '' %>"><%= job.started_at ? 'Started ' + new Date(job.started_at).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : 'Start time unavailable' %></span></div>
|
||||
<p class="active-job-attribution field-hint"<%- unconfirmed ? '' : ' hidden' %>><%= unconfirmed && job.worker ? 'Saved worker: ' + job.worker.name + ' · live assignment unconfirmed' : unconfirmed ? 'Worker was not recorded for this claim.' : '' %></p>
|
||||
</li>
|
||||
@@ -1,5 +1,4 @@
|
||||
<footer class="mt-5 small">Built by DeSqBlocki</footer>
|
||||
</div>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
</body>
|
||||
</main>
|
||||
<footer class="app-footer"><span>Proxer Downloader</span><span>Built by DeSqBlocki</span></footer>
|
||||
</body>
|
||||
</html>
|
||||
+37
-46
@@ -1,56 +1,47 @@
|
||||
<%
|
||||
const currentPage = typeof activePage === 'string' ? activePage : '';
|
||||
const pageTitle = typeof title === 'string' && title ? title : 'Proxer Downloader';
|
||||
const globalStatus = typeof global === 'object' && global ? global : {};
|
||||
const summaryKnown = typeof counts === 'object' && counts !== null;
|
||||
const downloadsPaused = globalStatus.captcha_blocked === true;
|
||||
const pendingCount = summaryKnown ? (Number(counts.queued) || 0) + (Number(counts.processing) || 0) : null;
|
||||
%>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Proxer-Downloader</title>
|
||||
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title><%= pageTitle %><%= pageTitle === 'Proxer Downloader' ? '' : ' · Proxer Downloader' %></title>
|
||||
<link rel="icon" href="/assets/favicon.ico" type="image/x-icon">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<script src="/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- CAPTCHA ALERT (initially hidden, will be toggled by JS) -->
|
||||
<div id="captcha-alert" class="alert alert-danger text-center m-0" style="display: <%= (typeof global !== 'undefined' && global.captcha_blocked) ? 'block' : 'none' %>;">
|
||||
<span id="captcha-message"><%= (typeof global !== 'undefined' && global.pause_reason === 'resolution')
|
||||
? '⚠ The video link could not be resolved. Possible causes include CAPTCHA or login verification, an unavailable video, or a source change. Workers are paused for verification.'
|
||||
: '⚠ Authentication or access needs verification on Proxer. Workers are paused until verification is complete.' %></span>
|
||||
<form id="clear-captcha-form" action="/clear-captcha" method="POST" class="d-inline ms-2">
|
||||
<button class="btn btn-danger btn-sm">Resume after verification</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="container-fluid py-4" style="max-width: 2000px;">
|
||||
<!-- HEADER -->
|
||||
<header class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1>Proxer-Downloader</h1>
|
||||
<nav class="d-flex gap-2">
|
||||
<a class="btn btn-outline-light" href="/">Home</a>
|
||||
<a class="btn btn-outline-light" href="/status">Status</a>
|
||||
<a class="btn btn-outline-light" href="/pm2">PM2</a>
|
||||
<a class="skip-link" href="#main-content">Skip to content</a>
|
||||
<header class="topbar">
|
||||
<div class="topbar-inner">
|
||||
<a class="brand" href="/" aria-label="Proxer Downloader home">
|
||||
<span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none"><path d="M12 4v11m-4-4 4 4 4-4M5 17v3h14v-3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
|
||||
<span class="brand-text">Proxer<span>Downloader</span></span>
|
||||
</a>
|
||||
<nav class="main-nav" aria-label="Main navigation">
|
||||
<a href="/" class="nav-link<%= currentPage === 'dashboard' ? ' is-active' : '' %>"<%- currentPage === 'dashboard' ? ' aria-current="page"' : '' %>>Dashboard</a>
|
||||
<a href="/download" class="nav-link<%= currentPage === 'download' ? ' is-active' : '' %>"<%- currentPage === 'download' ? ' aria-current="page"' : '' %>>New download</a>
|
||||
<a href="/status" class="nav-link<%= currentPage === 'queue' ? ' is-active' : '' %>"<%- currentPage === 'queue' ? ' aria-current="page"' : '' %>>Queue <span id="nav-queue-count" class="nav-count"<%- pendingCount === null ? ' hidden' : '' %>><%= pendingCount === null ? '' : pendingCount.toLocaleString('en') %></span></a>
|
||||
<a href="/pm2" class="nav-link<%= currentPage === 'workers' ? ' is-active' : '' %>"<%- currentPage === 'workers' ? ' aria-current="page"' : '' %>>Workers</a>
|
||||
</nav>
|
||||
<span id="global-status" class="connection-status<%= downloadsPaused ? ' is-paused' : summaryKnown ? ' is-ready' : '' %>" role="status" aria-live="polite"><span class="status-dot" aria-hidden="true"></span><span id="global-status-text"><%= downloadsPaused ? 'Downloads paused' : summaryKnown ? 'Queue ready' : 'Checking queue…' %></span></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<script>
|
||||
async function updateCaptchaAlert() {
|
||||
try {
|
||||
const res = await fetch('/status-data', { cache: 'no-store' });
|
||||
const data = await res.json();
|
||||
const alertEl = document.getElementById('captcha-alert');
|
||||
const messageEl = document.getElementById('captcha-message');
|
||||
|
||||
if (data.global && data.global.captcha_blocked) {
|
||||
messageEl.textContent = data.global.pause_reason === 'resolution'
|
||||
? '⚠ The video link could not be resolved. Possible causes include CAPTCHA or login verification, an unavailable video, or a source change. Workers are paused for verification.'
|
||||
: '⚠ Authentication or access needs verification on Proxer. Workers are paused until verification is complete.';
|
||||
alertEl.style.display = 'block';
|
||||
} else {
|
||||
alertEl.style.display = 'none';
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching status-data:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Poll every 5 seconds
|
||||
setInterval(updateCaptchaAlert, 5000);
|
||||
</script>
|
||||
<div class="notice-wrap">
|
||||
<section id="captcha-alert" class="verification-notice" aria-label="Downloads need your attention"<%- downloadsPaused ? '' : ' hidden' %>>
|
||||
<div class="notice-copy"><strong>Verification needed</strong><span id="captcha-message"><%= globalStatus.pause_reason === 'resolution'
|
||||
? 'The video link could not be resolved. Possible causes include CAPTCHA or login verification, an unavailable video, or a source change. Workers are paused for verification.'
|
||||
: 'Authentication or access needs verification on Proxer. Workers are paused until verification is complete.' %></span></div>
|
||||
<form id="clear-captcha-form" action="/clear-captcha" method="POST">
|
||||
<button type="submit" class="button button-warning button-small">Resume after verification</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
<main id="main-content" class="app-main" data-page="<%= currentPage %>" tabindex="-1">
|
||||
+117
-379
@@ -1,402 +1,140 @@
|
||||
<%- include('partials/header') %>
|
||||
<%- include('partials/header', { title: 'Workers', activePage: 'workers' }) %>
|
||||
<%
|
||||
const workerProcesses = Array.isArray(processes) ? processes : [];
|
||||
const onlineCount = workerProcesses.filter(p => ['online', 'running'].includes(p.status)).length;
|
||||
const workerStatusClass = status => ['online', 'running'].includes(status) ? 'status-online'
|
||||
: ['stopped', 'errored', 'offline'].includes(status) ? 'status-stopped' : 'status-pending';
|
||||
%>
|
||||
|
||||
<style>
|
||||
/* Dark theme PM2 CSS (integrates with your style.css) */
|
||||
.pm2-row { cursor: pointer; border: 1px solid #4A4A4A; }
|
||||
.pm2-row.active, .pm2-row.selected-outline {
|
||||
background-color: #555 !important;
|
||||
border-color: #8A190B !important;
|
||||
box-shadow: 0 0 0 2px rgba(138,25,11,0.4);
|
||||
}
|
||||
|
||||
#logs {
|
||||
height: 60vh;
|
||||
background: #0b1220;
|
||||
color: #e6eef8;
|
||||
padding: 10px;
|
||||
font-family: monospace;
|
||||
font-size: 0.85rem;
|
||||
overflow-y: auto;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #444;
|
||||
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.kv-label { width: 110px; display: inline-block; color: #C0C0C0; }
|
||||
.kv-value { font-weight: bold; color: #ffffff; }
|
||||
.subtle { color: #BEBEBE; font-size: 0.85rem; }
|
||||
|
||||
.badge-small { font-size: .75rem; padding: .25rem .5rem; border-radius: .4rem; }
|
||||
</style>
|
||||
|
||||
<div class="container py-3" style="max-width:1300px;">
|
||||
|
||||
<div class="row g-3">
|
||||
|
||||
<!-- LEFT COLUMN — PROCESS LIST & CONTROL CENTRE -->
|
||||
<div class="col-md-5 d-flex">
|
||||
<div class="card-dark w-100 d-flex flex-column">
|
||||
|
||||
<div class="d-flex justify-content-between mb-2">
|
||||
<section class="page-heading" aria-labelledby="workers-title">
|
||||
<div>
|
||||
<h4 class="mb-0">Downloader Workers</h4>
|
||||
<div class="subtle">Select a worker to manage it and view its logs.</div>
|
||||
<p class="eyebrow">Download operations</p>
|
||||
<h1 id="workers-title" class="page-title">Workers</h1>
|
||||
<p class="page-description">Manage your download workers and follow their output.</p>
|
||||
</div>
|
||||
<div class="page-actions">
|
||||
<span id="worker-counts" class="worker-counts"><%= onlineCount %> online · <%= workerProcesses.length %> total</span>
|
||||
<button id="refresh-list" class="button button-secondary" type="button" disabled>Refresh workers</button>
|
||||
<button id="btn-quick-add" class="button button-primary" type="button" disabled>Quick add worker</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="d-flex gap-2 align-items-center">
|
||||
<button id="refresh-list" class="btn btn-sm btn-outline-light" aria-label="Refresh worker list">⟳</button>
|
||||
<noscript><p class="notice">Enable JavaScript to manage workers and view live logs.</p></noscript>
|
||||
<p id="control-output" class="action-message" role="status" aria-live="polite" hidden></p>
|
||||
|
||||
<!-- NEW: ONE-CLICK CREATE -->
|
||||
<button id="btn-create" class="btn btn-sm btn-success" aria-label="Create downloader worker">
|
||||
<strong>+</strong>
|
||||
<div class="workers-layout">
|
||||
<section class="panel" aria-labelledby="worker-list-title">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="worker-list-title">Your workers</h2>
|
||||
<p id="worker-refresh-state" class="muted" role="status" aria-live="polite">Updates every 10 seconds</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<ul id="process-list" class="worker-list" aria-label="Download workers">
|
||||
<% workerProcesses.forEach(p => { %>
|
||||
<li class="worker-list-item">
|
||||
<button type="button" class="worker-row" aria-pressed="false" disabled
|
||||
data-key="<%= String(p.pm_id) + ':' + p.name %>"
|
||||
data-name="<%= p.name %>" data-pmid="<%= p.pm_id %>"
|
||||
data-pid="<%= p.pid %>" data-status="<%= p.status %>"
|
||||
data-cpu="<%= p.cpu %>" data-memory="<%= p.memoryMB %>"
|
||||
data-uptime="<%= p.uptime %>" data-exec="<%= p.execPath %>">
|
||||
<span class="worker-row-heading">
|
||||
<strong class="worker-name"><%= p.name %></strong>
|
||||
<span class="badge <%= workerStatusClass(p.status) %>" data-worker-status><%= p.status %></span>
|
||||
</span>
|
||||
<span class="worker-row-meta" data-worker-metrics>CPU <%= p.cpu %> · <%= p.memoryMB %> · <%= p.uptime %></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PROCESS LIST -->
|
||||
<div id="process-list" class="list-group" style="max-height:40vh; overflow-y:auto;">
|
||||
<% if (processes && processes.length) { %>
|
||||
<% processes.forEach(p => {
|
||||
let status = (p.status || '').toLowerCase();
|
||||
let badge = 'bg-secondary';
|
||||
if (status === 'online' || status === 'running') badge = 'bg-success';
|
||||
else if (status.includes('stop') || status.includes('exit')) badge = 'bg-danger';
|
||||
else if (status.includes('launch') || status.includes('start')) badge = 'bg-warning text-dark';
|
||||
%>
|
||||
<a href="#"
|
||||
class="list-group-item pm2-row d-flex justify-content-between"
|
||||
data-name="<%= p.name %>"
|
||||
data-pid="<%= p.pid %>"
|
||||
data-pmid="<%= p.pm_id %>"
|
||||
data-status="<%= p.status %>"
|
||||
>
|
||||
<div>
|
||||
<strong><%= p.name %></strong>
|
||||
<span class="badge badge-small <%= badge %>"><%= p.status %></span>
|
||||
<div class="subtle"><%= p.execPath %></div>
|
||||
</div>
|
||||
|
||||
<div class="text-end">
|
||||
<div>pid: <span><%= p.pid %></span></div>
|
||||
<div class="subtle"><%= p.uptime %></div>
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
<% }) %>
|
||||
<% } else { %>
|
||||
<div class="alert alert-warning">No downloader workers found.</div>
|
||||
<% } %>
|
||||
</ul>
|
||||
<div id="workers-empty" class="empty-state" <%= workerProcesses.length ? 'hidden' : '' %>>
|
||||
<h3>No workers yet</h3>
|
||||
<p>Use Quick add worker to start processing the queue.</p>
|
||||
</div>
|
||||
|
||||
<pre id="control-output" class="mt-3 p-2" role="status" aria-live="polite" style="background:#0b0b0b; max-height:110px; overflow:auto; border-radius:6px; white-space:pre-wrap;">Worker action results will appear here.</pre>
|
||||
|
||||
<!-- CONTROL CENTRE -->
|
||||
<div id="control-centre" class="mt-3 p-3" style="display:none; background:#3A3A3A; border-radius:8px; border:1px solid #555;">
|
||||
<h5 id="cc-name">Process Name</h5>
|
||||
<div id="cc-sub" class="subtle mb-2">pm_id / pid / status</div>
|
||||
|
||||
<!-- Quick actions -->
|
||||
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||
<button id="btn-start" class="btn btn-success btn-sm">Start</button>
|
||||
<button id="btn-stop" class="btn btn-danger btn-sm">Stop</button>
|
||||
<button id="btn-restart" class="btn btn-warning btn-sm">Restart</button>
|
||||
<button id="btn-delete" class="btn btn-outline-light btn-sm">Delete</button>
|
||||
<p class="field-hint worker-quick-add-hint">Quick add starts a worker immediately, named proxer-worker-1, proxer-worker-2 and so on. The next number is chosen automatically.</p>
|
||||
<details class="worker-create">
|
||||
<summary>Choose a custom name</summary>
|
||||
<form id="create-worker-form" novalidate>
|
||||
<div class="field">
|
||||
<label class="field-label" for="worker-name">Worker name</label>
|
||||
<input class="field-input" id="worker-name" name="workerName" type="text"
|
||||
required maxlength="64" pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}"
|
||||
autocomplete="off" spellcheck="false" placeholder="my-worker"
|
||||
aria-describedby="worker-name-hint">
|
||||
<p id="worker-name-hint" class="field-hint">Start with a letter or number. Use letters, numbers, underscores or hyphens.</p>
|
||||
</div>
|
||||
|
||||
<!-- Details -->
|
||||
<div class="small">
|
||||
<div><span class="kv-label">PM2 name</span> <span class="kv-value" id="detail-name">—</span></div>
|
||||
<div><span class="kv-label">PM2 id</span> <span class="kv-value" id="detail-pmid">—</span></div>
|
||||
<div><span class="kv-label">PID</span> <span class="kv-value" id="detail-pid">—</span></div>
|
||||
<div><span class="kv-label">Status</span> <span class="kv-value" id="detail-status">—</span></div>
|
||||
<div><span class="kv-label">Uptime</span> <span class="kv-value" id="detail-uptime">—</span></div>
|
||||
<div><span class="kv-label">CPU</span> <span class="kv-value" id="detail-cpu">—</span></div>
|
||||
<div><span class="kv-label">Memory</span> <span class="kv-value" id="detail-mem">—</span></div>
|
||||
<div><span class="kv-label">Exec Path</span> <span class="kv-value" id="detail-exec">—</span></div>
|
||||
<button id="btn-create" class="button button-secondary" type="submit" disabled>Create named worker</button>
|
||||
<p class="field-hint">A new worker starts immediately.</p>
|
||||
</form>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="worker-workspace">
|
||||
<section id="worker-placeholder" class="panel worker-selection-empty">
|
||||
<div class="empty-state">
|
||||
<h2>Select a worker</h2>
|
||||
<p>Choose a worker to see its health, manage it and open its logs.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="control-centre" class="panel worker-controls" aria-labelledby="cc-name" hidden>
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<p class="eyebrow">Selected worker</p>
|
||||
<h2 id="cc-name"></h2>
|
||||
<p id="cc-sub" class="muted"></p>
|
||||
</div>
|
||||
<button id="clear-selection" class="button button-ghost" type="button">Deselect</button>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<dl class="worker-stats">
|
||||
<div><dt>CPU</dt><dd id="detail-cpu">—</dd></div>
|
||||
<div><dt>Memory</dt><dd id="detail-mem">—</dd></div>
|
||||
<div><dt>Uptime</dt><dd id="detail-uptime">—</dd></div>
|
||||
</dl>
|
||||
<div class="worker-actions" aria-label="Selected worker actions">
|
||||
<button id="btn-start" class="button button-primary" type="button" disabled>Start</button>
|
||||
<button id="btn-stop" class="button button-secondary" type="button" disabled>Stop</button>
|
||||
<button id="btn-restart" class="button button-secondary" type="button" disabled>Restart</button>
|
||||
<button id="btn-delete" class="button button-danger" type="button" disabled>Delete worker</button>
|
||||
</div>
|
||||
<details class="worker-details">
|
||||
<summary>Process details</summary>
|
||||
<dl>
|
||||
<div><dt>PM2 ID</dt><dd id="detail-pmid">—</dd></div>
|
||||
<div><dt>Process ID</dt><dd id="detail-pid">—</dd></div>
|
||||
<div><dt>Status</dt><dd id="detail-status">—</dd></div>
|
||||
<div><dt>Executable</dt><dd id="detail-exec">—</dd></div>
|
||||
</dl>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel log-panel" aria-labelledby="logs-title">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="logs-title">Worker logs</h2>
|
||||
<p id="log-connection-state" class="muted" role="status" aria-live="polite">No worker selected</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RIGHT COLUMN — LOGS -->
|
||||
<div class="col-md-7 d-flex">
|
||||
<div class="card-dark w-100 d-flex flex-column">
|
||||
|
||||
<div class="d-flex justify-content-between mb-2">
|
||||
<h4>Logs</h4>
|
||||
<div class="d-flex gap-2">
|
||||
<button id="clear-logs" class="btn btn-outline-light btn-sm">Clear</button>
|
||||
<div class="panel-body">
|
||||
<div class="log-toolbar">
|
||||
<label class="checkbox-label" for="follow-logs"><input id="follow-logs" type="checkbox" checked> Follow output</label>
|
||||
<div class="worker-actions">
|
||||
<button id="reconnect-logs" class="button button-secondary button-small" type="button" disabled>Reconnect logs</button>
|
||||
<button id="clear-logs" class="button button-ghost button-small" type="button">Clear view</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="logs">[no logs yet]</div>
|
||||
|
||||
<pre id="logs" class="log-view" tabindex="0" aria-label="Worker log output" aria-live="off">Select a worker to view its logs.</pre>
|
||||
<p class="field-hint">The latest output stays here while you browse. Clearing this view does not delete stored logs.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host);
|
||||
const logsEl = document.getElementById('logs');
|
||||
const actionOutput = document.getElementById('control-output');
|
||||
const MAX_VISIBLE_LOG = 64 * 1024;
|
||||
let selectedEl = null;
|
||||
let selectedData = null;
|
||||
let selectionGeneration = 0;
|
||||
let logWorkerName = null;
|
||||
let commandInFlight = false;
|
||||
|
||||
function appendLog(message) {
|
||||
const following = logsEl.scrollHeight - logsEl.scrollTop - logsEl.clientHeight < 40;
|
||||
const combined = logsEl.textContent + `[${new Date().toLocaleTimeString()}] ${String(message)}\n`;
|
||||
logsEl.textContent = combined.length > MAX_VISIBLE_LOG
|
||||
? '[earlier log output omitted]\n' + combined.slice(-MAX_VISIBLE_LOG)
|
||||
: combined;
|
||||
if (following) logsEl.scrollTop = logsEl.scrollHeight;
|
||||
}
|
||||
|
||||
function sendLogRequest(payload, showUnavailable = true) {
|
||||
if (ws.readyState !== WebSocket.OPEN) {
|
||||
if (showUnavailable) appendLog('[log connection is not ready]');
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
ws.send(JSON.stringify(payload));
|
||||
return true;
|
||||
} catch {
|
||||
if (showUnavailable) appendLog('[log request could not be sent]');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function startSelectedLogs() {
|
||||
if (!selectedData || logWorkerName === selectedData.name) return;
|
||||
if (sendLogRequest({ type: 'logs', name: selectedData.name })) logWorkerName = selectedData.name;
|
||||
}
|
||||
|
||||
ws.addEventListener('open', () => {
|
||||
appendLog('[log connection ready]');
|
||||
startSelectedLogs();
|
||||
});
|
||||
ws.addEventListener('close', () => {
|
||||
logWorkerName = null;
|
||||
appendLog('[log connection closed; reload this page to reconnect]');
|
||||
});
|
||||
ws.addEventListener('error', () => appendLog('[log connection unavailable]'));
|
||||
ws.addEventListener('message', event => {
|
||||
let payload;
|
||||
try { payload = JSON.parse(event.data); } catch { return; }
|
||||
if (!payload || typeof payload !== 'object') return;
|
||||
if (payload.type === 'stdout' || payload.type === 'stderr') appendLog(payload.data || '');
|
||||
else if (payload.type === 'info') appendLog('[info] ' + (payload.message || ''));
|
||||
else if (payload.type === 'error') {
|
||||
logWorkerName = null;
|
||||
appendLog('[error] ' + (payload.error || 'The log stream failed.'));
|
||||
} else if (payload.type === 'close') {
|
||||
logWorkerName = null;
|
||||
appendLog('[log stream closed]');
|
||||
}
|
||||
});
|
||||
|
||||
function clearSelection() {
|
||||
selectionGeneration++;
|
||||
document.querySelectorAll('.pm2-row').forEach(row => row.classList.remove('active', 'selected-outline'));
|
||||
selectedEl = null;
|
||||
selectedData = null;
|
||||
logWorkerName = null;
|
||||
document.getElementById('control-centre').style.display = 'none';
|
||||
sendLogRequest({ type: 'stop-logs' }, false);
|
||||
}
|
||||
|
||||
function controlData(process) {
|
||||
return { ...process, pmid: process.pm_id ?? process.pmid ?? '—' };
|
||||
}
|
||||
|
||||
function populateControlCentre(data) {
|
||||
const values = {
|
||||
'cc-name': data.name,
|
||||
'cc-sub': `pm_id: ${data.pmid} • pid: ${data.pid} • status: ${data.status}`,
|
||||
'detail-name': data.name,
|
||||
'detail-pmid': data.pmid,
|
||||
'detail-pid': data.pid,
|
||||
'detail-status': data.status,
|
||||
'detail-uptime': data.uptime,
|
||||
'detail-cpu': data.cpu,
|
||||
'detail-mem': data.memoryMB,
|
||||
'detail-exec': data.execPath,
|
||||
};
|
||||
for (const [id, value] of Object.entries(values)) document.getElementById(id).textContent = value ?? '—';
|
||||
}
|
||||
|
||||
async function readProcesses() {
|
||||
const response = await fetch('/pm2/list-json', { cache: 'no-store' });
|
||||
const result = await response.json();
|
||||
if (!response.ok || !result.ok || !Array.isArray(result.processes)) throw new Error('The worker list is unavailable.');
|
||||
return result.processes;
|
||||
}
|
||||
|
||||
function bindRowEvents() {
|
||||
document.querySelectorAll('.pm2-row').forEach(row => {
|
||||
row.addEventListener('click', async event => {
|
||||
event.preventDefault();
|
||||
if (selectedEl === row) {
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
clearSelection();
|
||||
const requestGeneration = selectionGeneration;
|
||||
row.classList.add('active', 'selected-outline');
|
||||
selectedEl = row;
|
||||
selectedData = controlData({
|
||||
name: row.dataset.name,
|
||||
pmid: row.dataset.pmid,
|
||||
pid: row.dataset.pid,
|
||||
status: row.dataset.status,
|
||||
});
|
||||
populateControlCentre(selectedData);
|
||||
document.getElementById('control-centre').style.display = 'block';
|
||||
const name = selectedData.name;
|
||||
try {
|
||||
const full = (await readProcesses()).find(process => process.name === name);
|
||||
if (requestGeneration !== selectionGeneration || selectedData?.name !== name) return;
|
||||
if (!full) {
|
||||
clearSelection();
|
||||
actionOutput.textContent = 'The selected worker is no longer available.';
|
||||
return;
|
||||
}
|
||||
selectedData = controlData(full);
|
||||
populateControlCentre(selectedData);
|
||||
} catch {
|
||||
if (requestGeneration !== selectionGeneration || selectedData?.name !== name) return;
|
||||
actionOutput.textContent = 'Could not refresh the selected worker details.';
|
||||
}
|
||||
if (requestGeneration === selectionGeneration && selectedData?.name === name) startSelectedLogs();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function element(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined) node.textContent = String(text ?? '—');
|
||||
return node;
|
||||
}
|
||||
|
||||
function processRow(process) {
|
||||
const row = element('a', 'list-group-item pm2-row d-flex justify-content-between');
|
||||
row.href = '#';
|
||||
row.dataset.name = String(process.name);
|
||||
row.dataset.pid = String(process.pid);
|
||||
row.dataset.pmid = String(process.pm_id);
|
||||
row.dataset.status = String(process.status);
|
||||
const status = String(process.status || '').toLowerCase();
|
||||
let badge = 'bg-secondary';
|
||||
if (status === 'online' || status === 'running') badge = 'bg-success';
|
||||
else if (status.includes('stop') || status.includes('exit')) badge = 'bg-danger';
|
||||
else if (status.includes('start') || status.includes('launch')) badge = 'bg-warning text-dark';
|
||||
const description = element('div');
|
||||
description.append(element('strong', '', process.name), ' ', element('span', 'badge badge-small ' + badge, process.status), element('div', 'subtle', process.execPath));
|
||||
const detail = element('div', 'text-end');
|
||||
detail.append(element('div', '', 'pid: ' + process.pid), element('div', 'subtle', process.uptime));
|
||||
row.append(description, detail);
|
||||
return row;
|
||||
}
|
||||
|
||||
async function refreshList() {
|
||||
try {
|
||||
const processes = await readProcesses();
|
||||
const list = document.getElementById('process-list');
|
||||
const selectedName = selectedData?.name;
|
||||
list.replaceChildren();
|
||||
for (const process of processes) {
|
||||
const row = processRow(process);
|
||||
list.appendChild(row);
|
||||
if (process.name === selectedName) {
|
||||
selectedEl = row;
|
||||
selectedData = controlData(process);
|
||||
row.classList.add('active', 'selected-outline');
|
||||
populateControlCentre(selectedData);
|
||||
}
|
||||
}
|
||||
if (!processes.length) list.appendChild(element('div', 'alert alert-warning', 'No downloader workers found.'));
|
||||
if (selectedName && !processes.some(process => process.name === selectedName)) clearSelection();
|
||||
bindRowEvents();
|
||||
return true;
|
||||
} catch {
|
||||
actionOutput.textContent = 'Could not refresh the worker list. Please try again.';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function execCommand(payload) {
|
||||
if (commandInFlight) return false;
|
||||
commandInFlight = true;
|
||||
actionOutput.textContent = 'Running worker command…';
|
||||
try {
|
||||
const response = await fetch('/pm2/command', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const result = await response.json();
|
||||
actionOutput.textContent = result.message || result.error || 'The worker command could not be completed.';
|
||||
if (response.ok && result.ok) {
|
||||
await refreshList();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
actionOutput.textContent = 'Could not contact the worker supervisor. Please try again.';
|
||||
return false;
|
||||
} finally {
|
||||
commandInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function findNextWorkerName() {
|
||||
const names = new Set((await readProcesses()).map(process => process.name));
|
||||
let next = 1;
|
||||
while (names.has('proxerdl-worker' + next)) next++;
|
||||
return 'proxerdl-worker' + next;
|
||||
}
|
||||
|
||||
document.getElementById('btn-create').addEventListener('click', async event => {
|
||||
const button = event.currentTarget;
|
||||
if (button.disabled || commandInFlight) return;
|
||||
button.disabled = true;
|
||||
actionOutput.textContent = 'Preparing a downloader worker…';
|
||||
try {
|
||||
const name = await findNextWorkerName();
|
||||
if (await execCommand({ cmd: 'create', name })) {
|
||||
const row = [...document.querySelectorAll('.pm2-row')].find(item => item.dataset.name === name);
|
||||
if (row) row.click();
|
||||
}
|
||||
} catch {
|
||||
actionOutput.textContent = 'Could not prepare the worker. Refresh the list and try again.';
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
for (const command of ['start', 'stop', 'restart', 'delete']) {
|
||||
document.getElementById('btn-' + command).addEventListener('click', () => {
|
||||
if (!selectedData) {
|
||||
actionOutput.textContent = 'Select a downloader worker first.';
|
||||
return;
|
||||
}
|
||||
execCommand({ cmd: command, name: selectedData.name });
|
||||
});
|
||||
}
|
||||
document.getElementById('refresh-list').addEventListener('click', refreshList);
|
||||
document.getElementById('clear-logs').addEventListener('click', () => { logsEl.textContent = ''; });
|
||||
window.addEventListener('beforeunload', () => sendLogRequest({ type: 'stop-logs' }, false));
|
||||
bindRowEvents();
|
||||
</script>
|
||||
|
||||
<script src="/workers.js" defer></script>
|
||||
<%- include('partials/footer') %>
|
||||
+132
-303
@@ -1,315 +1,144 @@
|
||||
<%- include("partials/header") %>
|
||||
<%- include("partials/header", { title: "Queue", activePage: "queue" }) %>
|
||||
<%
|
||||
const states = {
|
||||
queued: { label: "Queued", note: "Waiting to start", badge: "badge-neutral", date: "created_at", dateLabel: "Queued" },
|
||||
processing: { label: "Active", note: "Claimed by workers", badge: "badge-info", date: "started_at", dateLabel: "Started" },
|
||||
done: { label: "Completed", note: "Successful downloads", badge: "badge-success", date: "finished_at", dateLabel: "Finished" },
|
||||
failed: { label: "Failed attempts", note: "Review the attempt log", badge: "badge-danger", date: "failed_at", dateLabel: "Failed" }
|
||||
};
|
||||
const selected = states[filters.state];
|
||||
const clearActions = {
|
||||
queued: { label: 'Clear waiting queue', confirmation: 'Remove every waiting episode from the queue, including episodes outside this filter or page? Active downloads will continue.' },
|
||||
done: { label: 'Clear completed history', confirmation: 'Clear all completed download records, including records outside this filter or page? Downloaded files will remain on disk.' },
|
||||
failed: { label: 'Clear failed history', confirmation: 'Clear all failed-attempt records, including records outside this filter or page? Retained queued episodes and files will remain unchanged.' }
|
||||
};
|
||||
const clearAction = clearActions[filters.state];
|
||||
const pageLink = (state, page, q = filters.q) => "/status?" + new URLSearchParams({ state, q, page: String(page), pageSize: String(pagination.pageSize) }).toString();
|
||||
const safeSource = value => typeof value === "string" && /^https:\/\/proxer\.me\/watch\/[1-9]\d*\/[1-9]\d*\/(engsub|engdub|gersub|gerdub)$/.test(value) ? value : "";
|
||||
const languages = { engsub: "English sub", engdub: "English dub", gersub: "German sub", gerdub: "German dub" };
|
||||
const sourceLabel = value => {
|
||||
const parts = safeSource(value).split("/");
|
||||
return parts.length === 7 ? "Series " + parts[4] + " · Episode " + parts[5] + " · " + languages[parts[6]] : "Source unavailable";
|
||||
};
|
||||
const bytes = value => {
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return "—";
|
||||
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
|
||||
const index = value > 0 ? Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1) : 0;
|
||||
return (value / Math.pow(1024, index)).toFixed(index === 0 ? 0 : 1) + " " + units[index];
|
||||
};
|
||||
const displayDate = value => {
|
||||
const date = new Date(value);
|
||||
return value && Number.isFinite(date.getTime()) ? date.toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short" }) : "Not recorded";
|
||||
};
|
||||
%>
|
||||
|
||||
<style>
|
||||
.status-card {
|
||||
background: #3A3A3A;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #444;
|
||||
padding: 15px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.35);
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.status-title {
|
||||
margin: 0;
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.log-box {
|
||||
background:#001122;
|
||||
color:#9cf;
|
||||
padding:10px;
|
||||
border-radius:5px;
|
||||
white-space:pre-wrap;
|
||||
overflow-wrap:break-word;
|
||||
}
|
||||
|
||||
.log-box-light {
|
||||
background:#222;
|
||||
color:#e0e0e0;
|
||||
padding:10px;
|
||||
border-radius:5px;
|
||||
white-space:pre-wrap;
|
||||
overflow-wrap:break-word;
|
||||
}
|
||||
|
||||
.log-box-error {
|
||||
background:#330000;
|
||||
color:#ffb3b3;
|
||||
padding:10px;
|
||||
border-radius:5px;
|
||||
white-space:pre-wrap;
|
||||
overflow-wrap:break-word;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
display:flex;
|
||||
justify-content:center;
|
||||
align-items:center;
|
||||
margin-bottom:10px;
|
||||
gap:6px;
|
||||
}
|
||||
|
||||
.list-group-item {
|
||||
background:#3A3A3A;
|
||||
border-color:#4A4A4A;
|
||||
}
|
||||
|
||||
details summary {
|
||||
cursor:pointer;
|
||||
margin-top:6px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="row g-3">
|
||||
|
||||
<!-- ======================= -->
|
||||
<!-- QUEUED -->
|
||||
<!-- ======================= -->
|
||||
<div class="col-md-3">
|
||||
<div class="status-card text-center">
|
||||
|
||||
<div class="section-header">
|
||||
<h3 class="status-title">Queued</h3>
|
||||
<form action="/clear-queued" method="POST">
|
||||
<button class="btn btn-outline-secondary btn-sm rounded-pill">🗑️</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ul class="list-group" id="queuedList">
|
||||
<% if (queued.length === 0) { %>
|
||||
<li class="list-group-item ">No queued jobs</li>
|
||||
<% } %>
|
||||
|
||||
<% queued.forEach(job => { %>
|
||||
<li class="list-group-item">
|
||||
<strong><%= job.filename %></strong><br>
|
||||
<small><%= job.url %></small><br>
|
||||
<small><%= new Date(job.created_at).toLocaleString() %></small>
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ======================= -->
|
||||
<!-- PROCESSING -->
|
||||
<!-- ======================= -->
|
||||
<div class="col-md-3">
|
||||
<div class="status-card text-center">
|
||||
|
||||
<div class="section-header">
|
||||
<h3 class="status-title" style="color:#58a6ff;">Processing</h3>
|
||||
</div>
|
||||
|
||||
<ul class="list-group" id="processingList">
|
||||
<% if (processing.length === 0) { %>
|
||||
<li class="list-group-item ">Nothing processing</li>
|
||||
<% } %>
|
||||
|
||||
<% processing.forEach(job => { %>
|
||||
<li class="list-group-item">
|
||||
<strong style="color:#58a6ff"><%= job.filename %></strong>
|
||||
<span class="spinner-border spinner-border-sm ms-1" style="color:#58a6ff"></span><br>
|
||||
<small><%= job.url %></small><br>
|
||||
<small><%= job.started_at ? 'Started' : 'Queued' %>: <%= new Date(job.started_at || job.created_at).toLocaleString() %></small><br>
|
||||
|
||||
<% if (job.fileSize) { %>
|
||||
<small>Downloaded: <%= job.fileSize %></small>
|
||||
<% } %>
|
||||
|
||||
<% if (job.output_log) { %>
|
||||
<details data-id="processing-<%= job._id %>">
|
||||
<summary class="text-light">Live Log</summary>
|
||||
<pre class="log-box"><%= job.output_log %></pre>
|
||||
</details>
|
||||
<% } %>
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ======================= -->
|
||||
<!-- DONE -->
|
||||
<!-- ======================= -->
|
||||
<div class="col-md-3">
|
||||
<div class="status-card text-center">
|
||||
|
||||
<div class="section-header">
|
||||
<h3 class="status-title text-success">Done</h3>
|
||||
<form action="/clear-done" method="POST">
|
||||
<button class="btn btn-outline-success btn-sm rounded-pill">🗑️</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ul class="list-group" id="doneList">
|
||||
<% if (finished.length === 0) { %>
|
||||
<li class="list-group-item ">No completed jobs</li>
|
||||
<% } %>
|
||||
|
||||
<% finished.forEach(job => { %>
|
||||
<li class="list-group-item">
|
||||
|
||||
<strong class="text-success"><%= job.filename %></strong><br>
|
||||
<small><%= new Date(job.finished_at).toLocaleString() %></small><br>
|
||||
|
||||
<% if (job.fileSize) { %>
|
||||
<small>Size: <%= job.fileSize %></small><br>
|
||||
<% } %>
|
||||
|
||||
<% if (job.output_log) { %>
|
||||
<details data-id="done-<%= job._id %>">
|
||||
<summary class="text-light">Show Log</summary>
|
||||
<pre class="log-box-light"><%= job.output_log %></pre>
|
||||
</details>
|
||||
<% } %>
|
||||
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ======================= -->
|
||||
<!-- FAILED -->
|
||||
<!-- ======================= -->
|
||||
<div class="col-md-3">
|
||||
<div class="status-card text-center">
|
||||
|
||||
<div class="section-header">
|
||||
<h3 class="status-title text-danger">Failed</h3>
|
||||
<form action="/clear-failed" method="POST">
|
||||
<button class="btn btn-outline-danger btn-sm rounded-pill">🗑️</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ul class="list-group" id="failedList">
|
||||
<% if (failed.length === 0) { %>
|
||||
<li class="list-group-item ">No failed jobs</li>
|
||||
<% } %>
|
||||
|
||||
<% failed.forEach(job => { %>
|
||||
<li class="list-group-item">
|
||||
|
||||
<strong class="text-danger"><%= job.filename %></strong><br>
|
||||
<small><%= new Date(job.failed_at).toLocaleString() %></small><br>
|
||||
|
||||
<% if (job.output_log) { %>
|
||||
<details data-id="failed-<%= job._id %>">
|
||||
<summary class="text-danger">Show Error Log</summary>
|
||||
<pre class="log-box-error"><%= job.output_log %></pre>
|
||||
</details>
|
||||
<% } %>
|
||||
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Download activity</p>
|
||||
<h1 class="page-title">Your queue, at a glance.</h1>
|
||||
<p class="page-description">Follow active downloads and find the episode you need.</p>
|
||||
</div>
|
||||
<a class="button button-primary" href="/download">New download</a>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
/* ============================================================
|
||||
AUTO REFRESH STATUS
|
||||
============================================================ */
|
||||
<% if (typeof added !== "undefined" && added > 0) { %>
|
||||
<div class="notice notice-success" role="status"><strong><%= added %> <%= added === 1 ? "episode" : "episodes" %> added to the queue.</strong> Downloads will start when a worker is available and the queue is ready.</div>
|
||||
<% } %>
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (!bytes) return "Unknown";
|
||||
const units = ["B","KB","MB","GB","TB"];
|
||||
let i = 0;
|
||||
while (bytes >= 1024 && i < units.length - 1) {
|
||||
bytes /= 1024;
|
||||
i++;
|
||||
}
|
||||
return bytes.toFixed(1) + " " + units[i];
|
||||
}
|
||||
<%- include('partials/active-downloads') %>
|
||||
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
// Track open details by data-id
|
||||
const openMap = new Set(
|
||||
[...document.querySelectorAll("details")].filter(d => d.open).map(d => d.dataset.id)
|
||||
);
|
||||
<nav class="queue-overview" aria-label="Filter downloads by state">
|
||||
<% Object.entries(states).forEach(([state, info]) => { %>
|
||||
<a class="queue-stat<%= state === filters.state ? ' is-selected' : '' %>" href="<%= pageLink(state, 1) %>" data-state-link="<%= state %>"<%- state === filters.state ? ' aria-current="page"' : '' %>>
|
||||
<span class="queue-stat-label"><%= info.label %></span>
|
||||
<strong class="queue-stat-count" data-state-count="<%= state %>"><%= counts[state] %></strong>
|
||||
<span class="queue-stat-note"><%= info.note %></span>
|
||||
</a>
|
||||
<% }) %>
|
||||
</nav>
|
||||
|
||||
const res = await fetch("/status-data");
|
||||
const data = await res.json();
|
||||
<section class="panel" aria-labelledby="queue-title" id="queue-view" data-state="<%= filters.state %>" data-page="<%= pagination.page %>" data-page-size="<%= pagination.pageSize %>" data-query="<%= filters.q %>">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="queue-title"><%= selected.label %></h2>
|
||||
<p id="queue-state-note" class="muted"><%= filters.state === "failed" ? "An attempt can appear here even when its retained episode later completes. Check the queue and completed downloads before resubmitting." : filters.state === "processing" ? "File size shows the current file on disk. A claimed item may be resolving its source or transferring." : filters.state === "done" ? "Completed downloads stay in history until you clear their records." : "Waiting episodes are taken by available workers when verification is clear." %></p>
|
||||
</div>
|
||||
<div class="button-group">
|
||||
<form action="/clear-state" method="POST" id="queue-clear-state-form" data-confirm="<%= clearAction?.confirmation || '' %>"<%- clearAction ? '' : ' hidden' %>>
|
||||
<input type="hidden" name="state" id="queue-clear-state" value="<%= filters.state %>">
|
||||
<button class="button button-danger button-small" type="submit" id="queue-clear-state-button"<%- clearAction && counts[filters.state] > 0 ? '' : ' disabled' %>><%= clearAction?.label || 'Clear records' %></button>
|
||||
</form>
|
||||
<span class="badge badge-neutral" id="queue-active-protected"<%- clearAction ? ' hidden' : '' %>>Active downloads protected</span>
|
||||
<button class="button button-secondary button-small" type="button" id="queue-refresh">Refresh</button>
|
||||
<button class="button button-secondary button-small" type="button" id="queue-auto-refresh" aria-pressed="true">Auto refresh: on</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
/* Renderer helpers */
|
||||
const q = job => `
|
||||
<li class="list-group-item">
|
||||
<strong>${escapeHtml(job.filename)}</strong><br>
|
||||
<small>${escapeHtml(job.url)}</small><br>
|
||||
<small>${new Date(job.created_at).toLocaleString()}</small>
|
||||
</li>`;
|
||||
<div class="panel-body">
|
||||
<form method="GET" action="/status" id="queue-filter-form" class="queue-filters">
|
||||
<input type="hidden" name="state" id="queue-state" value="<%= filters.state %>">
|
||||
<div class="field queue-search">
|
||||
<label class="field-label" for="queue-query">Find a filename</label>
|
||||
<input class="field-input" type="search" id="queue-query" name="q" maxlength="100" value="<%= filters.q %>" placeholder="Search episode titles…" autocomplete="off">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="field-label" for="queue-page-size">Per page</label>
|
||||
<select class="field-input" name="pageSize" id="queue-page-size">
|
||||
<% [10, 25, 50].forEach(size => { %>
|
||||
<option value="<%= size %>"<%- size === pagination.pageSize ? ' selected' : '' %>><%= size %></option>
|
||||
<% }) %>
|
||||
</select>
|
||||
</div>
|
||||
<button class="button button-secondary" type="submit">Filter</button>
|
||||
<a class="button button-secondary" id="queue-clear-filter" href="<%= pageLink(filters.state, 1, '') %>"<%- filters.q ? '' : ' hidden' %>>Clear search</a>
|
||||
</form>
|
||||
<p class="field-hint" id="queue-feedback" role="status" aria-live="polite">Updates every 10 seconds while this page is visible.</p>
|
||||
</div>
|
||||
|
||||
const p = job => `
|
||||
<li class="list-group-item">
|
||||
<strong style="color:#58a6ff">${escapeHtml(job.filename)}</strong>
|
||||
<span class="spinner-border spinner-border-sm ms-1" style="color:#58a6ff"></span><br>
|
||||
<small>${escapeHtml(job.url)}</small><br>
|
||||
<small>${job.started_at ? 'Started' : 'Queued'}: ${new Date(job.started_at || job.created_at).toLocaleString()}</small><br>
|
||||
<small>Downloaded: ${formatBytes(job.fileSize || 0)}</small>
|
||||
${job.output_log ? `
|
||||
<details data-id="processing-${escapeHtml(job._id)}">
|
||||
<summary class="text-light">Live Log</summary>
|
||||
<pre class="log-box">${escapeHtml(job.output_log)}</pre>
|
||||
</details>` : ""}
|
||||
</li>`;
|
||||
<div class="queue-columns" aria-hidden="true">
|
||||
<span>Download</span><span>State</span><span>When</span><span>File on disk</span>
|
||||
</div>
|
||||
<ul class="job-list" id="queue-jobs" aria-label="<%= selected.label %>">
|
||||
<% items.forEach(job => { const stamp = job[selected.date] || job.created_at; const source = safeSource(job.url); %>
|
||||
<li class="job-row" data-job-id="<%= job._id %>" data-job-state="<%= filters.state %>">
|
||||
<div class="job-primary">
|
||||
<strong class="job-filename"><%= job.filename %></strong>
|
||||
<a class="job-source"<% if (source) { %> href="<%= source %>" target="_blank" rel="noopener noreferrer"<% } %>><%= sourceLabel(job.url) %></a>
|
||||
</div>
|
||||
<div class="job-state">
|
||||
<span class="badge <%= selected.badge %>"><%= selected.label %></span>
|
||||
<span class="job-error-category muted"><%= job.error_category || "" %></span>
|
||||
</div>
|
||||
<div class="job-time">
|
||||
<span class="job-time-label muted"><%= filters.state === "processing" && !job.started_at ? "Queued" : selected.dateLabel %></span>
|
||||
<time<% if (stamp) { %> datetime="<%= stamp %>"<% } %>><%= displayDate(stamp) %></time>
|
||||
</div>
|
||||
<div class="job-size">
|
||||
<span class="job-size-value"><%= bytes(job.fileSize) %></span>
|
||||
<small class="muted"><%= typeof job.fileSize === "number" ? "on disk" : "not available" %></small>
|
||||
</div>
|
||||
<details class="job-log"<%- job.output_log ? "" : " hidden" %>>
|
||||
<summary><%= filters.state === "failed" ? "View attempt log" : "View log" %></summary>
|
||||
<pre class="log-output" tabindex="0"><%= job.output_log || "" %></pre>
|
||||
</details>
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
<div class="empty-state" id="queue-empty"<%- items.length ? " hidden" : "" %>>
|
||||
<strong id="queue-empty-title"><%= filters.q ? "No matching filenames" : "No " + selected.label.toLowerCase() %></strong>
|
||||
<p id="queue-empty-message"><%= filters.q ? "Try a shorter search or choose another state." : filters.state === "queued" ? "Add a series or a single episode to get started." : filters.state === "processing" ? "No episodes are currently claimed by a worker." : filters.state === "done" ? "Successful downloads will appear here." : "No failed attempts are recorded." %></p>
|
||||
</div>
|
||||
|
||||
const d = job => `
|
||||
<li class="list-group-item">
|
||||
<strong class="text-success">${escapeHtml(job.filename)}</strong><br>
|
||||
<small>${new Date(job.finished_at).toLocaleString()}</small><br>
|
||||
<small>Size: ${formatBytes(job.fileSize || 0)}</small>
|
||||
${job.output_log ? `
|
||||
<details data-id="done-${escapeHtml(job._id)}">
|
||||
<summary class="text-light">Show Log</summary>
|
||||
<pre class="log-box-light">${escapeHtml(job.output_log)}</pre>
|
||||
</details>` : ""}
|
||||
</li>`;
|
||||
|
||||
const f = job => `
|
||||
<li class="list-group-item">
|
||||
<strong class="text-danger">${escapeHtml(job.filename)}</strong><br>
|
||||
<small>${new Date(job.failed_at).toLocaleString()}</small><br>
|
||||
${job.output_log ? `
|
||||
<details data-id="failed-${escapeHtml(job._id)}">
|
||||
<summary class="text-danger">Show Error Log</summary>
|
||||
<pre class="log-box-error">${escapeHtml(job.output_log)}</pre>
|
||||
</details>` : ""}
|
||||
</li>`;
|
||||
|
||||
/* Replace lists */
|
||||
queuedList.innerHTML = data.queued.length ? data.queued.map(q).join("") : `<li class="list-group-item ">No queued jobs</li>`;
|
||||
processingList.innerHTML = data.processing.length ? data.processing.map(p).join("") : `<li class="list-group-item ">Nothing processing</li>`;
|
||||
doneList.innerHTML = data.done.length ? data.done.map(d).join("") : `<li class="list-group-item ">No completed jobs</li>`;
|
||||
failedList.innerHTML = data.failed.length ? data.failed.map(f).join("") : `<li class="list-group-item ">No failed jobs</li>`;
|
||||
|
||||
// Restore open <details>
|
||||
document.querySelectorAll("details").forEach(d => {
|
||||
if (openMap.has(d.dataset.id)) {
|
||||
d.open = true;
|
||||
}
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error("Status refresh error:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text ?? "").replace(/[&<>"']/g, c =>
|
||||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])
|
||||
);
|
||||
}
|
||||
|
||||
setInterval(refreshStatus, 3000);
|
||||
|
||||
|
||||
</script>
|
||||
<nav class="queue-pagination" aria-label="Queue pages">
|
||||
<p id="queue-range" class="muted"><%= pagination.total ? ((pagination.page - 1) * pagination.pageSize + 1) + "–" + Math.min(pagination.page * pagination.pageSize, pagination.total) + " of " + pagination.total : "0 results" %><%= filters.q && pagination.total ? " matches" : "" %></p>
|
||||
<div class="button-group">
|
||||
<a class="button button-secondary button-small" href="<%= pageLink(filters.state, Math.max(1, pagination.page - 1)) %>" data-page-link="previous" aria-disabled="<%= pagination.page <= 1 %>"<%- pagination.page <= 1 ? ' tabindex="-1"' : '' %>>Previous</a>
|
||||
<span id="queue-page-label">Page <%= pagination.page %> of <%= pagination.totalPages %></span>
|
||||
<a class="button button-secondary button-small" href="<%= pageLink(filters.state, Math.min(pagination.totalPages, pagination.page + 1)) %>" data-page-link="next" aria-disabled="<%= pagination.page >= pagination.totalPages %>"<%- pagination.page >= pagination.totalPages ? ' tabindex="-1"' : '' %>>Next</a>
|
||||
</div>
|
||||
</nav>
|
||||
</section>
|
||||
|
||||
<p class="field-hint queue-action-help">The clear action applies to all records in the selected state, including records outside this search or page. Clearing history keeps downloaded files on disk.</p>
|
||||
<script src="/status.js" defer></script>
|
||||
<%- include("partials/footer") %>
|
||||
Reference in new issue
Block a user