// proxer-queue-worker.js const { exec } = require("child_process"); const { MongoClient } = require("mongodb"); const path = require("path"); require("dotenv").config(); // ======================== // CONFIG // ======================== const MONGO_URI = process.env.MONGO_URI; const DB_NAME = process.env.MONGO_DB || "downloads"; const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP/"; const client = new MongoClient(MONGO_URI); let queueCol, doneCol, failedCol; // ======================== // RUN A JOB // ======================== async function runJob(job) { const venvPython = "/home/pm2/Proxer-Downloader/.venv/bin/python"; const cleanName = job.filename.replace(".mp4", ""); const safeToken = token.replace(/^"+|"+$/g, ''); // strip extra quotes const command = `${venvPython} ${scriptPath} -u "${url}" -f "${cleanName}" -t "${safeToken}" -o "${OUTPUT_DIR}"`; console.log("Running:", command); exec(command, async (error, stdout, stderr) => { const outputLog = `${stdout}\n${stderr}`.trim(); if (error) { console.error(`FAILED: ${cleanName}`); await failedCol.insertOne({ filename: job.filename, url: job.url, failed_at: new Date(), output_log: outputLog, return_code: error.code, }); await queueCol.deleteOne({ _id: job._id }); } else { console.log(`SUCCESS: ${cleanName}`); await doneCol.insertOne({ filename: job.filename, url: job.url, finished_at: new Date(), output_log: outputLog, result: "success", }); await queueCol.deleteOne({ _id: job._id }); } }); } // ======================== // MAIN LOOP // ======================== async function main() { console.log("Worker started. Watching queue..."); try { await client.connect(); const db = client.db(DB_NAME); queueCol = db.collection("queue"); doneCol = db.collection("done"); failedCol = db.collection("failed"); while (true) { const job = await queueCol.findOneAndUpdate( {}, { $set: { processing: true } }, { sort: { created_at: 1 }, returnDocument: "after" } ); if (job && job.value) { await runJob(job.value); } else { // Queue empty, wait 1 second await new Promise((resolve) => setTimeout(resolve, 1000)); } } } catch (err) { console.error("Worker error:", err); } } main();