import cors from "cors"; import express from "express"; import multer from "multer"; import fs from "node:fs"; import fsp from "node:fs/promises"; import https from "node:https"; import http from "node:http"; import path from "node:path"; import os from "node:os"; import { fileURLToPath } from "node:url"; import { spawn } from "node:child_process"; import { Readable } from "node:stream"; const __filename = fileURLToPath(import.meta.url); // Robust fetch with timeout using AbortController (works on all Node.js versions) async function fetchWithTimeout(url, options = {}, timeoutMs = 5000) { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeoutMs); try { const response = await fetch(url, { ...options, signal: controller.signal }); clearTimeout(timeoutId); return response; } catch (err) { clearTimeout(timeoutId); if (err.name === "AbortError") { throw new Error(`Timed out after ${timeoutMs / 1000}s - server not responding`); } // Provide clearer error messages for common network issues const errMsg = err.message || String(err); if (errMsg.includes("fetch failed") || errMsg.includes("ECONNREFUSED")) { throw new Error(`Cannot connect to server. The server may be down, or HuggingFace Spaces may block connections to this port. Try a standard port (80, 443, 8080).`); } if (errMsg.includes("ENOTFOUND") || errMsg.includes("getaddrinfo")) { throw new Error(`Server hostname not found: ${url}`); } if (errMsg.includes("ETIMEDOUT") || errMsg.includes("ENETUNREACH")) { throw new Error(`Network unreachable or timed out connecting to: ${url}`); } throw err; } } const __dirname = path.dirname(__filename); const projectRoot = path.resolve(__dirname, ".."); const distDir = path.join(projectRoot, "dist"); const PORT = Number(process.env.PORT || 7860); const HOST = process.env.HOST || "0.0.0.0"; const DOWNLOADS_DIR = process.env.DOWNLOADS_DIR || path.join(projectRoot, "downloads"); const ENCODED_DIR = process.env.ENCODED_DIR || path.join(projectRoot, "encoded"); await fsp.mkdir(DOWNLOADS_DIR, { recursive: true }); await fsp.mkdir(ENCODED_DIR, { recursive: true }); const app = express(); app.use(cors()); app.use(express.json({ limit: "1mb" })); const upload = multer({ storage: multer.memoryStorage() }); // ── Job stores ───────────────────────────────────────────────────────────────── const jobs = new Map(); const downloadJobs = new Map(); function randomId(prefix = "job") { return `${prefix}_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`; } function parseFfmpegTimeToSeconds(value) { const parts = value.split(":"); if (parts.length !== 3) return 0; const [hh, mm, ss] = parts; return Number(hh) * 3600 + Number(mm) * 60 + Number(ss); } function runProcess(command, args) { return new Promise((resolve, reject) => { const p = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; let stderr = ""; p.stdout.on("data", (d) => { stdout += d.toString(); }); p.stderr.on("data", (d) => { stderr += d.toString(); }); p.on("error", reject); p.on("close", (code) => { if (code === 0) resolve({ stdout, stderr }); else reject(new Error(stderr || `${command} exited with code ${code}`)); }); }); } async function getDurationSeconds(filePath) { try { const { stdout } = await runProcess("ffprobe", [ "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filePath, ]); const sec = Number(stdout.trim()); return Number.isFinite(sec) ? sec : 0; } catch { return 0; } } function fixUtf8(str) { if (!str) return str; const win1252Map = new Set([ 0x20ac, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x017d, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x017e, 0x0178, ]); let isLikelyMojibake = true; for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); if (code > 0x00ff && !win1252Map.has(code)) { isLikelyMojibake = false; break; } } if (!isLikelyMojibake) return str; try { const bytes = new Uint8Array(str.length); for (let i = 0; i < str.length; i++) { let code = str.charCodeAt(i); if (code === 0x20ac) code = 0x80; else if (code === 0x201a) code = 0x82; else if (code === 0x0192) code = 0x83; else if (code === 0x201e) code = 0x84; else if (code === 0x2026) code = 0x85; else if (code === 0x2020) code = 0x86; else if (code === 0x2021) code = 0x87; else if (code === 0x02c6) code = 0x88; else if (code === 0x2030) code = 0x89; else if (code === 0x0160) code = 0x8a; else if (code === 0x2039) code = 0x8b; else if (code === 0x0152) code = 0x8c; else if (code === 0x017d) code = 0x8e; else if (code === 0x2018) code = 0x91; else if (code === 0x2019) code = 0x92; else if (code === 0x201c) code = 0x93; else if (code === 0x201d) code = 0x94; else if (code === 0x2022) code = 0x95; else if (code === 0x2013) code = 0x96; else if (code === 0x2014) code = 0x97; else if (code === 0x02dc) code = 0x98; else if (code === 0x2122) code = 0x99; else if (code === 0x0161) code = 0x9a; else if (code === 0x203a) code = 0x9b; else if (code === 0x0153) code = 0x9c; else if (code === 0x017e) code = 0x9e; else if (code === 0x0178) code = 0x9f; bytes[i] = code; } const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes); return decoded; } catch { /* fall through */ } return str; } function safeFilenameFromUrl(urlValue) { try { const u = new URL(urlValue); const name = decodeURIComponent(path.basename(u.pathname || "")).trim(); return fixUtf8(name) || `download_${Date.now()}.bin`; } catch { return `download_${Date.now()}.bin`; } } function getFilenameFromHeaders(response, urlValue) { const disposition = response.headers.get("content-disposition"); if (disposition) { const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i); if (utf8Match) return decodeURIComponent(utf8Match[1]); const asciiMatch = disposition.match(/filename="([^"]+)"/i); if (asciiMatch) return fixUtf8(asciiMatch[1]); } return safeFilenameFromUrl(urlValue); } /** * Sanitize a single path segment (no slashes allowed). */ function sanitizeSegment(seg, fallback = "file") { const cleaned = String(seg || "") .normalize("NFC") .replace(/[\\/]/g, "_") .replace(/[.\s]+$/, "") // no trailing dots/spaces .replace(/^[.\s]+/, "") // no leading dots/spaces .replace(/[\u0000-\u001f\u007f]/g, "") .trim(); return cleaned || fallback; } /** * Sanitize a relative folder path like "MyShow/Season 1" * Each segment is sanitized individually. */ function sanitizeFolderPath(rawPath) { if (!rawPath || rawPath === "/" || rawPath === ".") return "/"; return rawPath .split(/[\\/]/) .filter(Boolean) .map((seg) => sanitizeSegment(seg, "folder")) .join("/"); } function getUniqueFilePath(dir, filename) { const baseName = path.parse(filename).name || "file"; const ext = path.parse(filename).ext || ""; let candidateName = `${baseName}${ext}`; let candidatePath = path.join(dir, candidateName); let i = 1; while (fs.existsSync(candidatePath)) { candidateName = `${baseName} (${i})${ext}`; candidatePath = path.join(dir, candidateName); i += 1; } return { name: candidateName, fullPath: candidatePath }; } async function getVideoResolution(filePath) { try { const { stdout } = await runProcess("ffprobe", [ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=s=x:p=0", filePath, ]); return stdout.trim() || "unknown"; } catch { return "unknown"; } } /** * Resolve a file id like "downloaded:MyFolder/filename.mkv" * Returns { source, name (relative path), filePath (absolute), folder } */ function resolveFileFromId(fileId) { const [source, ...nameParts] = String(fileId || "").split(":"); const name = nameParts.join(":"); if (!name || (source !== "downloaded" && source !== "encoded")) return null; // Prevent path traversal const base = source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR; const resolved = path.resolve(base, name); if (!resolved.startsWith(base + path.sep) && resolved !== base) return null; const folder = path.dirname(name) === "." ? "/" : `/${path.dirname(name)}`; return { source, name, filePath: resolved, folder }; } /** * Recursively list all files under dirPath, returning entries with relative paths. */ async function listFilesRecursive(dirPath, source, relDir = "") { const out = []; let entries; try { entries = await fsp.readdir(dirPath, { withFileTypes: true }); } catch { return out; } for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); const relPath = relDir ? `${relDir}/${entry.name}` : entry.name; if (entry.isDirectory()) { const children = await listFilesRecursive(fullPath, source, relPath); out.push(...children); } else if (entry.isFile()) { // Skip hidden/temp files and settings sidecars if (entry.name.startsWith("_concat_") || entry.name.startsWith(".")) continue; if (entry.name.endsWith(".settings.json")) continue; const st = await fsp.stat(fullPath); const folder = relDir ? `/${relDir}` : "/"; out.push({ id: `${source}:${relPath}`, name: entry.name, relativePath: relPath, sizeBytes: st.size, source, createdAt: st.mtimeMs, folder, }); } } return out; } async function listFoldersRecursive(dirPath, relDir = "") { const out = []; let entries; try { entries = await fsp.readdir(dirPath, { withFileTypes: true }); } catch { return out; } for (const entry of entries) { if (!entry.isDirectory()) continue; if (entry.name.startsWith(".")) continue; const relPath = relDir ? `${relDir}/${entry.name}` : entry.name; out.push(`/${relPath}`); const children = await listFoldersRecursive(path.join(dirPath, entry.name), relPath); out.push(...children); } return out; } function buildEncodeArgs(settings, inputPath, outputPath) { const args = ["-y"]; if (settings.startTime) args.push("-ss", String(settings.startTime)); if (settings.endTime) args.push("-to", String(settings.endTime)); args.push("-i", inputPath); const subtitleRel = settings.subtitleFile ? String(settings.subtitleFile) : ""; let subtitlePath = null; let subtitleExists = false; if (subtitleRel) { const resolvedSub = path.resolve(DOWNLOADS_DIR, subtitleRel); if (resolvedSub.startsWith(DOWNLOADS_DIR + path.sep) || resolvedSub === DOWNLOADS_DIR) { subtitlePath = resolvedSub; subtitleExists = fs.existsSync(resolvedSub); } } if (subtitleExists) { args.push("-i", subtitlePath); } const isAudioOnly = settings.outputFormat === 'audio'; const sameAsOriginalVideo = settings.sameAsOriginalVideo; const sameAsOriginalAudio = settings.sameAsOriginalAudio; const filters = []; if (!isAudioOnly && !sameAsOriginalVideo) { if (settings.resolution === "1080p") filters.push("scale=-2:1080"); else if (settings.resolution === "720p") filters.push("scale=-2:720"); else if (settings.resolution === "480p") filters.push("scale=-2:480"); else if (settings.resolution === "custom" && settings.scaleWidth && settings.scaleHeight) filters.push(`scale=${settings.scaleWidth}:${settings.scaleHeight}`); if (settings.deinterlace) filters.push("yadif=1"); if (settings.denoise) filters.push("hqdn3d=3:3:6:6"); if (settings.rotate === "90cw") filters.push("transpose=1"); if (settings.rotate === "90ccw") filters.push("transpose=2"); if (settings.rotate === "180") filters.push("transpose=2,transpose=2"); if (settings.speed && Number(settings.speed) !== 1) filters.push(`setpts=${(1 / Number(settings.speed)).toFixed(3)}*PTS`); // Only add eq filter when values differ from defaults const br = Number(settings.brightness ?? 0); const ct = Number(settings.contrast ?? 1); const sat = Number(settings.saturation ?? 1); if (br !== 0 || ct !== 1 || sat !== 1) { filters.push(`eq=brightness=${br}:contrast=${ct}:saturation=${sat}`); } if (settings.subtitleBurn && subtitleExists) { const subPath = subtitlePath.replace(/\\/g, "\\\\").replace(/:/g, "\\:"); filters.push(`subtitles='${subPath}'`); } } if (filters.length) args.push("-vf", filters.join(",")); if (!isAudioOnly && settings.frameRate !== "original") args.push("-r", String(settings.frameRate)); if (!isAudioOnly) { args.push("-pix_fmt", "yuv420p"); const fps = settings.frameRate !== "original" ? Number(settings.frameRate) : 30; args.push("-g", String(Math.round(fps * 10))); // -sc_threshold only works for h264/h265, not SVT-AV1 if (settings.codec !== "av1" && settings.sceneChange !== undefined && settings.sceneChange !== null) { const sc = Math.max(0, Math.min(100, Number(settings.sceneChange))); args.push("-sc_threshold", String(sc)); } } if (settings.stripSubtitles && !subtitleExists) args.push("-sn"); if (settings.stripMetadata) args.push("-map_metadata", "-1"); if (isAudioOnly) { args.push("-vn"); // No video } else if (sameAsOriginalVideo) { args.push("-c:v", "copy"); } else { if (settings.codec === "av1") { args.push("-c:v", "libsvtav1", "-preset", String(settings.preset ?? 5)); if (settings.mode === "crf-1pass") args.push("-crf", String(settings.crf ?? 40)); else args.push("-b:v", `${settings.videoBitrateKbps || 800}k`); const svtParams = [ "tune=0", `aq-mode=${settings.aqMode !== undefined ? settings.aqMode : 0}`, "enable-tf=1", "enable-overlays=1", "film-grain=0", "fast-decode=1", ]; if (settings.tiles === "2x2") svtParams.push("tile-columns=1", "tile-rows=1"); args.push("-svtav1-params", svtParams.join(":")); } if (settings.codec === "h265") { const h265Preset = settings.h26xPreset || "medium"; args.push("-c:v", "libx265", "-preset", h265Preset); if (settings.mode === "crf-1pass") args.push("-crf", String(settings.crf ?? 28)); else args.push("-b:v", `${settings.videoBitrateKbps || 1800}k`); args.push("-x265-params", "psy-rd=1.0:psy-rdoq=1.0:b-adapt=2"); } if (settings.codec === "h264") { const h264Preset = settings.h26xPreset || "medium"; args.push("-c:v", "libx264", "-preset", h264Preset); if (settings.mode === "crf-1pass") args.push("-crf", String(settings.crf ?? 23)); else args.push("-b:v", `${settings.videoBitrateKbps || 2200}k`); args.push("-tune", "film"); } } // Audio speed filter (atempo) when speed is changed — must match video setpts const speedVal = Number(settings.speed || 1); if (speedVal !== 1 && speedVal > 0 && !isAudioOnly) { // atempo only accepts values between 0.5 and 100.0, chain for extreme values const audioFilters = []; let remaining = speedVal; while (remaining > 2.0) { audioFilters.push("atempo=2.0"); remaining /= 2.0; } while (remaining < 0.5) { audioFilters.push("atempo=0.5"); remaining /= 0.5; } audioFilters.push(`atempo=${remaining.toFixed(4)}`); args.push("-filter:a", audioFilters.join(",")); } if (!sameAsOriginalAudio) { args.push("-c:a", "libopus", "-b:a", `${settings.audioBitrateKbps || 72}k`, "-vbr", "on", "-compression_level", "10", "-application", "audio"); if (settings.forceStereo || settings.audioChannels === "stereo") args.push("-ac", "2"); if (settings.audioChannels === "mono") args.push("-ac", "1"); } else { args.push("-c:a", "copy"); // Copy original audio } if (subtitleExists && !settings.subtitleBurn && !isAudioOnly) { // Map video, audio from first input, then subtitle from second input args.push("-map", "0:v:0", "-map", "0:a:0", "-map", "1:0"); args.push("-c:s", "copy"); if (settings.subtitleLang) { args.push("-metadata:s:s:0", `language=${settings.subtitleLang}`); } } else if (isAudioOnly) { args.push("-map", "0:a:0"); // Only audio } const ext = path.extname(outputPath).toLowerCase(); if (ext === ".mp4" || ext === ".m4v") { args.push("-strict", "experimental", "-movflags", "+faststart"); } if (ext === ".webm") { // WebM container: enforce compatible audio codec args.push("-c:a", "libopus"); } args.push(outputPath); return args; } // ── API Routes ───────────────────────────────────────────────────────────────── app.get("/api/health", (_req, res) => res.json({ ok: true })); app.get("/api/files", async (_req, res) => { try { const downloaded = await listFilesRecursive(DOWNLOADS_DIR, "downloaded"); const encoded = await listFilesRecursive(ENCODED_DIR, "encoded"); const folders = await listFoldersRecursive(DOWNLOADS_DIR); res.json({ downloaded, encoded, folders }); } catch (err) { res.status(500).json({ error: err.message || "Failed to list files" }); } }); /** * Upload endpoint. * Each file may have a corresponding folderPath_N field (relative path like "MyFolder/SubFolder"). * Files are saved into DOWNLOADS_DIR//. */ app.post("/api/files/upload", upload.array("files"), async (req, res) => { const files = Array.isArray(req.files) ? req.files : []; if (files.length === 0) return res.status(400).json({ error: "No files uploaded" }); try { const uploaded = []; for (let i = 0; i < files.length; i++) { const file = files[i]; const rawName = fixUtf8(file.originalname) || "upload.bin"; const safeName = path.basename(rawName); // Folder path sent by client (e.g. "MyShow/Season1" or "") const rawFolder = String(req.body?.[`folderPath_${i}`] || "").trim(); const folderPath = sanitizeFolderPath(rawFolder); // "/" or "MyShow/Season1" let targetDir = DOWNLOADS_DIR; if (folderPath && folderPath !== "/") { targetDir = path.join(DOWNLOADS_DIR, folderPath); await fsp.mkdir(targetDir, { recursive: true }); } const { name, fullPath } = getUniqueFilePath(targetDir, safeName); // relative path for the id const relPath = folderPath && folderPath !== "/" ? `${folderPath.replace(/^\//, "")}/${name}` : name; await fsp.writeFile(fullPath, file.buffer); uploaded.push({ name, relPath, folder: folderPath || "/" }); } return res.json({ ok: true, uploaded }); } catch (err) { return res.status(500).json({ error: err.message || "Failed to upload files" }); } }); app.get("/api/files/:id/download", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); if (!info) return res.status(400).json({ error: "Invalid file id" }); try { await fsp.access(info.filePath); return res.download(info.filePath, info.name); } catch { return res.status(404).json({ error: "File not found" }); } }); app.post("/api/files/:id/rename", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); const requestedName = String(req.body?.newName || "").trim(); if (!info) return res.status(400).json({ error: "Invalid file id" }); if (!requestedName) return res.status(400).json({ error: "newName is required" }); const fileDir = path.dirname(info.filePath); const oldParsed = path.parse(info.name); const reqParsed = path.parse(requestedName); const withExt = reqParsed.ext ? requestedName : `${requestedName}${oldParsed.ext || ""}`; const { name: nextName, fullPath: nextPath } = getUniqueFilePath(fileDir, withExt); try { await fsp.access(info.filePath); if (nextPath !== info.filePath) await fsp.rename(info.filePath, nextPath); // Rebuild id with same folder prefix const folderPrefix = info.folder !== "/" ? info.folder.replace(/^\//, "") + "/" : ""; const newId = `${info.source}:${folderPrefix}${nextName}`; return res.json({ ok: true, id: newId, name: nextName }); } catch { return res.status(404).json({ error: "File not found" }); } }); app.delete("/api/files/:id", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); if (!info) return res.status(400).json({ error: "Invalid file id" }); try { await fsp.unlink(info.filePath); return res.json({ ok: true }); } catch { return res.status(404).json({ error: "File not found" }); } }); app.delete("/api/files", async (_req, res) => { for (const dir of [DOWNLOADS_DIR, ENCODED_DIR]) { const entries = await fsp.readdir(dir, { withFileTypes: true }); await Promise.all( entries.map((e) => { const fullPath = path.join(dir, e.name); if (e.isDirectory()) return fsp.rm(fullPath, { recursive: true, force: true }); return fsp.unlink(fullPath); }) ); } return res.json({ ok: true }); }); // ── URL Download with progress tracking ──────────────────────────────────────── app.post("/api/download-url", async (req, res) => { const { url, username, password } = req.body || {}; if (!url || typeof url !== "string") return res.status(400).json({ error: "url is required" }); const headers = {}; if (username && password) { headers.Authorization = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`; } const dlJobId = randomId("dl"); const dlJob = { id: dlJobId, createdAt: Date.now(), status: "running", url, filename: null, bytesDownloaded: 0, totalBytes: 0, error: null, abortController: new AbortController(), }; downloadJobs.set(dlJobId, dlJob); res.json({ ok: true, jobId: dlJobId }); (async () => { try { const response = await fetch(url, { headers, signal: dlJob.abortController.signal }); if (!response.ok || !response.body) { dlJob.status = "failed"; dlJob.error = `Server returned ${response.status}`; return; } const contentLength = response.headers.get("content-length"); dlJob.totalBytes = contentLength ? Number(contentLength) : 0; const requestedName = getFilenameFromHeaders(response, url); const { name: filename, fullPath: destPath } = getUniqueFilePath(DOWNLOADS_DIR, requestedName); dlJob.filename = filename; const fileStream = fs.createWriteStream(destPath); const nodeReadable = Readable.fromWeb(response.body); nodeReadable.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; }); await new Promise((resolve, reject) => { nodeReadable.on("error", reject); fileStream.on("error", reject); fileStream.on("finish", resolve); nodeReadable.pipe(fileStream); }); dlJob.status = "done"; } catch (err) { if (err.name === "AbortError") dlJob.status = "stopped"; else { dlJob.status = "failed"; dlJob.error = err.message || "Download failed"; } } })(); }); app.get("/api/download-jobs/:id", (req, res) => { const dlJob = downloadJobs.get(req.params.id); if (!dlJob) return res.status(404).json({ error: "Download job not found" }); const { abortController: _ac, ...safe } = dlJob; return res.json({ job: safe }); }); app.post("/api/download-jobs/:id/stop", (req, res) => { const dlJob = downloadJobs.get(req.params.id); if (!dlJob) return res.status(404).json({ error: "Download job not found" }); if (dlJob.status === "running") { dlJob.abortController.abort(); dlJob.status = "stopped"; } return res.json({ ok: true }); }); // ── Encode ───────────────────────────────────────────────────────────────────── app.post("/api/encode", async (req, res) => { const settings = req.body || {}; if (!settings.inputFilename || !settings.outputFilename) { return res.status(400).json({ error: "inputFilename and outputFilename are required" }); } const rawInput = String(settings.inputFilename || ""); const inputPath = path.resolve(DOWNLOADS_DIR, rawInput); if (!inputPath.startsWith(DOWNLOADS_DIR + path.sep) && inputPath !== DOWNLOADS_DIR) { return res.status(400).json({ error: "Invalid input path" }); } const tempOutputPath = path.join(ENCODED_DIR, path.basename(settings.outputFilename)); try { await fsp.access(inputPath); } catch { return res.status(404).json({ error: "Input file not found in downloads folder" }); } const jobId = randomId("enc"); const durationSeconds = await getDurationSeconds(inputPath); const job = { id: jobId, createdAt: Date.now(), startedAt: Date.now(), status: "running", settings, batchIndex: settings.batchIndex !== undefined ? Number(settings.batchIndex) : null, batchTotal: settings.batchTotal !== undefined ? Number(settings.batchTotal) : null, outputFolder: "/", outputSource: "encoded", _process: null, progress: { percent: 0, fps: 0, etaSeconds: durationSeconds, speed: 0, bitrateKbps: 0, sizeOutBytes: 0, log: ["Starting ffmpeg encode..."] }, }; jobs.set(jobId, job); const args = buildEncodeArgs(settings, inputPath, tempOutputPath); const ffmpeg = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] }); job._process = ffmpeg; ffmpeg.stderr.on("data", async (chunk) => { const line = chunk.toString(); const latest = jobs.get(jobId); if (!latest) return; latest.progress.log.push(line.trim()); if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500); const timeMatch = line.match(/time=([0-9:.]+)/); if (timeMatch) { const seconds = parseFfmpegTimeToSeconds(timeMatch[1]); if (durationSeconds > 0) { latest.progress.percent = Math.min(99.5, (seconds / durationSeconds) * 100); // Calculate actual encoding speed and accurate ETA const elapsedMs = Date.now() - latest.startedAt; const elapsedSec = elapsedMs / 1000; const speed = elapsedSec > 0 ? seconds / elapsedSec : 0; latest.progress.speed = speed; const remaining = durationSeconds - seconds; latest.progress.etaSeconds = speed > 0 ? Math.max(0, remaining / speed) : remaining; } } const fpsMatch = line.match(/fps=\s*([0-9.]+)/); if (fpsMatch) latest.progress.fps = Number(fpsMatch[1]) || 0; // Parse current bitrate from ffmpeg output (e.g., bitrate= 883.2kbits/s) const bitrateMatch = line.match(/bitrate=\s*([0-9.]+)kbits\/s/); if (bitrateMatch) latest.progress.bitrateKbps = Number(bitrateMatch[1]) || 0; const sizeMatch = line.match(/size=\s*([0-9]+)kB/); if (sizeMatch) { latest.progress.sizeOutBytes = Number(sizeMatch[1]) * 1024; } else { try { const st = await fsp.stat(tempOutputPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ } } }); ffmpeg.on("error", (err) => { const latest = jobs.get(jobId); if (!latest) return; latest.status = "failed"; latest.progress.log.push(`Failed to launch ffmpeg: ${err.message}`); }); ffmpeg.on("close", async (code) => { const latest = jobs.get(jobId); if (!latest) return; latest._process = null; if (latest.status === "stopped") return; if (code === 0) { const resolution = await getVideoResolution(tempOutputPath); const parsedOutput = path.parse(tempOutputPath); const desiredName = `${parsedOutput.name}_${resolution}${parsedOutput.ext}`; const { name: finalName, fullPath: finalPath } = getUniqueFilePath(ENCODED_DIR, desiredName); try { await fsp.rename(tempOutputPath, finalPath); } catch { latest.progress.log.push(`Warning: could not rename to ${finalName}`); } const actualPath = fs.existsSync(finalPath) ? finalPath : tempOutputPath; latest.status = "done"; latest.outputFolder = "/"; latest.outputSource = "encoded"; latest.progress.percent = 100; latest.progress.etaSeconds = 0; try { const st = await fsp.stat(actualPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ } latest.progress.log.push(`Encode completed. Output: ${path.basename(actualPath)}`); // Persist encoding settings sidecar for later display try { const settingsPath = `${actualPath}.settings.json`; await fsp.writeFile(settingsPath, JSON.stringify({ createdAt: Date.now(), inputFilename: settings.inputFilename, outputFilename: path.basename(actualPath), resolution, settings, }, null, 2), "utf8"); } catch { // ignore sidecar failures } } else { latest.status = "failed"; latest.progress.log.push(`ffmpeg exited with code ${code}`); } }); const { _process: _p, ...safeJob } = job; return res.json({ job: safeJob }); }); // ── Stop an encode/trim/merge job ────────────────────────────────────────────── app.post("/api/jobs/:id/stop", (req, res) => { const job = jobs.get(req.params.id); if (!job) return res.status(404).json({ error: "Job not found" }); if (job.status !== "running") return res.json({ ok: true, note: "Job not running" }); job.status = "stopped"; job.progress.log.push("Job stopped by user."); if (job._process) { try { job._process.kill("SIGTERM"); } catch { /* ignore */ } job._process = null; } return res.json({ ok: true }); }); app.get("/api/jobs", (_req, res) => { const allJobs = [...jobs.values()] .sort((a, b) => b.createdAt - a.createdAt) .map(({ _process: _p, ...j }) => j); res.json({ jobs: allJobs }); }); app.get("/api/jobs/:id", (req, res) => { const job = jobs.get(req.params.id); if (!job) return res.status(404).json({ error: "Job not found" }); const { _process: _p, ...safeJob } = job; return res.json({ job: safeJob }); }); // ── File Info ────────────────────────────────────────────────────────────────── app.get("/api/files/:id/info", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); if (!info) return res.status(400).json({ error: "Invalid file id" }); try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); } try { const { stdout } = await runProcess("ffprobe", [ "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", info.filePath, ]); const probe = JSON.parse(stdout); const fmt = probe.format || {}; const streams = probe.streams || []; const videoStream = streams.find((s) => s.codec_type === "video"); const audioStream = streams.find((s) => s.codec_type === "audio"); const durationSec = parseFloat(fmt.duration || videoStream?.duration || 0); const h = Math.floor(durationSec / 3600); const m = Math.floor((durationSec % 3600) / 60); const s = Math.floor(durationSec % 60); const durationStr = h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`; const st = await fsp.stat(info.filePath); const totalBitrate = parseInt(fmt.bit_rate || 0); const audioBitrate = parseInt(audioStream?.bit_rate || 0); const videoBitrate = parseInt(videoStream?.bit_rate || 0) || (totalBitrate - audioBitrate) || 0; const videoStreamSize = durationSec > 0 && videoBitrate > 0 ? Math.round((videoBitrate / 8) * durationSec) : null; const audioStreamSize = durationSec > 0 && audioBitrate > 0 ? Math.round((audioBitrate / 8) * durationSec) : null; function fmtBytes(b) { if (!b) return "unknown"; if (b < 1024) return `${b} B`; if (b < 1024 ** 2) return `${(b / 1024).toFixed(1)} KB`; if (b < 1024 ** 3) return `${(b / 1024 ** 2).toFixed(2)} MB`; return `${(b / 1024 ** 3).toFixed(2)} GB`; } function fmtBitrate(bps) { if (!bps) return "unknown"; if (bps >= 1_000_000) return `${(bps / 1_000_000).toFixed(2)} Mbps`; return `${(bps / 1000).toFixed(0)} kbps`; } let frameRate = "unknown"; if (videoStream?.r_frame_rate) { const [num, den] = videoStream.r_frame_rate.split("/").map(Number); if (den && den !== 0) frameRate = (num / den).toFixed(3).replace(/\.?0+$/, "") + " fps"; } let encodeSettings = null; if (info.source === "encoded") { try { const settingsPath = `${info.filePath}.settings.json`; const raw = await fsp.readFile(settingsPath, "utf8"); encodeSettings = JSON.parse(raw); } catch { encodeSettings = null; } } return res.json({ ok: true, info: { fileSize: fmtBytes(st.size), fileSizeBytes: st.size, duration: durationStr, durationSeconds: durationSec, video: videoStream ? { codec: videoStream.codec_name || "unknown", profile: videoStream.profile || null, resolution: `${videoStream.width}x${videoStream.height}`, width: videoStream.width, height: videoStream.height, frameRate, bitrate: fmtBitrate(videoBitrate), bitrateRaw: videoBitrate, pixFmt: videoStream.pix_fmt || "unknown", streamSize: videoStreamSize ? fmtBytes(videoStreamSize) : "unknown", } : null, audio: audioStream ? { codec: audioStream.codec_name || "unknown", sampleRate: audioStream.sample_rate ? `${audioStream.sample_rate} Hz` : "unknown", channels: audioStream.channels || "unknown", channelLayout: audioStream.channel_layout || "unknown", bitrate: fmtBitrate(parseInt(audioStream.bit_rate || 0)), bitrateRaw: parseInt(audioStream.bit_rate || 0), streamSize: audioStreamSize ? fmtBytes(audioStreamSize) : "unknown", } : null, encodeSettings, }, }); } catch (err) { return res.status(500).json({ error: err.message || "ffprobe failed" }); } }); // ── Trim ─────────────────────────────────────────────────────────────────────── app.post("/api/trim", async (req, res) => { const { fileId, startTime, endTime, outputFilename, segments } = req.body || {}; if (!fileId || !outputFilename) { return res.status(400).json({ error: "fileId and outputFilename are required" }); } const info = resolveFileFromId(String(fileId)); if (!info) return res.status(400).json({ error: "Invalid file id" }); try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); } const normalizedSegments = Array.isArray(segments) ? segments.map((item) => ({ startTime: Number(item?.startTime), endTime: Number(item?.endTime) })) : [{ startTime: Number(startTime), endTime: Number(endTime) }]; if (normalizedSegments.length === 0) { return res.status(400).json({ error: "At least one trim segment is required" }); } for (const segment of normalizedSegments) { if (!Number.isFinite(segment.startTime) || !Number.isFinite(segment.endTime)) { return res.status(400).json({ error: "Invalid trim segment times" }); } if (segment.endTime <= segment.startTime) { return res.status(400).json({ error: "Each trim segment must have an end time after its start time" }); } } // Save trimmed output to the SAME folder as the source file const sourceDir = path.dirname(info.filePath); const { name: outName, fullPath: outPath } = getUniqueFilePath(sourceDir, String(outputFilename)); // Compute output folder (relative to DOWNLOADS_DIR or ENCODED_DIR) const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR; const relOutDir = path.relative(base, sourceDir); const outputFolder = relOutDir ? `/${relOutDir}` : "/"; const totalDuration = normalizedSegments.reduce((sum, segment) => sum + (segment.endTime - segment.startTime), 0); const jobId = randomId("trim"); const job = { id: jobId, createdAt: Date.now(), status: "running", _process: null, outputFolder, outputSource: info.source, settings: { inputFilename: info.name, outputFilename: outName, segments: normalizedSegments, type: "trim" }, progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: ["Starting trim..."] }, }; jobs.set(jobId, job); const runFfmpegProcess = (args, previousSeconds = 0) => new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] }); const update = (chunk) => { const line = chunk.toString(); const latest = jobs.get(jobId); if (!latest) return; latest.progress.log.push(line.trim()); if (latest.progress.log.length > 200) latest.progress.log = latest.progress.log.slice(-200); const timeMatch = line.match(/time=([0-9:.]+)/); if (timeMatch) { const secs = parseFfmpegTimeToSeconds(timeMatch[1]); if (totalDuration > 0) { latest.progress.percent = Math.min(99.5, ((previousSeconds + secs) / totalDuration) * 100); latest.progress.etaSeconds = Math.max(0, totalDuration - (previousSeconds + secs)); } } const sizeMatch = line.match(/size=\s*([0-9]+)kB/); if (sizeMatch) latest.progress.sizeOutBytes = Number(sizeMatch[1]) * 1024; }; ffmpeg.stderr.on("data", update); ffmpeg.on("error", (err) => { const latest = jobs.get(jobId); if (!latest) return; latest.status = "failed"; latest.progress.log.push(`Failed: ${err.message}`); reject(err); }); ffmpeg.on("close", (code) => { const latest = jobs.get(jobId); if (!latest) return resolve(null); latest._process = null; if (latest.status === "stopped") { return resolve(null); } if (code === 0) { resolve(null); } else { latest.status = "failed"; latest.progress.log.push(`ffmpeg exited with code ${code}`); reject(new Error(`ffmpeg exited with code ${code}`)); } }); job._process = ffmpeg; }); const runSegment = async (segment, idx, outputPath, previousSeconds = 0) => { const args = ["-y", "-ss", String(segment.startTime), "-to", String(segment.endTime), "-i", info.filePath, "-c", "copy", outputPath]; await runFfmpegProcess(args, previousSeconds); return outputPath; }; let tempDir = null; let concatListPath = null; let segmentFiles = []; try { if (normalizedSegments.length === 1) { const segment = normalizedSegments[0]; await runSegment(segment, 0, outPath, 0); job.status = "done"; job.progress.percent = 100; job.progress.etaSeconds = 0; try { const st = await fsp.stat(outPath); job.progress.sizeOutBytes = st.size; } catch { /* ignore */ } job.progress.log.push(`Trim completed. Output: ${outName}`); } else { tempDir = path.join(os.tmpdir(), `trim-segments-${jobId}`); await fsp.mkdir(tempDir, { recursive: true }); let elapsed = 0; for (let idx = 0; idx < normalizedSegments.length; idx += 1) { const segment = normalizedSegments[idx]; const segmentPath = path.join(tempDir, `segment_${idx + 1}${path.extname(info.filePath) || ".mkv"}`); job.progress.log.push(`Trimming segment ${idx + 1} of ${normalizedSegments.length}…`); await runSegment(segment, idx, segmentPath, elapsed); if (job.status === "stopped") break; segmentFiles.push(segmentPath); elapsed += segment.endTime - segment.startTime; } if (job.status !== "stopped") { job.progress.log.push(`Merging ${segmentFiles.length} segments…`); concatListPath = path.join(tempDir, `concat-${jobId}.txt`); const concatContent = segmentFiles.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n"); await fsp.writeFile(concatListPath, concatContent, "utf8"); await runFfmpegProcess(["-y", "-f", "concat", "-safe", "0", "-i", concatListPath, "-c", "copy", outPath], 0); if (job.status !== "stopped") { job.status = "done"; job.progress.percent = 100; job.progress.etaSeconds = 0; try { const st = await fsp.stat(outPath); job.progress.sizeOutBytes = st.size; } catch { /* ignore */ } job.progress.log.push(`Trim completed. Output: ${outName}`); } } } } catch (err) { const latest = jobs.get(jobId); if (latest && latest.status !== "stopped") { latest.status = "failed"; latest.progress.log.push(`Trim failed: ${err.message || err}`); } } finally { if (concatListPath) { await fsp.rm(concatListPath, { force: true }).catch(() => {}); } if (segmentFiles.length > 0) { await Promise.all(segmentFiles.map((filePath) => fsp.rm(filePath, { force: true }).catch(() => {}))); } if (tempDir) { await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {}); } } const { _process: _p, ...safeJob } = job; return res.json({ job: safeJob }); }); // ── Pixeldrain Upload ────────────────────────────────────────────────────────── const pixeldrainJobs = new Map(); app.post("/api/files/:id/pixeldrain", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); if (!info) return res.status(400).json({ error: "Invalid file id" }); try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); } const PIXELDRAIN_API_KEY = process.env.PIXELDRAIN_API_KEY || ""; const pdJobId = randomId("pd"); const st = await fsp.stat(info.filePath); const pdJob = { id: pdJobId, createdAt: Date.now(), status: "running", filename: info.name, bytesUploaded: 0, totalBytes: st.size, pixeldrainUrl: null, error: null, }; pixeldrainJobs.set(pdJobId, pdJob); res.json({ ok: true, jobId: pdJobId }); (async () => { try { const fileStream = fs.createReadStream(info.filePath); let bytesRead = 0; fileStream.on("data", (chunk) => { bytesRead += chunk.length; pdJob.bytesUploaded = bytesRead; }); const headers = { "Content-Type": "application/octet-stream", "Content-Length": String(st.size), }; if (PIXELDRAIN_API_KEY) { headers["Authorization"] = `Basic ${Buffer.from(`:${PIXELDRAIN_API_KEY}`).toString("base64")}`; } const url = `https://pixeldrain.com/api/file/${encodeURIComponent(info.name)}`; const response = await new Promise((resolve, reject) => { const parsedUrl = new URL(url); const options = { hostname: parsedUrl.hostname, path: parsedUrl.pathname + parsedUrl.search, method: "PUT", headers, }; const req2 = https.request(options, resolve); req2.on("error", reject); fileStream.pipe(req2); }); let body = ""; await new Promise((resolve) => { response.on("data", (d) => { body += d.toString(); }); response.on("end", resolve); }); const result = JSON.parse(body); if (result.id) { pdJob.status = "done"; pdJob.bytesUploaded = st.size; pdJob.pixeldrainUrl = `https://pixeldrain.com/u/${result.id}`; } else { pdJob.status = "failed"; pdJob.error = result.message || result.value || "Upload failed"; } } catch (err) { pdJob.status = "failed"; pdJob.error = err.message || "Upload failed"; } })(); }); app.get("/api/pixeldrain-jobs/:id", (req, res) => { const job = pixeldrainJobs.get(req.params.id); if (!job) return res.status(404).json({ error: "Job not found" }); return res.json({ job }); }); // ── Merge ────────────────────────────────────────────────────────────────────── app.post("/api/merge", async (req, res) => { const { fileIds, outputFilename } = req.body || {}; if (!Array.isArray(fileIds) || fileIds.length < 2) { return res.status(400).json({ error: "fileIds array with at least 2 files is required" }); } if (!outputFilename) return res.status(400).json({ error: "outputFilename is required" }); const resolvedFiles = []; for (const id of fileIds) { const info = resolveFileFromId(String(id)); if (!info) return res.status(400).json({ error: `Invalid file id: ${id}` }); try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: `File not found: ${info.name}` }); } resolvedFiles.push(info); } // Save merged output to same folder as first source file const firstInfo = resolvedFiles[0]; const outputDir = path.dirname(firstInfo.filePath); const base = firstInfo.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR; const relOutDir = path.relative(base, outputDir); const outputFolder = relOutDir ? `/${relOutDir}` : "/"; const { name: outName, fullPath: outPath } = getUniqueFilePath(outputDir, String(outputFilename)); const concatListPath = path.join(DOWNLOADS_DIR, `_concat_${Date.now()}.txt`); const concatContent = resolvedFiles.map((f) => `file '${f.filePath.replace(/'/g, "'\\''")}'`).join("\n"); await fsp.writeFile(concatListPath, concatContent, "utf8"); let totalDuration = 0; for (const f of resolvedFiles) totalDuration += await getDurationSeconds(f.filePath); const jobId = randomId("merge"); const job = { id: jobId, createdAt: Date.now(), status: "running", _process: null, outputFolder, outputSource: firstInfo.source, settings: { type: "merge", inputFilenames: resolvedFiles.map((f) => f.name), outputFilename: outName, }, batchIndex: null, batchTotal: null, progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: [`Merging ${resolvedFiles.length} files…`], }, }; jobs.set(jobId, job); const args = ["-y", "-f", "concat", "-safe", "0", "-i", concatListPath, "-c", "copy", outPath]; const ffmpeg = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] }); job._process = ffmpeg; ffmpeg.stderr.on("data", (chunk) => { const line = chunk.toString(); const latest = jobs.get(jobId); if (!latest) return; latest.progress.log.push(line.trim()); if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500); const timeMatch = line.match(/time=([0-9:.]+)/); if (timeMatch) { const secs = parseFfmpegTimeToSeconds(timeMatch[1]); if (totalDuration > 0) { latest.progress.percent = Math.min(99.5, (secs / totalDuration) * 100); latest.progress.etaSeconds = Math.max(0, totalDuration - secs); } } const sizeMatch = line.match(/size=\s*([0-9]+)kB/); if (sizeMatch) latest.progress.sizeOutBytes = Number(sizeMatch[1]) * 1024; }); ffmpeg.on("error", (err) => { const latest = jobs.get(jobId); if (!latest) return; latest.status = "failed"; latest.progress.log.push(`Failed: ${err.message}`); fsp.unlink(concatListPath).catch(() => {}); }); ffmpeg.on("close", async (code) => { const latest = jobs.get(jobId); if (!latest) return; latest._process = null; fsp.unlink(concatListPath).catch(() => {}); if (latest.status === "stopped") return; if (code === 0) { latest.status = "done"; latest.progress.percent = 100; latest.progress.etaSeconds = 0; try { const st = await fsp.stat(outPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ } latest.progress.log.push(`Merge completed. Output: ${outName}`); } else { latest.status = "failed"; latest.progress.log.push(`ffmpeg exited with code ${code}`); } }); const { _process: _p, ...safeJob } = job; return res.json({ job: safeJob }); }); // ── Folder operations ────────────────────────────────────────────────────────── app.post("/api/folders/create", async (req, res) => { const rawName = String(req.body?.folderName || req.body?.name || "").trim(); const rawParent = String(req.body?.parent || "").trim(); if (!rawName) return res.status(400).json({ error: "name is required" }); const safeName = sanitizeSegment(rawName, "folder"); const safeParent = sanitizeFolderPath(rawParent); const parentDir = safeParent && safeParent !== "/" ? path.join(DOWNLOADS_DIR, safeParent) : DOWNLOADS_DIR; const newDir = path.join(parentDir, safeName); if (!newDir.startsWith(DOWNLOADS_DIR)) return res.status(400).json({ error: "Invalid path" }); try { await fsp.mkdir(newDir, { recursive: true }); const relPath = path.relative(DOWNLOADS_DIR, newDir); return res.json({ ok: true, folder: `/${relPath}` }); } catch (err) { return res.status(500).json({ error: err.message }); } }); app.post("/api/folders/rename", async (req, res) => { const rawFolder = String(req.body?.oldPath || req.body?.folder || "").trim(); const rawNewName = String(req.body?.newName || "").trim(); if (!rawFolder || rawFolder === "/") return res.status(400).json({ error: "folder is required" }); if (!rawNewName) return res.status(400).json({ error: "newName is required" }); const safeFolder = sanitizeFolderPath(rawFolder); const oldDir = path.join(DOWNLOADS_DIR, safeFolder); if (!oldDir.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" }); const parentDir = path.dirname(oldDir); const safeName = sanitizeSegment(rawNewName, "folder"); const newDir = path.join(parentDir, safeName); if (!newDir.startsWith(DOWNLOADS_DIR)) return res.status(400).json({ error: "Invalid path" }); try { await fsp.access(oldDir); await fsp.rename(oldDir, newDir); const relPath = path.relative(DOWNLOADS_DIR, newDir); return res.json({ ok: true, folder: `/${relPath}` }); } catch (err) { return res.status(500).json({ error: err.message }); } }); app.delete("/api/folders", async (req, res) => { const rawFolder = String(req.body?.folderPath || req.body?.folder || "").trim(); if (!rawFolder || rawFolder === "/") return res.status(400).json({ error: "folder path is required" }); const safeFolder = sanitizeFolderPath(rawFolder); const dirPath = path.join(DOWNLOADS_DIR, safeFolder); if (!dirPath.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" }); try { await fsp.rm(dirPath, { recursive: true, force: true }); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ error: err.message }); } }); app.get("/api/folders/zip", async (req, res) => { const rawFolder = String(req.query?.folder || "").trim(); if (!rawFolder || rawFolder === "/") return res.status(400).json({ error: "folder query param is required" }); const safeFolder = sanitizeFolderPath(rawFolder); const dirPath = path.join(DOWNLOADS_DIR, safeFolder); if (!dirPath.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" }); try { await fsp.access(dirPath); } catch { return res.status(404).json({ error: "Folder not found" }); } const folderName = path.basename(dirPath); res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Disposition", `attachment; filename="${encodeURIComponent(folderName)}.zip"`); try { const archiver = (await import("archiver")).default; const archive = archiver("zip", { zlib: { level: 0 } }); // level 0 = store only (fast) archive.on("error", (err) => { console.error("zip error", err); res.end(); }); archive.pipe(res); archive.directory(dirPath, folderName); await archive.finalize(); } catch (err) { console.error("archiver error", err); if (!res.headersSent) res.status(500).json({ error: err.message }); } }); app.post("/api/folders/upload-zip", upload.any(), async (req, res) => { const rawFolder = String(req.body?.folderPath || req.body?.folder || "").trim(); const files = Array.isArray(req.files) ? req.files : []; const uploadedFile = files[0]; if (!uploadedFile) return res.status(400).json({ error: "No file uploaded" }); const safeFolder = sanitizeFolderPath(rawFolder); const targetDir = safeFolder && safeFolder !== "/" ? path.join(DOWNLOADS_DIR, safeFolder) : DOWNLOADS_DIR; if (!targetDir.startsWith(DOWNLOADS_DIR)) return res.status(400).json({ error: "Invalid path" }); try { await fsp.mkdir(targetDir, { recursive: true }); const tmpZip = path.join(DOWNLOADS_DIR, `_upload_zip_${Date.now()}.zip`); await fsp.writeFile(tmpZip, uploadedFile.buffer); const unzipper = (await import("unzipper")).default; await new Promise((resolve, reject) => { fs.createReadStream(tmpZip) .pipe(unzipper.Extract({ path: targetDir })) .on("close", resolve) .on("error", reject); }); await fsp.unlink(tmpZip).catch(() => {}); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ error: err.message }); } }); app.post("/api/files/:id/move", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); if (!info) return res.status(400).json({ error: "Invalid file id" }); const rawDest = String(req.body?.targetFolder || req.body?.destFolder || "").trim(); const safeFolder = sanitizeFolderPath(rawDest); const rootDir = info.source === "encoded" ? ENCODED_DIR : DOWNLOADS_DIR; const destDir = safeFolder && safeFolder !== "/" ? path.join(rootDir, safeFolder) : rootDir; if (!destDir.startsWith(rootDir)) return res.status(400).json({ error: "Invalid destination" }); try { await fsp.access(info.filePath); await fsp.mkdir(destDir, { recursive: true }); const { name: newName, fullPath: newPath } = getUniqueFilePath(destDir, info.name); await fsp.rename(info.filePath, newPath); const relPath = path.relative(rootDir, newPath); return res.json({ ok: true, id: `${info.source}:${relPath}`, name: newName, folder: safeFolder || "/" }); } catch (err) { return res.status(500).json({ error: err.message }); } }); app.post("/api/batch/move", async (req, res) => { const ids = Array.isArray(req.body?.ids) ? req.body.ids : []; const rawDest = String(req.body?.targetFolder || req.body?.destFolder || "").trim(); const safeFolder = sanitizeFolderPath(rawDest); if (!ids.length) return res.status(400).json({ error: "ids array is required" }); const results = []; for (const id of ids) { const info = resolveFileFromId(String(id)); if (!info) { results.push({ id, ok: false, error: "Invalid id" }); continue; } const rootDir = info.source === "encoded" ? ENCODED_DIR : DOWNLOADS_DIR; const destDir = safeFolder && safeFolder !== "/" ? path.join(rootDir, safeFolder) : rootDir; if (!destDir.startsWith(rootDir)) { results.push({ id, ok: false, error: "Invalid destination" }); continue; } try { await fsp.access(info.filePath); await fsp.mkdir(destDir, { recursive: true }); const { name: newName, fullPath: newPath } = getUniqueFilePath(destDir, info.name); await fsp.rename(info.filePath, newPath); const relPath = path.relative(rootDir, newPath); results.push({ id, ok: true, newId: `${info.source}:${relPath}`, name: newName, folder: safeFolder || "/" }); } catch (err) { results.push({ id, ok: false, error: err.message }); } } return res.json({ ok: true, results }); }); // ── Batch operations ─────────────────────────────────────────────────────────── app.post("/api/batch/delete", async (req, res) => { const ids = Array.isArray(req.body?.ids) ? req.body.ids : []; if (!ids.length) return res.status(400).json({ error: "ids array is required" }); const results = []; for (const id of ids) { const info = resolveFileFromId(String(id)); if (!info) { results.push({ id, ok: false, error: "Invalid id" }); continue; } try { await fsp.unlink(info.filePath); results.push({ id, ok: true }); } catch { results.push({ id, ok: false, error: "Not found" }); } } return res.json({ ok: true, results }); }); app.post("/api/batch/pixeldrain", async (req, res) => { const ids = Array.isArray(req.body?.ids) ? req.body.ids : []; if (!ids.length) return res.status(400).json({ error: "ids array is required" }); const PIXELDRAIN_API_KEY = process.env.PIXELDRAIN_API_KEY || ""; const jobIds = []; for (const id of ids) { const info = resolveFileFromId(String(id)); if (!info) continue; try { await fsp.access(info.filePath); } catch { continue; } const st = await fsp.stat(info.filePath); const pdJobId = randomId("pd"); const pdJob = { id: pdJobId, createdAt: Date.now(), status: "running", filename: info.name, bytesUploaded: 0, totalBytes: st.size, pixeldrainUrl: null, error: null, }; pixeldrainJobs.set(pdJobId, pdJob); jobIds.push(pdJobId); (async (localInfo, localSt, localJob) => { try { const fileStream = fs.createReadStream(localInfo.filePath); let bytesRead = 0; fileStream.on("data", (chunk) => { bytesRead += chunk.length; localJob.bytesUploaded = bytesRead; }); const headers = { "Content-Type": "application/octet-stream", "Content-Length": String(localSt.size), }; if (PIXELDRAIN_API_KEY) { headers["Authorization"] = `Basic ${Buffer.from(`:${PIXELDRAIN_API_KEY}`).toString("base64")}`; } const url = `https://pixeldrain.com/api/file/${encodeURIComponent(localInfo.name)}`; const response = await new Promise((resolve, reject) => { const parsedUrl = new URL(url); const opts = { hostname: parsedUrl.hostname, path: parsedUrl.pathname + parsedUrl.search, method: "PUT", headers }; const r = https.request(opts, resolve); r.on("error", reject); fileStream.pipe(r); }); let body = ""; await new Promise((resolve) => { response.on("data", (d) => { body += d.toString(); }); response.on("end", resolve); }); const result = JSON.parse(body); if (result.id) { localJob.status = "done"; localJob.bytesUploaded = localSt.size; localJob.pixeldrainUrl = `https://pixeldrain.com/u/${result.id}`; } else { localJob.status = "failed"; localJob.error = result.message || "Upload failed"; } } catch (err) { localJob.status = "failed"; localJob.error = err.message || "Upload failed"; } })(info, st, pdJob); } return res.json({ ok: true, jobIds }); }); // ── Batch Zip ────────────────────────────────────────────────────────────────── app.post("/api/batch/zip", async (req, res) => { const ids = Array.isArray(req.body?.fileIds) ? req.body.fileIds : []; if (ids.length < 1) return res.status(400).json({ error: "fileIds array is required" }); const resolvedFiles = []; for (const id of ids) { const info = resolveFileFromId(String(id)); if (!info) continue; try { await fsp.access(info.filePath); resolvedFiles.push(info); } catch { /* skip missing */ } } if (resolvedFiles.length === 0) return res.status(400).json({ error: "No valid files to zip" }); // Generate unique zip filename const timestamp = new Date().toISOString().slice(0, 19).replace(/[T:]/g, "-"); const { name: zipName, fullPath: zipPath } = getUniqueFilePath(DOWNLOADS_DIR, `archive_${timestamp}.zip`); try { const archiver = (await import("archiver")).default; const archive = archiver("zip", { zlib: { level: 5 } }); const output = fs.createWriteStream(zipPath); await new Promise((resolve, reject) => { output.on("close", resolve); archive.on("error", reject); archive.pipe(output); for (const f of resolvedFiles) { archive.file(f.filePath, { name: path.basename(f.filePath) }); } archive.finalize(); }); return res.json({ ok: true, filename: zipName, fileCount: resolvedFiles.length }); } catch (err) { // Clean up partial zip on failure await fsp.unlink(zipPath).catch(() => {}); return res.status(500).json({ error: err.message || "Failed to create zip" }); } }); // ── Unzip archive ────────────────────────────────────────────────────────────── app.post("/api/files/:id/unzip", async (req, res) => { const info = resolveFileFromId(decodeURIComponent(String(req.params.id || ""))); if (!info) return res.status(400).json({ error: "Invalid file id" }); try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); } const ext = info.name.toLowerCase(); const isZip = ext.endsWith(".zip"); const isTar = ext.endsWith(".tar") || ext.endsWith(".tar.gz") || ext.endsWith(".tgz") || ext.endsWith(".tar.xz") || ext.endsWith(".tar.bz2"); if (!isZip && !isTar) { return res.status(400).json({ error: "Unsupported archive format. Supported: .zip, .tar, .tar.gz, .tgz, .tar.xz, .tar.bz2" }); } // Create output folder named after the archive (without extension) in the same directory const sourceDir = path.dirname(info.filePath); let baseName = path.parse(info.name).name; // Handle double extensions like .tar.gz if (baseName.toLowerCase().endsWith(".tar")) baseName = baseName.slice(0, -4); // Find a unique folder name let outDirName = baseName; let outDir = path.join(sourceDir, outDirName); let idx = 1; while (fs.existsSync(outDir)) { outDirName = `${baseName} (${idx})`; outDir = path.join(sourceDir, outDirName); idx++; } await fsp.mkdir(outDir, { recursive: true }); try { if (isZip) { const unzipper = (await import("unzipper")).default; await new Promise((resolve, reject) => { fs.createReadStream(info.filePath) .pipe(unzipper.Extract({ path: outDir })) .on("close", resolve) .on("error", reject); }); } else if (isTar) { // Use system tar command for .tar, .tar.gz, .tar.xz, .tar.bz2 await runProcess("tar", ["-xf", info.filePath, "-C", outDir]); } // Count extracted files let fileCount = 0; const countFiles = async (dir) => { const entries = await fsp.readdir(dir, { withFileTypes: true }); for (const e of entries) { if (e.isFile()) fileCount++; else if (e.isDirectory()) await countFiles(path.join(dir, e.name)); } }; await countFiles(outDir); // Compute relative output folder path const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR; const relOutDir = path.relative(base, outDir); const outputFolder = relOutDir ? `/${relOutDir}` : "/"; return res.json({ ok: true, outputFolder, fileCount }); } catch (err) { // Clean up on failure await fsp.rm(outDir, { recursive: true, force: true }).catch(() => {}); return res.status(500).json({ error: err.message || "Extraction failed" }); } }); // ── Remote Server Browser ────────────────────────────────────────────────────── const remoteDownloadJobs = new Map(); // Test endpoint to check if a URL is reachable from HuggingFace app.get("/api/remote/test", async (req, res) => { const testUrl = String(req.query.url || "").trim(); if (!testUrl) return res.status(400).json({ error: "url query param required" }); console.log(`[Remote Test] Testing connectivity to: ${testUrl}`); const startTime = Date.now(); try { const response = await fetchWithTimeout(testUrl, { method: "HEAD" }, 5000); const elapsed = Date.now() - startTime; console.log(`[Remote Test] Success: ${response.status} in ${elapsed}ms`); return res.json({ ok: true, reachable: true, status: response.status, statusText: response.statusText, responseTimeMs: elapsed, headers: Object.fromEntries(response.headers.entries()), }); } catch (err) { const elapsed = Date.now() - startTime; console.log(`[Remote Test] Failed after ${elapsed}ms: ${err.message}`); return res.json({ ok: false, reachable: false, error: err.message, responseTimeMs: elapsed, suggestion: "HuggingFace Spaces may block connections to non-standard ports. Try using ports 80, 443, or 8080. Also ensure the remote server is running and publicly accessible.", }); } }); app.get("/api/remote/list", async (req, res) => { const baseUrl = String(req.query.url || "").trim().replace(/\/+$/, ""); if (!baseUrl) return res.status(400).json({ error: "url query param is required" }); // Send response quickly - don't let HF gateway timeout const startTime = Date.now(); // Helper to parse JSON array response from custom Python server function parseJsonListing(text) { const json = JSON.parse(text); const arr = Array.isArray(json) ? json : []; return arr.map((item) => { const size = typeof item.size === "number" ? item.size : parseInt(item.size) || 0; const isDir = item.type === "directory" || item.type === "dir" || item.type === "folder"; return { name: String(item.name || "unknown"), isDir, size, sizeStr: isDir ? "-" : (size > 0 ? fmtBytesSimple(size) : "0 B"), type: item.type || "file", }; }); } // Helper to parse HTML directory listing (Apache/Nginx/Python SimpleHTTPServer) function parseHtmlListing(html) { const entries = []; // Match name patterns const linkRegex = /]*href="([^"]+)"[^>]*>([^<]*)<\/a>/gi; let match; while ((match = linkRegex.exec(html)) !== null) { const href = match[1]; const text = match[2].trim(); // Skip parent directory, query strings, absolute URLs, and anchors if (!href || href === "../" || href === ".." || href.startsWith("?") || href.startsWith("#") || href.startsWith("http://") || href.startsWith("https://") || href.startsWith("/") || text === "Parent Directory" || text === "..") continue; const isDir = href.endsWith("/"); const name = decodeURIComponent(isDir ? href.slice(0, -1) : href); if (!name) continue; // Try to extract size from the line (common in autoindex) let size = 0; const lineAfter = html.substring(match.index + match[0].length, match.index + match[0].length + 100); const sizeMatch = lineAfter.match(/(\d+(?:\.\d+)?)\s*([KMGT]i?B?)/i); if (sizeMatch) { const num = parseFloat(sizeMatch[1]); const unit = sizeMatch[2].toUpperCase().replace("I", ""); if (unit.startsWith("K")) size = Math.round(num * 1024); else if (unit.startsWith("M")) size = Math.round(num * 1024 * 1024); else if (unit.startsWith("G")) size = Math.round(num * 1024 * 1024 * 1024); else if (unit.startsWith("T")) size = Math.round(num * 1024 * 1024 * 1024 * 1024); } entries.push({ name, isDir, size, sizeStr: size ? fmtBytesSimple(size) : (isDir ? "-" : undefined), type: isDir ? "directory" : "file", }); } return entries; } try { // Strategy 1: Try GET /files (custom Python server API) let entries = null; let fetchError = null; console.log(`[Remote] Attempting to list files from: ${baseUrl}`); try { console.log(`[Remote] Strategy 1: GET ${baseUrl}/files`); const response = await fetchWithTimeout(`${baseUrl}/files`, { headers: { "Accept": "application/json" }, }, 5000); // 5 second timeout console.log(`[Remote] Strategy 1 response status: ${response.status}`); if (response.ok) { const text = await response.text(); console.log(`[Remote] Strategy 1 response length: ${text.length} chars`); try { entries = parseJsonListing(text); console.log(`[Remote] Strategy 1 parsed ${entries.length} entries`); } catch (parseErr) { // /files returned non-JSON, not a custom API server fetchError = `GET /files returned non-JSON: ${text.substring(0, 100)}`; console.log(`[Remote] Strategy 1 parse failed: ${fetchError}`); } } else { fetchError = `GET /files returned ${response.status}`; console.log(`[Remote] Strategy 1 failed: ${fetchError}`); } } catch (err) { fetchError = err.message || "Failed to connect"; console.log(`[Remote] Strategy 1 error: ${fetchError}`); } // Strategy 2: If /files failed, try root URL for HTML directory listing if (!entries || entries.length === 0) { try { console.log(`[Remote] Strategy 2: GET ${baseUrl}/`); const rootResponse = await fetchWithTimeout(`${baseUrl}/`, {}, 5000); // 5 second timeout console.log(`[Remote] Strategy 2 response status: ${rootResponse.status}`); if (rootResponse.ok) { const html = await rootResponse.text(); console.log(`[Remote] Strategy 2 response length: ${html.length} chars`); // Try JSON first (maybe root returns JSON) try { entries = parseJsonListing(html); console.log(`[Remote] Strategy 2 parsed as JSON: ${entries.length} entries`); } catch { // Try HTML parsing const htmlEntries = parseHtmlListing(html); console.log(`[Remote] Strategy 2 parsed as HTML: ${htmlEntries.length} entries`); if (htmlEntries.length > 0) { entries = htmlEntries; fetchError = null; // HTML listing worked } } } } catch (err) { console.log(`[Remote] Strategy 2 error: ${err.message}`); // Root fetch also failed } } if (!entries || entries.length === 0) { return res.status(502).json({ error: fetchError ? `Could not list files from remote server. ${fetchError}` : "Could not list files. Server returned no parseable file listing. Make sure the server has GET /files endpoint or serves an HTML directory listing.", }); } // Sort: directories first, then files alphabetically entries.sort((a, b) => { if (a.isDir && !b.isDir) return -1; if (!a.isDir && b.isDir) return 1; return a.name.localeCompare(b.name); }); return res.json({ ok: true, entries, baseUrl }); } catch (err) { return res.status(500).json({ error: err.message || "Failed to fetch remote listing" }); } }); function fmtBytesSimple(bytes) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`; if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(2)} MB`; return `${(bytes / 1024 ** 3).toFixed(2)} GB`; } // Remote rename: PUT / with JSON body {"old_name": "...", "new_name": "..."} app.post("/api/remote/rename", async (req, res) => { const { serverUrl, oldName, newName } = req.body || {}; if (!serverUrl || !oldName || !newName) { return res.status(400).json({ error: "serverUrl, oldName and newName are required" }); } const baseUrl = String(serverUrl).trim().replace(/\/+$/, ""); try { const response = await fetchWithTimeout(`${baseUrl}/`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ old_name: oldName, new_name: newName }), }, 15000); if (!response.ok) { const text = await response.text(); return res.status(response.status).json({ error: text || `Remote returned ${response.status}` }); } const data = await response.json().catch(() => ({})); return res.json({ ok: true, ...data }); } catch (err) { return res.status(500).json({ error: err.message || "Remote rename failed" }); } }); // Remote delete: DELETE /?name=filename app.post("/api/remote/delete", async (req, res) => { const { serverUrl, name } = req.body || {}; if (!serverUrl || !name) { return res.status(400).json({ error: "serverUrl and name are required" }); } const baseUrl = String(serverUrl).trim().replace(/\/+$/, ""); try { const response = await fetchWithTimeout(`${baseUrl}/?name=${encodeURIComponent(name)}`, { method: "DELETE", }, 15000); if (!response.ok) { const text = await response.text(); return res.status(response.status).json({ error: text || `Remote returned ${response.status}` }); } const data = await response.json().catch(() => ({})); return res.json({ ok: true, ...data }); } catch (err) { return res.status(500).json({ error: err.message || "Remote delete failed" }); } }); // Remote upload: POST / with FormData field "file" app.post("/api/remote/upload", upload.single("file"), async (req, res) => { const serverUrl = String(req.body?.serverUrl || "").trim().replace(/\/+$/, ""); if (!serverUrl) return res.status(400).json({ error: "serverUrl is required" }); if (!req.file) return res.status(400).json({ error: "No file uploaded" }); try { // Build FormData for the remote server const formData = new FormData(); const blob = new Blob([req.file.buffer], { type: req.file.mimetype || "application/octet-stream" }); formData.append("file", blob, req.file.originalname); const response = await fetchWithTimeout(`${serverUrl}/`, { method: "POST", body: formData, }, 60000); // 60s timeout for uploads if (!response.ok) { const text = await response.text(); return res.status(response.status).json({ error: text || `Remote returned ${response.status}` }); } const data = await response.json().catch(() => ({})); return res.json({ ok: true, ...data }); } catch (err) { return res.status(500).json({ error: err.message || "Remote upload failed" }); } }); app.post("/api/remote/download", async (req, res) => { const { url, filename, targetFolder, serverUrl, remoteName } = req.body || {}; // Support both direct URL and serverUrl+remoteName for the custom Python server const downloadUrl = url || (serverUrl && remoteName ? `${String(serverUrl).trim().replace(/\/+$/, "")}/${encodeURIComponent(remoteName)}` : null); if (!downloadUrl) return res.status(400).json({ error: "url or serverUrl+remoteName is required" }); const safeFolder = sanitizeFolderPath(String(targetFolder || "")); const targetDir = safeFolder && safeFolder !== "/" ? path.join(DOWNLOADS_DIR, safeFolder) : DOWNLOADS_DIR; await fsp.mkdir(targetDir, { recursive: true }); const dlJobId = randomId("rdl"); const dlJob = { id: dlJobId, createdAt: Date.now(), status: "running", url: String(url), filename: filename || null, bytesDownloaded: 0, totalBytes: 0, error: null, targetFolder: safeFolder || "/", abortController: new AbortController(), }; remoteDownloadJobs.set(dlJobId, dlJob); res.json({ ok: true, jobId: dlJobId }); (async () => { try { const response = await fetch(downloadUrl, { signal: dlJob.abortController.signal }); if (!response.ok || !response.body) { dlJob.status = "failed"; dlJob.error = `Server returned ${response.status}`; return; } const contentLength = response.headers.get("content-length"); dlJob.totalBytes = contentLength ? Number(contentLength) : 0; const requestedName = filename || remoteName || getFilenameFromHeaders(response, downloadUrl); const { name: finalName, fullPath: destPath } = getUniqueFilePath(targetDir, requestedName); dlJob.filename = finalName; const fileStream = fs.createWriteStream(destPath); const nodeReadable = Readable.fromWeb(response.body); nodeReadable.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; }); await new Promise((resolve, reject) => { nodeReadable.on("error", reject); fileStream.on("error", reject); fileStream.on("finish", resolve); nodeReadable.pipe(fileStream); }); dlJob.status = "done"; } catch (err) { if (err.name === "AbortError") dlJob.status = "stopped"; else { dlJob.status = "failed"; dlJob.error = err.message || "Download failed"; } } })(); }); app.get("/api/remote/download-jobs/:id", (req, res) => { const dlJob = remoteDownloadJobs.get(req.params.id); if (!dlJob) return res.status(404).json({ error: "Job not found" }); const { abortController: _ac, ...safe } = dlJob; return res.json({ job: safe }); }); app.post("/api/remote/download-jobs/:id/stop", (req, res) => { const dlJob = remoteDownloadJobs.get(req.params.id); if (!dlJob) return res.status(404).json({ error: "Job not found" }); if (dlJob.status === "running") { dlJob.abortController.abort(); dlJob.status = "stopped"; } return res.json({ ok: true }); }); // ── Static / SPA fallback ────────────────────────────────────────────────────── if (fs.existsSync(distDir)) { app.use(express.static(distDir)); app.use((req, res, next) => { if (req.path.startsWith("/api")) return next(); res.sendFile(path.join(distDir, "index.html")); }); } else { console.warn(`[warn] dist/ not found at ${distDir}. Run "npm run build" first.`); } app.listen(PORT, HOST, () => { console.log(`Server running on http://${HOST}:${PORT}`); console.log(`downloads: ${DOWNLOADS_DIR}`); console.log(`encoded: ${ENCODED_DIR}`); });