phase 1 rework
This commit is contained in:
1 parent
211bfd174d
commit
20054198f3
38 files changed
+5001
-1019
No files matched your search
+89
-180
@@ -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 };
|
||||
Reference in new issue
Block a user