jesus christ

This commit is contained in:
DeSqBlocki committed 2025-12-06 18:07:19 +01:00
1 parent d97600122e
commit 49309d6733
9 files changed
+505 -295

No files matched your search

+27 -24
View File
@@ -130,12 +130,15 @@ exports.status = async (req, res) => {
.sort({ failed_at: -1 }) .sort({ failed_at: -1 })
.toArray(); .toArray();
const settings =
(await db.collection("settings").findOne({ _id: "global" })) || {};
console.log;
res.render("status", { res.render("status", {
title: "Queue Status",
queued, queued,
processing, processing,
finished: done, finished: done,
failed, failed,
global: settings,
}); });
}; };
@@ -166,31 +169,31 @@ exports.statusData = async (req, res) => {
.sort({ failed_at: -1 }) .sort({ failed_at: -1 })
.toArray(); .toArray();
// =========================== // File sizes
// FILE SIZE FOR DONE const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP";
// =========================== for (const list of [processing, done]) {
for (let job of done) { for (const job of list) {
try { try {
const filePath = path.join(process.env.OUTPUT_DIR, `${job.filename}.mp4`); const stat = fs.statSync(path.join(OUTPUT_DIR, `${job.filename}.mp4`));
const stats = fs.statSync(filePath); job.fileSize = stat.size;
job.fileSize = stats.size; } catch {
} catch { job.fileSize = null;
job.fileSize = null; }
} }
} }
// =========================== // Fetch global settings
// FILE SIZE FOR PROCESSING const settings = await db.collection("settings").findOne({ _id: "global" }) || {};
// =========================== settings.captcha_blocked = !!settings.captcha_blocked;
for (let job of processing) {
try {
const filePath = path.join(process.env.OUTPUT_DIR, `${job.filename}.mp4`);
const stats = fs.statSync(filePath);
job.fileSize = stats.size;
} catch {
job.fileSize = null;
}
}
res.json({ queued, processing, done, failed }); // Send JSON including global
res.json({
queued,
processing,
done,
failed,
global: settings,
});
}; };
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+45
View File
@@ -112,6 +112,51 @@ button,
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35); 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 ALERTS
=============================== */ =============================== */
+80 -57
View File
@@ -14,52 +14,74 @@ const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP/";
const client = new MongoClient(MONGO_URI); const client = new MongoClient(MONGO_URI);
let queueCol, doneCol, failedCol; let queueCol, doneCol, failedCol;
// ========================
// HELPER
// ========================
async function isBlocked() {
const settings = await queueCol.db
.collection("settings")
.findOne({ _id: "global" });
return settings?.captcha_blocked === true;
}
// ======================== // ========================
// RUN A JOB // RUN A JOB
// ======================== // ========================
function runJob(job) { async function runJob(job) {
return new Promise((resolve) => { try {
const venvPython = process.env.VENV_PYTHON const cmd = [
"python3",
path.join(__dirname, "proxer-dl-video.py"),
"-u", job.url,
"-f", job.filename,
"-t", job.token,
"-o", process.env.OUTPUT_DIR
];
const cleanName = job.filename.replace(".mp4", ""); const proc = spawn(cmd[0], cmd.slice(1));
const safeToken = job.token.replace(/^"+|"+$/g, '');
const scriptPath = 'scripts/proxer-dl-video.py'
const command = `${venvPython} ${scriptPath} -u "${job.url}" -f "${cleanName}" -t "${safeToken}" -o "${OUTPUT_DIR}"`;
console.log("Running:", command); let output = "";
proc.stdout.on("data", d => output += d.toString());
proc.stderr.on("data", d => output += d.toString());
exec(command, async (error, stdout, stderr) => { const exitCode = await new Promise(resolve =>
const outputLog = `${stdout}\n${stderr}`.trim(); proc.on("close", resolve)
);
try { // ========== CAPTCHA / ERROR DETECTION ==========
if (error) { const suspicious =
console.error(`FAILED: ${cleanName}`); exitCode !== 0 ||
await failedCol.insertOne({ output.toLowerCase().includes("captcha") ||
filename: job.filename, output.toLowerCase().includes("403") ||
url: job.url, output.toLowerCase().includes("blocked") ||
failed_at: new Date(), output.toLowerCase().includes("token") ||
output_log: outputLog, output.toLowerCase().includes("forbidden");
return_code: error.code,
}); if (suspicious) {
} else { console.log("⛔ CAPTCHA or fatal error detected, notifying system");
console.log(`SUCCESS: ${cleanName}`); await failedCol.insertOne({
await doneCol.insertOne({ filename: job.filename,
filename: job.filename, failed_at: new Date(),
url: job.url, output_log: output
finished_at: new Date(), });
output_log: outputLog, return true; // signals worker to halt globally
result: "success", }
});
} // Success
// Remove from queue in both cases await doneCol.insertOne({
await queueCol.deleteOne({ _id: job._id }); filename: job.filename,
} catch (dbErr) { finished_at: new Date(),
console.error("DB error:", dbErr); output_log: output
} finally {
resolve(); // resolve promise when done
}
}); });
});
await queueCol.deleteOne({ _id: job._id });
return false;
} catch (err) {
console.error("Worker crash:", err);
return true;
}
} }
@@ -78,29 +100,31 @@ async function main() {
failedCol = db.collection("failed"); failedCol = db.collection("failed");
while (true) { while (true) {
if (await isBlocked()) {
console.log("⛔ CAPTCHA BLOCK — Worker paused");
await new Promise((r) => setTimeout(r, 5000));
continue;
}
const job = await queueCol.findOneAndUpdate( const job = await queueCol.findOneAndUpdate(
{ { processing: { $ne: true } }, // prevents grabbing others
// Only pick jobs NOT being processed { $set: { processing: true } },
$or: [ { sort: { created_at: 1 }, returnDocument: "after" }
{ processing: { $exists: false } },
{ processing: false }
]
},
{
// Atomically claim job
$set: { processing: true, started_at: new Date() }
},
{
sort: { created_at: 1 },
returnDocument: "after"
}
); );
if (job && job.token) { if (job && job.token) {
await runJob(job); const failed = await runJob(job);
if (failed === true) {
await queueCol.db
.collection("settings")
.updateOne(
{ _id: "global" },
{ $set: { captcha_blocked: true } },
{ upsert: true }
);
}
} else { } else {
// No available job, wait a bit await new Promise((resolve) => setTimeout(resolve, 1000));
await new Promise(resolve => setTimeout(resolve, 1000));
} }
} }
} catch (err) { } catch (err) {
@@ -109,4 +133,3 @@ async function main() {
} }
main(); main();
+30 -2
View File
@@ -1,13 +1,41 @@
const express = require("express"); const express = require("express");
const router = express.Router(); const router = express.Router();
const queue = require("../controllers/queueController"); const queue = require("../controllers/queueController");
const { getDb } = require("../lib/mongo");
// =======================
// HOME PAGE
// =======================
router.get("/", (req, res) => router.get("/", (req, res) =>
res.render("index", { title: "Proxer Downloader" }) res.render("index", { title: "Proxer Downloader" })
); );
router.post("/queue", queue.enqueue); // <-- FIXED // =======================
router.get("/status-data", queue.statusData); // QUEUE REQUEST
// =======================
router.post("/queue", queue.enqueue);
// =======================
// STATUS (SSR RENDER)
// =======================
router.get("/status", queue.status); router.get("/status", queue.status);
// =======================
// STATUS JSON API
// =======================
router.get("/status-data", queue.statusData);
// =======================
// CAPTCHA CLEAR
// =======================
router.post("/clear-captcha", async (req, res) => {
const db = await getDb();
await db.collection("settings").updateOne(
{ _id: "global" },
{ $set: { captcha_blocked: false } }
);
// Redirect to status, controller fetches everything
res.redirect("/status");
});
module.exports = router; module.exports = router;
+6 -1
View File
@@ -18,7 +18,12 @@ app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(morgan('dev'));
// Morgan: log only non-static requests
app.use(morgan(':method :url :status :res[content-length] - :response-time ms', {
skip: (req) => req.url.startsWith('/assets') || req.url.startsWith('/favicon.ico')
}));
// Routes // Routes
app.use('/', indexRouter); app.use('/', indexRouter);
+120 -88
View File
@@ -1,99 +1,131 @@
<%- include("partials/header") %> <%- include("partials/header") %>
<div class="card card-dark p-4"> <div class="card card-dark p-4">
<div class="d-flex justify-content-center mb-3"> <div class="d-flex justify-content-center mb-4">
<div class="form-check form-switch"> <div class="pill-toggle" id="pillToggle">
<input class="form-check-input" type="checkbox" id="modeToggle"> <div class="pill-option active" data-mode="series" id="pillSeries">
<label class="form-check-label " for="modeToggle" id="modeLabel">Series</label> Series
</div> </div>
<div class="pill-option" data-mode="video" 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" />
<!-- SERIES FIELDS -->
<div id="seriesFields">
<div class="mb-3">
<label class="form-label">Series ID</label>
<input class="form-control" name="id" placeholder="12345" />
</div>
<!-- UPDATED: EPISODE RANGE (FROM / TO) -->
<div class="mb-3">
<label class="form-label">Episode Range</label>
<div class="row">
<div class="col">
<input
class="form-control"
name="episode_from"
placeholder="From (e.g. 1)"
/>
</div>
<div class="col">
<input
class="form-control"
name="episode_to"
placeholder="To (e.g. 12)"
/>
</div>
</div> </div>
</div>
<form method="POST" action="/queue" id="jobForm"> <div class="mb-3">
<input type="hidden" name="mode" id="modeInput" value="series"> <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>
<!-- SERIES FIELDS --> <div class="mb-3">
<div id="seriesFields"> <label class="form-label">Name (optional)</label>
<div class="mb-3"> <input
<label class="form-label">Series ID</label> class="form-control"
<input class="form-control" name="id" placeholder="12345"> name="name"
</div> placeholder="OnePiece_1_engsub"
/>
<!-- UPDATED: EPISODE RANGE (FROM / TO) --> </div>
<div class="mb-3">
<label class="form-label">Episode Range</label>
<div class="row">
<div class="col">
<input class="form-control" name="episode_from" placeholder="From (e.g. 1)">
</div>
<div class="col">
<input class="form-control" name="episode_to" placeholder="To (e.g. 12)">
</div>
</div>
</div>
<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>
<div class="mb-3">
<label class="form-label">Name (optional)</label>
<input class="form-control" name="name" placeholder="OnePiece_1_engsub">
</div>
</div>
<!-- VIDEO FIELDS -->
<div id="videoFields" style="display:none">
<div class="mb-3">
<label class="form-label">Video URL</label>
<input class="form-control" name="url" placeholder="https://proxer.me/watch/...">
</div>
<div class="mb-3">
<label class="form-label">Filename (optional)</label>
<input class="form-control" name="filename" placeholder="MyVideo.mp4">
</div>
</div>
<!-- TOKEN -->
<div class="mb-3">
<label class="form-label">Token suffix</label>
<input class="form-control" name="token" placeholder="user-token">
<div class="form-text">Full token = TOKEN_PREFIX + this value</div>
</div>
<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> </div>
<script> <!-- VIDEO FIELDS -->
const toggle = document.getElementById('modeToggle'); <div id="videoFields" style="display: none">
const modeLabel = document.getElementById('modeLabel'); <div class="mb-3">
const modeInput = document.getElementById('modeInput'); <label class="form-label">Video URL</label>
const seriesFields = document.getElementById('seriesFields'); <input
const videoFields = document.getElementById('videoFields'); class="form-control"
name="url"
placeholder="https://proxer.me/watch/..."
/>
</div>
toggle.addEventListener('change', () => { <div class="mb-3">
if (toggle.checked) { <label class="form-label">Filename (optional)</label>
modeLabel.innerText = 'Video'; <input class="form-control" name="filename" placeholder="MyVideo.mp4" />
modeInput.value = 'video'; </div>
seriesFields.style.display = 'none'; </div>
videoFields.style.display = '';
} else { <!-- TOKEN -->
modeLabel.innerText = 'Series'; <div class="mb-3">
modeInput.value = 'series'; <label class="form-label">Token suffix</label>
seriesFields.style.display = ''; <input class="form-control" name="token" placeholder="user-token" />
videoFields.style.display = 'none'; <div class="form-text">Full token = TOKEN_PREFIX + this value</div>
} </div>
});
<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>
<script>
const pill = document.getElementById("pillToggle");
const indicator = document.getElementById("pillIndicator");
const btnSeries = document.getElementById("pillSeries");
const btnVideo = document.getElementById("pillVideo");
const modeInput = document.getElementById("modeInput");
const seriesFields = document.getElementById("seriesFields");
const videoFields = document.getElementById("videoFields");
function updateMode(mode) {
if (mode === "series") {
indicator.style.transform = "translateX(0)";
btnSeries.classList.add("active");
btnVideo.classList.remove("active");
modeInput.value = "series";
seriesFields.style.display = "";
videoFields.style.display = "none";
} else {
indicator.style.transform = "translateX(100%)";
btnVideo.classList.add("active");
btnSeries.classList.remove("active");
modeInput.value = "video";
seriesFields.style.display = "none";
videoFields.style.display = "";
}
}
btnSeries.onclick = () => updateMode("series");
btnVideo.onclick = () => updateMode("video");
</script> </script>
<%- include("partials/footer") %> <%- include("partials/footer") %>
+45 -12
View File
@@ -1,18 +1,51 @@
<!doctype html> <!doctype html>
<html> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Proxer-Downloader</title> <title>Proxer-Downloader</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="/style.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="/style.css">
</head> </head>
<body> <body>
<div class="container py-4">
<!-- CAPTCHA ALERT (initially hidden, will be toggled by JS) -->
<div id="captcha-alert" class="alert alert-danger text-center m-0" style="display: <%= (global && global.captcha_blocked) ? 'block' : 'none' %>;">
⚠ Human Action Required: Proxer CAPTCHA triggered. Workers paused until cleared.
<form id="clear-captcha-form" action="/clear-captcha" method="POST" class="d-inline ms-2">
<button class="btn btn-danger btn-sm">⚠ Clear CAPTCHA</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"> <header class="d-flex justify-content-between align-items-center mb-4">
<h1>Proxer-Downloader</h1> <h1>Proxer-Downloader</h1>
<nav> <nav class="d-flex gap-2">
<a class="btn btn-outline-light" href="/">Home</a> <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="/status">Status</a>
</nav> </nav>
</header> </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');
if (data.global && data.global.captcha_blocked) {
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>
+152 -111
View File
@@ -1,6 +1,7 @@
<%- include("partials/header") %> <%- include("partials/header") %>
<div class="row"> <div class="row">
<!-- ======================= --> <!-- ======================= -->
<!-- QUEUED --> <!-- QUEUED -->
<!-- ======================= --> <!-- ======================= -->
@@ -13,7 +14,8 @@
<small><%= job.url %></small><br /> <small><%= job.url %></small><br />
<small><%= new Date(job.created_at).toLocaleString() %></small> <small><%= new Date(job.created_at).toLocaleString() %></small>
</li> </li>
<% }) %> <% if (queued.length === 0) { %> <% }) %>
<% if (queued.length === 0) { %>
<li class="list-group-item">No queued jobs</li> <li class="list-group-item">No queued jobs</li>
<% } %> <% } %>
</ul> </ul>
@@ -23,40 +25,35 @@
<!-- PROCESSING --> <!-- PROCESSING -->
<!-- ======================= --> <!-- ======================= -->
<div class="col-md-3"> <div class="col-md-3">
<h3 style="color: #58a6ff">Processing</h3> <h3 style="color:#58a6ff">Processing</h3>
<ul class="list-group" id="processingList"> <ul class="list-group" id="processingList">
<% processing.forEach(job => { %> <% processing.forEach(job => { %>
<li class="list-group-item"> <li class="list-group-item">
<strong style="color: #58a6ff"><%= job.filename %></strong> <strong style="color:#58a6ff"><%= job.filename %></strong>
<span <span class="spinner-border spinner-border-sm ms-2" style="color:#58a6ff"></span><br>
class="spinner-border spinner-border-sm ms-2" <small><%= job.url %></small><br>
style="color: #58a6ff"
></span>
<br />
<small><%= job.url %></small><br />
<small>Started: <%= new Date(job.created_at).toLocaleString() %></small> <small>Started: <%= new Date(job.created_at).toLocaleString() %></small>
<% if (job.fileSize) { %>
<br><small>Downloaded: <%= job.fileSize %></small>
<% } %>
<% if (job.output_log) { %> <% if (job.output_log) { %>
<details class="mt-2"> <details class="mt-2">
<summary class="text-light">Live Log</summary> <summary class="text-light">Live Log</summary>
<pre <pre style="background:#001122; color:#9cf; padding:10px; border-radius:5px; white-space:pre-wrap;">
style="
background: #001122;
color: #9cf;
padding: 10px;
border-radius: 5px;
white-space: pre-wrap;
"
>
<%= job.output_log %> <%= job.output_log %>
</pre </pre>
>
</details> </details>
<% } %> <% } %>
</li> </li>
<% }) %> <% if (processing.length === 0) { %> <% }) %>
<% if (processing.length === 0) { %>
<li class="list-group-item">Nothing processing</li> <li class="list-group-item">Nothing processing</li>
<% } %> <% } %>
</ul> </ul>
</div> </div>
@@ -66,32 +63,32 @@
<div class="col-md-3"> <div class="col-md-3">
<h3 class="text-success">Done</h3> <h3 class="text-success">Done</h3>
<ul class="list-group" id="doneList"> <ul class="list-group" id="doneList">
<% finished.forEach(job => { %> <% finished.forEach(job => { %>
<li class="list-group-item"> <li class="list-group-item">
<strong class="text-success"><%= job.filename %></strong><br /> <strong class="text-success"><%= job.filename %></strong><br />
<small><%= new Date(job.finished_at).toLocaleString() %></small><br /> <small><%= new Date(job.finished_at).toLocaleString() %></small><br>
<% if (job.fileSize) { %>
<small>Size: <%= job.fileSize %></small><br>
<% } %>
<% if (job.output_log) { %> <% if (job.output_log) { %>
<details class="mt-2"> <details class="mt-2">
<summary class="text-light">Show Log</summary> <summary class="text-light">Show Log</summary>
<pre <pre style="background:#222; color:#e0e0e0; padding:10px; border-radius:5px; white-space:pre-wrap;">
style="
background: #222;
color: #e0e0e0;
padding: 10px;
border-radius: 5px;
white-space: pre-wrap;
"
>
<%= job.output_log %> <%= job.output_log %>
</pre </pre>
>
</details> </details>
<% } %> <% } %>
</li> </li>
<% }) %> <% if (finished.length === 0) { %> <% }) %>
<% if (finished.length === 0) { %>
<li class="list-group-item">No completed jobs</li> <li class="list-group-item">No completed jobs</li>
<% } %> <% } %>
</ul> </ul>
</div> </div>
@@ -101,106 +98,150 @@
<div class="col-md-3"> <div class="col-md-3">
<h3 class="text-danger">Failed</h3> <h3 class="text-danger">Failed</h3>
<ul class="list-group" id="failedList"> <ul class="list-group" id="failedList">
<% failed.forEach(job => { %> <% failed.forEach(job => { %>
<li class="list-group-item"> <li class="list-group-item">
<strong class="text-danger"><%= job.filename %></strong><br /> <strong class="text-danger"><%= job.filename %></strong><br />
<small><%= new Date(job.failed_at).toLocaleString() %></small><br /> <small><%= new Date(job.failed_at).toLocaleString() %></small><br>
<% if (job.output_log) { %> <% if (job.output_log) { %>
<details class="mt-2"> <details class="mt-2">
<summary class="text-danger">Show Error Log</summary> <summary class="text-danger">Show Error Log</summary>
<pre <pre style="background:#330000; color:#ffb3b3; padding:10px; border-radius:5px; white-space:pre-wrap;">
style="
background: #330000;
color: #ffb3b3;
padding: 10px;
border-radius: 5px;
white-space: pre-wrap;
"
>
<%= job.output_log %> <%= job.output_log %>
</pre </pre>
>
</details> </details>
<% } %> <% } %>
</li> </li>
<% }) %> <% if (failed.length === 0) { %> <% }) %>
<% if (failed.length === 0) { %>
<li class="list-group-item">No failed jobs</li> <li class="list-group-item">No failed jobs</li>
<% } %> <% } %>
</ul> </ul>
</div> </div>
</div> </div>
<!-- ======================= --> <!-- ======================= -->
<!-- AUTO-REFRESH SCRIPT --> <!-- AUTO-REFRESH SCRIPT -->
<!-- ======================= --> <!-- ======================= -->
<script> <script>
async function refreshStatus() { function formatBytes(bytes) {
try { if (!bytes) return "Unknown";
const res = await fetch("/status-data"); const units = ["B","KB","MB","GB","TB"];
const data = await res.json(); let i = 0;
while (bytes >= 1024 && i < units.length - 1) {
// Helper for templates bytes /= 1024;
function renderQueued(job) { i++;
return `
<li class="list-group-item">
<strong>${job.filename}</strong><br>
<small>${job.url}</small><br>
<small>${new Date(job.created_at).toLocaleString()}</small>
</li>`;
}
function renderProcessing(job) {
return `
<li class="list-group-item">
<strong style="color:#58a6ff">${job.filename}</strong>
<span class="spinner-border spinner-border-sm ms-2" style="color:#58a6ff"></span><br>
<small>${job.url}</small><br>
<small>Started: ${new Date(job.created_at).toLocaleString()}</small><br>
<small>Downloaded: ${formatBytes(job.fileSize)}</small>
</li>`;
}
function renderDone(job) {
return `
<li class="list-group-item">
<strong class="text-success">${job.filename}</strong><br>
<small>${new Date(job.finished_at).toLocaleString()}</small>
</li>`;
}
function renderFailed(job) {
return `
<li class="list-group-item">
<strong class="text-danger">${job.filename}</strong><br>
<small>${new Date(job.failed_at).toLocaleString()}</small>
</li>`;
}
// Update UI lists
document.getElementById("queuedList").innerHTML = data.queued.length
? data.queued.map(renderQueued).join("")
: `<li class="list-group-item ">No queued jobs</li>`;
document.getElementById("processingList").innerHTML = data.processing
.length
? data.processing.map(renderProcessing).join("")
: `<li class="list-group-item ">Nothing processing</li>`;
document.getElementById("doneList").innerHTML = data.done.length
? data.done.map(renderDone).join("")
: `<li class="list-group-item ">No completed jobs</li>`;
document.getElementById("failedList").innerHTML = data.failed.length
? data.failed.map(renderFailed).join("")
: `<li class="list-group-item ">No failed jobs</li>`;
} catch (err) {
console.error("Status refresh error:", err);
}
} }
return bytes.toFixed(1) + " " + units[i];
}
// Auto-refresh every 3 seconds async function refreshStatus() {
setInterval(refreshStatus, 3000); try {
// -----------------------------------------
// 1. CAPTURE CURRENTLY OPEN DETAILS TAGS
// -----------------------------------------
const openDetails = new Set();
document.querySelectorAll("details").forEach((d, index) => {
if (d.open) openDetails.add(index);
});
// fetch new data
const res = await fetch("/status-data");
const data = await res.json();
// =======================
// Templates
// =======================
const renderQueued = 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>`;
const renderProcessing = job => `
<li class="list-group-item">
<strong style="color:#58a6ff">${job.filename}</strong>
<span class="spinner-border spinner-border-sm ms-2" style="color:#58a6ff"></span><br>
<small>${job.url}</small><br>
<small>Started: ${new Date(job.created_at).toLocaleString()}</small><br>
<small>Downloaded: ${formatBytes(job.fileSize)}</small>
${job.output_log ? `
<details class="mt-2">
<summary class="text-light">Live Log</summary>
<pre style="background:#001122; color:#9cf; padding:10px; border-radius:5px; white-space:pre-wrap;">
${job.output_log}
</pre>
</details>` : ""}
</li>`;
const renderDone = job => `
<li class="list-group-item">
<strong class="text-success">${job.filename}</strong><br>
<small>${new Date(job.finished_at).toLocaleString()}</small><br>
<small>Size: ${formatBytes(job.fileSize)}</small>
${job.output_log ? `
<details class="mt-2">
<summary class="text-light">Show Log</summary>
<pre style="background:#222; color:#e0e0e0; padding:10px; border-radius:5px; white-space:pre-wrap;">
${job.output_log}
</pre>
</details>` : ""}
</li>`;
const renderFailed = job => `
<li class="list-group-item">
<strong class="text-danger">${job.filename}</strong><br>
<small>${new Date(job.failed_at).toLocaleString()}</small><br>
${job.output_log ? `
<details class="mt-2">
<summary class="text-danger">Show Error Log</summary>
<pre style="background:#330000; color:#ffb3b3; padding:10px; border-radius:5px; white-space:pre-wrap;">
${job.output_log}
</pre>
</details>` : ""}
</li>`;
// Replace lists
queuedList.innerHTML = data.queued.length ?
data.queued.map(renderQueued).join("") :
`<li class="list-group-item">No queued jobs</li>`;
processingList.innerHTML = data.processing.length ?
data.processing.map(renderProcessing).join("") :
`<li class="list-group-item">Nothing processing</li>`;
doneList.innerHTML = data.done.length ?
data.done.map(renderDone).join("") :
`<li class="list-group-item">No completed jobs</li>`;
failedList.innerHTML = data.failed.length ?
data.failed.map(renderFailed).join("") :
`<li class="list-group-item">No failed jobs</li>`;
// -----------------------------------------
// 2. RESTORE PREVIOUSLY OPEN DETAILS TAGS
// -----------------------------------------
document.querySelectorAll("details").forEach((d, index) => {
if (openDetails.has(index)) d.open = true;
});
} catch (err) {
console.error("Status refresh error:", err);
}
}
setInterval(refreshStatus, 3000);
</script> </script>
<%- include("partials/footer") %> <%- include("partials/footer") %>