migrated away from python
This commit is contained in:
1 parent
2dd68cb2b4
commit
bce6755a61
2 files changed
+99
-137
No files matched your search
@@ -0,0 +1,99 @@
|
||||
// proxer-queue-worker.js
|
||||
const { exec } = require("child_process");
|
||||
const { MongoClient } = require("mongodb");
|
||||
const path = require("path");
|
||||
require("dotenv").config({ path: path.join(__dirname, "..", ".env") });
|
||||
|
||||
// ========================
|
||||
// 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 url = job.url;
|
||||
const filename = job.filename;
|
||||
const token = job.token;
|
||||
|
||||
const cleanName = filename.replace(".mp4", "");
|
||||
|
||||
const scriptPath = path.join(__dirname, "proxer-dl-video.py");
|
||||
const venvPython = "/home/pm2/Proxer-Downloader/.venv/bin/python";
|
||||
|
||||
// Construct command string
|
||||
const command = `${venvPython} ${scriptPath} -u "${url}" -f "${cleanName}" -t "${token}" -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,
|
||||
url,
|
||||
failed_at: new Date(),
|
||||
output_log: outputLog,
|
||||
return_code: error.code,
|
||||
});
|
||||
|
||||
// Remove from queue
|
||||
await queueCol.deleteOne({ _id: job._id });
|
||||
} else {
|
||||
console.log(`SUCCESS: ${cleanName}`);
|
||||
await doneCol.insertOne({
|
||||
filename,
|
||||
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");
|
||||
|
||||
// Polling loop
|
||||
while (true) {
|
||||
const job = await queueCol.findOneAndUpdate(
|
||||
{},
|
||||
{ $set: { processing: true } },
|
||||
{ sort: { created_at: 1 }, returnDocument: "after" }
|
||||
);
|
||||
|
||||
if (job.value) {
|
||||
await runJob(job.value);
|
||||
} else {
|
||||
// Wait 1 second before checking again
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Worker error:", err);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,137 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import time
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from pymongo import MongoClient
|
||||
from dotenv import load_dotenv # <-- import dotenv
|
||||
|
||||
# ========================
|
||||
# LOAD .env
|
||||
# ========================
|
||||
|
||||
# .env is one directory up
|
||||
env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".env")
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
# ========================
|
||||
# CONFIG
|
||||
# ========================
|
||||
|
||||
MONGO_URI = os.environ.get("MONGO_URI")
|
||||
DB_NAME = os.environ.get("MONGO_DB", "downloads")
|
||||
OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "/mnt/media/WIP/")
|
||||
|
||||
client = MongoClient(MONGO_URI)
|
||||
db = client[DB_NAME]
|
||||
|
||||
queue_col = db["queue"]
|
||||
done_col = db["done"]
|
||||
failed_col = db["failed"]
|
||||
|
||||
# ========================
|
||||
# RUN A JOB
|
||||
# ========================
|
||||
|
||||
def run_job(job):
|
||||
"""Runs proxer-dl-video.py with job parameters."""
|
||||
|
||||
url = job["url"]
|
||||
filename = job["filename"]
|
||||
token = job["token"]
|
||||
|
||||
# Only filename *without extension* must be passed to script.
|
||||
clean_name = filename.replace(".mp4", "")
|
||||
|
||||
script_path = os.path.join(os.path.dirname(__file__), "proxer-dl-video.py")
|
||||
VENV_PYTHON = "/home/pm2/Proxer-Downloader/.venv/bin/python"
|
||||
|
||||
cmd = [
|
||||
VENV_PYTHON,
|
||||
script_path,
|
||||
"-u", url,
|
||||
"-f", f'"{clean_name}"', # wrap filename in quotes
|
||||
"-t", f'"{token}"', # wrap token in quotes
|
||||
"-o", OUTPUT_DIR
|
||||
]
|
||||
|
||||
|
||||
|
||||
print("Running:", " ".join(cmd))
|
||||
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True
|
||||
)
|
||||
|
||||
stdout = proc.stdout.strip()
|
||||
stderr = proc.stderr.strip()
|
||||
|
||||
# Merge for logs
|
||||
output_log = (stdout + "\n" + stderr).strip()
|
||||
|
||||
# Return code determines success/failure
|
||||
if proc.returncode == 0:
|
||||
print("SUCCESS:", clean_name)
|
||||
|
||||
done_col.insert_one({
|
||||
"filename": filename,
|
||||
"url": url,
|
||||
"finished_at": datetime.utcnow(),
|
||||
"output_log": output_log,
|
||||
"result": "success"
|
||||
})
|
||||
|
||||
# Remove from queue
|
||||
queue_col.delete_one({"_id": job["_id"]})
|
||||
else:
|
||||
print("FAILED:", clean_name)
|
||||
failed_col.insert_one({
|
||||
"filename": filename,
|
||||
"url": url,
|
||||
"failed_at": datetime.utcnow(),
|
||||
"output_log": output_log,
|
||||
"return_code": proc.returncode
|
||||
})
|
||||
|
||||
# Remove or mark as failed
|
||||
queue_col.delete_one({"_id": job["_id"]})
|
||||
|
||||
except Exception as e:
|
||||
|
||||
failed_col.insert_one({
|
||||
"filename": filename,
|
||||
"url": url,
|
||||
"failed_at": datetime.utcnow(),
|
||||
"output_log": str(e),
|
||||
"exception": True
|
||||
})
|
||||
|
||||
queue_col.delete_one({"_id": job["_id"]})
|
||||
|
||||
|
||||
# ========================
|
||||
# MAIN LOOP
|
||||
# ========================
|
||||
|
||||
def main():
|
||||
print("Worker started. Watching queue...")
|
||||
|
||||
while True:
|
||||
job = queue_col.find_one_and_update(
|
||||
{},
|
||||
{"$set": {"processing": True}},
|
||||
sort=[("created_at", 1)]
|
||||
)
|
||||
|
||||
if job:
|
||||
run_job(job)
|
||||
else:
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user