phase 1 rework

This commit is contained in:
admin_rb committed 2026-10-23 16:38:55 +02:00
1 parent 211bfd174d
commit 20054198f3
38 files changed
+5001 -1019

No files matched your search

+116 -156
View File
@@ -1,180 +1,140 @@
// controllers/pm2Controller.js
const { spawn } = require('child_process');
const { spawn } = require('node:child_process');
const path = require('node:path');
const { config } = require('../lib/config');
function runPm2Command(args, onData) {
function runPm2Command(args) {
return new Promise((resolve, reject) => {
const cmd = spawn('pm2', args);
const child = spawn('pm2', args, { cwd: config.projectRoot, stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
cmd.stdout.on('data', data => {
const s = data.toString();
stdout += s;
if (onData) onData({ type: 'stdout', data: s });
});
cmd.stderr.on('data', data => {
const s = data.toString();
stderr += s;
if (onData) onData({ type: 'stderr', data: s });
});
cmd.on('close', code => resolve({ code, stdout, stderr }));
cmd.on('error', err => reject(err));
let settled = false;
function finish(error, code) {
if (settled) return;
settled = true;
clearTimeout(timer);
if (error) reject(error);
else resolve({ code, stdout, stderr });
}
const timer = setTimeout(() => {
child.kill();
finish(new Error('PM2 did not respond in time.'));
}, 10000);
for (const [stream, field] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']]) {
stream.on('data', (data) => {
if (field === 'stdout') stdout += data.toString();
else stderr += data.toString();
if (stdout.length + stderr.length > 1024 * 1024) {
child.kill();
finish(new Error('PM2 response exceeded the supported size.'));
}
});
}
child.on('error', () => finish(new Error('PM2 is unavailable for this account.')));
child.on('close', (code) => finish(null, code));
});
}
function humanUptime(pm_uptime) {
if (!pm_uptime || pm_uptime <= 0) return '—';
const diff = Date.now() - pm_uptime;
if (diff < 1000) return '0s';
const sec = Math.floor(diff / 1000);
const days = Math.floor(sec / 86400);
const hrs = Math.floor((sec % 86400) / 3600);
const mins = Math.floor((sec % 3600) / 60);
const parts = [];
if (days) parts.push(days + 'd');
if (hrs) parts.push(hrs + 'h');
if (mins) parts.push(mins + 'm');
if (!parts.length) parts.push((sec % 60) + 's');
return parts.join(' ');
function humanUptime(timestamp) {
if (!timestamp || timestamp <= 0) return '—';
const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000));
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return [days && `${days}d`, hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' ') || `${seconds % 60}s`;
}
function normalizeProcess(p) {
const pid =
p.pid ||
(p.pm2_env && p.pm2_env.pm_pid) ||
(p.pm2_env && p.pm2_env.pmx && p.pm2_env.pmx.pid) ||
null;
const status = (p.pm2_env && p.pm2_env.status) || p.status || 'unknown';
let cpu = null, memoryMB = null;
if (p.monit) {
cpu = typeof p.monit.cpu === 'number' ? p.monit.cpu : null;
memoryMB = typeof p.monit.memory === 'number' ? Math.round(p.monit.memory / 1024 / 1024) : null;
} else if (p.pm2_env && p.pm2_env.axm_monitor) {
cpu = p.pm2_env.axm_monitor.cpu;
memoryMB = p.pm2_env.axm_monitor.memory ? Math.round(p.pm2_env.axm_monitor.memory / 1024 / 1024) : null;
} else if (p.pm2_env && p.pm2_env.monit) {
cpu = p.pm2_env.monit.cpu;
memoryMB = p.pm2_env.monit.memory ? Math.round(p.pm2_env.monit.memory / 1024 / 1024) : null;
}
const pm_uptime = (p.pm2_env && p.pm2_env.pm_uptime) || (p.pm_uptime || 0);
const uptime = humanUptime(pm_uptime);
function normalizeProcess(process) {
const env = process.pm2_env || {};
const cpu = process.monit?.cpu;
const memory = process.monit?.memory;
return {
name: p.name || (p.pm2_env && p.pm2_env.name) || '—',
pid: pid || '—',
pm_id: (p.pm2_env && p.pm2_env.pm_id) || (p.pm_id !== undefined ? String(p.pm_id) : '—'),
status,
cpu: cpu != null ? Number(cpu).toFixed(1) + '%' : '—',
memoryMB: memoryMB != null ? memoryMB + ' MB' : '—',
uptime,
execPath:
(p.pm2_env && p.pm2_env.pm_exec_path) ||
(p.pm2_env && p.pm2_env.exec_interpreter) ||
'—',
raw: p
name: String(process.name || env.name || '—'),
pid: process.pid || '—',
pm_id: String(process.pm_id ?? env.pm_id ?? '—'),
status: String(env.status || process.status || 'unknown'),
cpu: typeof cpu === 'number' ? `${cpu.toFixed(1)}%` : '—',
memoryMB: typeof memory === 'number' ? `${Math.round(memory / 1024 / 1024)} MB` : '—',
uptime: humanUptime(env.pm_uptime),
execPath: env.pm_exec_path || '—',
};
}
// ===============================
// VIEW: Render UI
// ===============================
exports.getManage = async (req, res, next) => {
try {
const { stdout } = await runPm2Command(['jlist']);
let processes = [];
try {
const parsed = JSON.parse(stdout || '[]');
processes = Array.isArray(parsed) ? parsed.map(normalizeProcess) : [];
} catch (e) {
processes = [];
}
res.render('pm2', { title: 'PM2 Manager', processes });
} catch (err) {
next(err);
}
};
function validName(name) {
return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all';
}
// ===============================
// JSON Process List
// ===============================
exports.listJson = async (req, res) => {
try {
const { stdout } = await runPm2Command(['jlist']);
let processes = [];
function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
function managed(process) {
const executable = process.pm2_env?.pm_exec_path;
return typeof executable === 'string' && path.resolve(executable) === settings.workerScript;
}
async function processes() {
const response = await run(['jlist']);
if (response.code !== 0) throw new Error('PM2 process list is unavailable.');
let parsed;
try { parsed = JSON.parse(response.stdout); } catch { throw new Error('PM2 returned an invalid process list.'); }
if (!Array.isArray(parsed)) throw new Error('PM2 returned an invalid process list.');
return parsed;
}
async function resolveManagedProcess(name) {
if (!validName(name)) return null;
const matches = (await processes()).filter((process) => managed(process) && (process.name || process.pm2_env?.name) === name);
if (matches.length !== 1) return null;
const id = matches[0].pm_id ?? matches[0].pm2_env?.pm_id;
if (!Number.isInteger(id) || id < 0) return null;
return { ...normalizeProcess(matches[0]), pm_id: String(id) };
}
async function getManage(req, res, next) {
try {
const parsed = JSON.parse(stdout || '[]');
processes = Array.isArray(parsed) ? parsed.map(normalizeProcess) : [];
res.render('pm2', { title: 'Proxer Workers', processes: (await processes()).filter(managed).map(normalizeProcess) });
} catch (error) { next(error); }
}
async function listJson(req, res) {
try {
res.json({ ok: true, processes: (await processes()).filter(managed).map(normalizeProcess) });
} catch {
processes = [];
res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' });
}
res.json({ ok: true, processes });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
};
// ===============================
// COMMAND EXECUTION
// ===============================
exports.postCommand = async (req, res) => {
// expected body: { cmd:'create'|'start'|'stop'|'restart'|'delete'|'save', name?, scriptPath? }
const allowed = new Set([
'start', 'stop', 'restart', 'delete', 'save', 'create'
]);
const { cmd, name, scriptPath } = req.body;
if (!allowed.has(cmd)) {
return res.status(400).json({ ok: false, error: 'Invalid command' });
}
try {
let args = [];
// -------------------------------
// CREATE = start script with name
// -------------------------------
if (cmd === 'create') {
if (!scriptPath || !name) {
return res.status(400).json({ ok: false, error: 'scriptPath and name required' });
}
if (!/^[\w-]+$/.test(name)) {
return res.status(400).json({ ok: false, error: 'Invalid process name' });
}
args = ['start', scriptPath, '--name', name];
console.log(args)
async function postCommand(req, res) {
const { cmd, name, scriptPath } = req.body || {};
if (!['start', 'stop', 'restart', 'delete', 'save', 'create'].includes(cmd)) {
return res.status(400).json({ ok: false, error: 'Invalid command.' });
}
// -------------------------------
// SAVE
// -------------------------------
else if (cmd === 'save') {
args = ['save'];
if (cmd === 'save') {
return res.status(409).json({ ok: false, error: 'Saving the full PM2 process list is a host-level operation. Run pm2 save as the download user during deployment.' });
}
// -------------------------------
// start/stop/restart/delete
// -------------------------------
else {
if (!name) {
return res.status(400).json({ ok: false, error: 'name is required' });
if (!validName(name)) return res.status(400).json({ ok: false, error: 'Invalid worker name.' });
try {
let args;
if (cmd === 'create') {
if (scriptPath !== undefined && scriptPath !== settings.workerScript) {
return res.status(400).json({ ok: false, error: 'The worker executable is configured by the server.' });
}
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'];
} else {
const worker = await resolveManagedProcess(name);
if (!worker) return res.status(404).json({ ok: false, error: 'The selected downloader worker was not found.' });
args = [cmd, worker.pm_id];
}
if (!/^[\w-]+$/.test(name)) {
return res.status(400).json({ ok: false, error: 'Invalid process name' });
}
args = [cmd, name];
const { code } = await run(args);
return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code,
message: code === 0 ? 'Worker command completed.' : 'Worker command failed. Check the supervisor on the server.' });
} catch {
return res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' });
}
const { code, stdout, stderr } = await runPm2Command(args);
res.json({ ok: code === 0, code, stdout, stderr });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
};
return { getManage, listJson, postCommand, resolveManagedProcess };
}
module.exports = { ...createPm2Controller(), createPm2Controller, normalizeProcess, validName };
+89 -180
View File
@@ -1,199 +1,108 @@
const fs = require("node:fs/promises");
const { getDb } = require("../lib/mongo");
const fs = require("fs");
const path = require("path");
const { config } = require("../lib/config");
const {
ValidationError, STATUS_READ_PROJECTION, buildQueueJobs, toPublicJob, validateOutputTarget,
} = require("../lib/jobValidation");
exports.enqueue = async (req, res) => {
try {
const db = await getDb();
const body = req.body;
function createQueueController(dependencies = {}) {
const connect = dependencies.getDb || getDb;
const settings = dependencies.config || config;
const now = dependencies.now || (() => new Date());
// Token always required
if (!body.token) throw new Error("token required");
const token_prefix = process.env.TOKEN_PREFIX;
const token = token_prefix + body.token;
// =========================================
// VIDEO MODE
// =========================================
if (body.mode === "video") {
if (!body.url) throw new Error("url required");
var filename;
if (!body.filename) {
let split_slash = body.url.split("/");
let split_hash =
`${split_slash[4]} E${split_slash[5]} ${split_slash[6]}`.split("#");
filename = split_hash[0];
console.log(filename);
async function enqueue(req, res) {
try {
const jobs = await buildQueueJobs(req.body, settings, now);
const db = await connect();
if (jobs.length === 1 && req.body.mode === "video") {
await db.collection("queue").insertOne(jobs[0]);
} else {
filename = body.filename;
await db.collection("queue").bulkWrite(jobs.map(document => ({ insertOne: { document } })));
}
await db.collection("queue").insertOne({
url: body.url,
token,
filename,
created_at: new Date(),
return res.redirect("/status");
} 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.",
details: null,
});
return res.redirect("/status");
}
// =========================================
// SERIES MODE
// =========================================
if (body.mode === "series") {
if (!body.id) throw new Error("id required");
if (!body.language) throw new Error("language required");
if (!body.episode_from) throw new Error("episode_from required");
if (!body.episode_to) throw new Error("episode_to required");
const id = body.id;
const lang = body.language;
const name = body.name?.trim() || null;
const from = parseInt(body.episode_from);
const to = parseInt(body.episode_to);
if (isNaN(from) || from <= 0)
throw new Error("episode_from must be a valid number");
if (isNaN(to) || to < from)
throw new Error("episode_to must be >= episode_from");
// Insert one queue item per episode
const ops = [];
// Determine padding width based on the highest episode number
const pad = String(to).length;
for (let ep = from; ep <= to; ep++) {
const epStr = String(ep).padStart(pad, "0");
const url = `https://proxer.me/watch/${id}/${ep}/${lang}`;
const filename = name
? `${name}E${epStr}_${lang}`
: `${id}E${epStr}_${lang}`;
ops.push({
insertOne: {
document: {
url,
token,
filename,
created_at: new Date(),
},
},
});
}
await db.collection("queue").bulkWrite(ops);
return res.redirect("/status");
}
throw new Error("Invalid mode");
} catch (err) {
res.render("error", {
title: "Enqueue Failed",
message: err.message,
details: err.stack,
});
}
};
exports.status = async (req, res) => {
const db = await getDb();
const queued = await db
.collection("queue")
.find({ $or: [{ processing: { $exists: false } }, { processing: false }] })
.sort({ created_at: 1 })
.toArray();
const processing = await db
.collection("queue")
.find({ processing: true })
.sort({ created_at: 1 })
.toArray();
const done = await db
.collection("done")
.find({})
.sort({ finished_at: -1 })
.toArray();
const failed = await db
.collection("failed")
.find({})
.sort({ failed_at: -1 })
.toArray();
const settings =
(await db.collection("settings").findOne({ _id: "global" })) || {};
console.log;
res.render("status", {
queued,
processing,
finished: done,
failed,
global: settings,
});
};
exports.statusData = async (req, res) => {
const db = await getDb();
const queued = await db
.collection("queue")
.find({ processing: { $ne: true } })
.sort({ created_at: 1 })
.toArray();
const processing = await db
.collection("queue")
.find({ processing: true })
.sort({ created_at: 1 })
.toArray();
const done = await db
.collection("done")
.find({})
.sort({ finished_at: -1 })
.toArray();
const failed = await db
.collection("failed")
.find({})
.sort({ failed_at: -1 })
.toArray();
// File sizes
const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP";
for (const list of [processing, done]) {
for (const job of list) {
async function readStatus() {
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]) {
try {
const stat = fs.statSync(path.join(OUTPUT_DIR, `${job.filename}.mp4`));
job.fileSize = stat.size;
const target = await validateOutputTarget(settings.outputDir, job.filename);
const stat = await fs.lstat(target);
job.fileSize = stat.isFile() && !stat.isSymbolicLink() ? stat.size : null;
} 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,
},
};
}
// Fetch global settings
const settings = await db.collection("settings").findOne({ _id: "global" }) || {};
settings.captcha_blocked = !!settings.captcha_blocked;
async function status(req, res, next) {
try {
const snapshot = await readStatus();
return res.render("status", { ...snapshot, finished: snapshot.done });
} catch (error) {
return next(error);
}
}
// Send JSON including global
res.json({
queued,
processing,
done,
failed,
global: settings,
});
};
async function statusData(req, res, next) {
try {
res.set("Cache-Control", "no-store");
return res.json(await readStatus());
} catch (error) {
return next(error);
}
}
function clearProcessing(req, res) {
return res.status(409).render("error", {
title: "Active downloads are protected",
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,
});
}
async function clearCaptcha(req, res, next) {
try {
const db = await connect();
await db.collection("settings").updateOne({ _id: "global" }, {
$set: { captcha_blocked: false },
$unset: { pause_reason: "" },
});
return res.redirect("/status");
} catch (error) {
return next(error);
}
}
return { enqueue, status, statusData, clearProcessing, clearCaptcha };
}
module.exports = { ...createQueueController(), createQueueController };