import cors from "cors"; import express from "express"; import multer from "multer"; import fs from "node:fs"; import fsp from "node:fs/promises"; import crypto from "node:crypto"; 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"; import { S3Client, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand, AbortMultipartUploadCommand, CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, PutObjectCommand, } from "@aws-sdk/client-s3"; 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 }); // ── Cross-device safe move ───────────────────────────────────────────────────── // fs.rename fails with EXDEV when src and dest are on different filesystems // (e.g. /tmp → /home/runner/workspace). Fall back to copy + unlink. async function safeMoveFile(src, dest) { try { await fsp.rename(src, dest); } catch (err) { if (err.code === "EXDEV") { await fsp.copyFile(src, dest); await fsp.unlink(src); } else { throw err; } } } // ── Startup validation ──────────────────────────────────────────────────────── async function checkBinary(name) { return new Promise((resolve) => { const proc = spawn(name, ["-version"], { stdio: "pipe" }); proc.on("close", (code) => resolve(code === 0)); proc.on("error", () => resolve(false)); // timeout after 5 seconds setTimeout(() => { try { proc.kill(); } catch {}; resolve(false); }, 5000); }); } const ffmpegOk = await checkBinary("ffmpeg"); const ffprobeOk = await checkBinary("ffprobe"); if (!ffmpegOk) console.warn("[warn] ffmpeg not found on PATH — encoding, trimming, and video info will fail."); if (!ffprobeOk) console.warn("[warn] ffprobe not found on PATH — video metadata extraction will fail."); if (ffmpegOk && ffprobeOk) console.log("[ok] ffmpeg and ffprobe found on PATH."); const app = express(); // ── Basic Auth ───────────────────────────────────────────────────────────────── const AUTH_USER = process.env.APP_USERNAME || "admin"; const AUTH_PASS = process.env.APP_PASSWORD || "1234"; function basicAuth(req, res, next) { // Skip auth for internal health-check pings if needed const header = req.headers["authorization"] || ""; const match = header.match(/^Basic\s+(.+)$/i); if (match) { const decoded = Buffer.from(match[1], "base64").toString("utf8"); const colon = decoded.indexOf(":"); if (colon !== -1) { const user = decoded.slice(0, colon); const pass = decoded.slice(colon + 1); // Constant-time comparison to prevent timing attacks const userOk = user.length === AUTH_USER.length && crypto.timingSafeEqual(Buffer.from(user), Buffer.from(AUTH_USER)); const passOk = pass.length === AUTH_PASS.length && crypto.timingSafeEqual(Buffer.from(pass), Buffer.from(AUTH_PASS)); if (userOk && passOk) return next(); } } res.set("WWW-Authenticate", 'Basic realm="OgA-Encoder"'); res.status(401).send("Unauthorized"); } app.use(basicAuth); 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(); // ── Job history persistence ─────────────────────────────────────────────────── const HISTORY_FILE = path.join(projectRoot, 'data', 'jobs_history.json'); await fsp.mkdir(path.dirname(HISTORY_FILE), { recursive: true }); try { const raw = await fsp.readFile(HISTORY_FILE, 'utf8'); const hist = JSON.parse(raw); if (Array.isArray(hist)) { for (const j of hist) jobs.set(j.id, { ...j, _process: null }); console.log(`[ok] Loaded ${hist.length} historical job(s)`); } } catch { /* no history file yet */ } async function persistJobHistory() { try { const toSave = [...jobs.values()] .filter(j => j.status !== 'running') .sort((a, b) => b.createdAt - a.createdAt) .slice(0, 300) .map(({ _process: _p, ...j }) => j); await fsp.writeFile(HISTORY_FILE, JSON.stringify(toSave, null, 2), 'utf8'); } catch { /* ignore */ } } // ── App settings persistence ────────────────────────────────────────────────── const SETTINGS_FILE = path.join(projectRoot, 'data', 'app_settings.json'); let appSettings = {}; try { const raw = await fsp.readFile(SETTINGS_FILE, 'utf8'); appSettings = JSON.parse(raw); console.log('[ok] Loaded app settings'); } catch { /* no settings file yet */ } async function persistSettings(patch) { try { appSettings = { ...appSettings, ...patch }; await fsp.writeFile(SETTINGS_FILE, JSON.stringify(appSettings, null, 2), 'utf8'); } catch { /* ignore */ } } app.get('/api/settings', (req, res) => res.json(appSettings)); app.post('/api/settings', async (req, res) => { await persistSettings(req.body || {}); res.json({ ok: true }); }); 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 parseLooseClockToSeconds(value) { const parts = String(value || "").split(":").map((p) => Number(p)); if (parts.some((n) => Number.isNaN(n) || n < 0)) return null; if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2]; if (parts.length === 2) return parts[0] * 60 + parts[1]; if (parts.length === 1 && String(value || "").trim()) return parts[0]; return null; } 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}`)); }); }); } function isChildProcessRunning(child) { return Boolean(child && !child.killed && child.exitCode === null); } function stopFfmpegProcess(job, reason = "Job stopped by user.") { if (!job || job.status !== "running") return; job.status = "stopped"; job.progress?.log?.push(reason); const child = job._process; if (!isChildProcessRunning(child)) { job._process = null; return; } let escalationStarted = false; const escalateStop = () => { if (!isChildProcessRunning(child)) return; if (!escalationStarted) { escalationStarted = true; try { child.kill("SIGTERM"); } catch { /* ignore */ } setTimeout(() => { if (!isChildProcessRunning(child)) return; try { child.kill("SIGKILL"); } catch { /* ignore */ } }, 3000).unref?.(); } }; try { if (child.stdin && !child.stdin.destroyed) { child.stdin.write("q\n", (err) => { if (err) escalateStop(); }); setTimeout(escalateStop, 1500).unref?.(); return; } } catch { // fall through to signal-based stop } escalateStop(); } 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"]; const startSeconds = settings.startTime ? parseLooseClockToSeconds(String(settings.startTime)) : null; const endSeconds = settings.endTime ? parseLooseClockToSeconds(String(settings.endTime)) : null; if (startSeconds != null) args.push("-ss", String(settings.startTime)); if (endSeconds != null && (startSeconds == null || endSeconds > startSeconds)) { 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 cropEnabled = Boolean(settings.cropEnabled); const cropLeft = Number(settings.cropLeft ?? 0); const cropRight = Number(settings.cropRight ?? 0); const cropTop = Number(settings.cropTop ?? 0); const cropBottom = Number(settings.cropBottom ?? 0); const needsVideoReencode = !isAudioOnly && (!sameAsOriginalVideo || cropEnabled); const filters = []; if (!isAudioOnly && needsVideoReencode) { if (cropEnabled && (cropLeft > 0 || cropRight > 0 || cropTop > 0 || cropBottom > 0)) { const cropW = 100 - cropLeft - cropRight; const cropH = 100 - cropTop - cropBottom; const cropX = cropLeft; const cropY = cropTop; filters.push(`crop=iw*${Math.max(0, cropW) / 100}:ih*${Math.max(0, cropH) / 100}:iw*${Math.max(0, cropX) / 100}:ih*${Math.max(0, cropY) / 100}`); } 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.max(60, Math.round(fps * 2)))); // -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 && !cropEnabled) { 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=1", `aq-mode=${settings.aqMode !== undefined ? settings.aqMode : 0}`, "enable-tf=0", "enable-overlays=0", "film-grain=0", "fast-decode=1", "scd=1", ]; const tilesValue = String(settings.tiles ?? "0"); if (tilesValue === "2x2" || tilesValue === "2") svtParams.push("tile-columns=1", "tile-rows=1"); else if (tilesValue === "4") svtParams.push("tile-columns=2", "tile-rows=2"); 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) => { try { let fileId; try { fileId = decodeURIComponent(String(req.params.id || "")); } catch { return res.status(400).json({ error: "Invalid file id encoding" }); } const info = resolveFileFromId(fileId); 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" }); } } catch (err) { console.error("[download] unexpected error:", err.message, err.stack); if (!res.headersSent) res.status(500).json({ error: err.message || "Download failed" }); } }); // Video/audio streaming endpoint with Range request support (required for browser playback) app.get("/api/files/:id/stream", async (req, res) => { try { let fileId; try { fileId = decodeURIComponent(String(req.params.id || "")); } catch { return res.status(400).json({ error: "Invalid file id encoding" }); } const info = resolveFileFromId(fileId); if (!info) return res.status(400).json({ error: "Invalid file id" }); let stat; try { stat = await fsp.stat(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); } const ext = path.extname(info.name).toLowerCase(); const mimeMap = { ".mp4": "video/mp4", ".m4v": "video/mp4", ".webm": "video/webm", ".mkv": "video/x-matroska", ".mov": "video/quicktime", ".avi": "video/x-msvideo", ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".aac": "audio/aac", ".ogg": "audio/ogg", ".wav": "audio/wav", ".flac": "audio/flac", }; const contentType = mimeMap[ext] || "application/octet-stream"; const fileSize = stat.size; const rangeHeader = req.headers.range; // For bucket-mounted storage, use larger chunks (50 MB) to reduce requests // This helps with seeking performance on network-mounted buckets const MAX_CHUNK = 50 * 1024 * 1024; // 50 MB let start = 0; let end = Math.min(fileSize - 1, MAX_CHUNK - 1); if (rangeHeader) { const parts = rangeHeader.replace(/bytes=/, "").split("-"); const reqStart = parseInt(parts[0], 10); // If client specifies an end, honour it; otherwise cap at MAX_CHUNK from start const reqEnd = parts[1] ? parseInt(parts[1], 10) : reqStart + MAX_CHUNK - 1; start = reqStart; end = Math.min(reqEnd, fileSize - 1); if (isNaN(start) || isNaN(end) || start >= fileSize || start > end) { return res.status(416).set("Content-Range", `bytes */${fileSize}`).end(); } } const chunkSize = end - start + 1; res.status(206) .set("Content-Range", `bytes ${start}-${end}/${fileSize}`) .set("Accept-Ranges", "bytes") .set("Content-Length", String(chunkSize)) .set("Content-Type", contentType) .set("Cache-Control", "public, max-age=604800, immutable") .set("Connection", "keep-alive") .set("Keep-Alive", "timeout=60, max=100"); const readStream = fs.createReadStream(info.filePath, { start, end, highWaterMark: 256 * 1024 // 256 KB buffer for better bucket performance }); // Longer timeout for bucket-mounted files (network I/O slower than local) // 120 seconds to allow bucket operations to complete const streamTimeout = setTimeout(() => { readStream.destroy(); console.warn("[stream] timeout on", info.filePath, `range: ${start}-${end}`); if (!res.headersSent) res.status(504).json({ error: "Stream timeout - bucket response too slow" }); else res.destroy(); }, 120000); // 120 second timeout for bucket readStream.on("error", (err) => { clearTimeout(streamTimeout); console.error("[stream] read error:", err.message, "file:", info.filePath); if (!res.headersSent) res.status(500).json({ error: "Stream read failed" }); else res.destroy(); }); readStream.on("end", () => clearTimeout(streamTimeout)); readStream.pipe(res); } catch (err) { console.error("[stream] unexpected error:", err.message, err.stack); if (!res.headersSent) res.status(500).json({ error: err.message || "Stream failed" }); } }); 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 ──────────────────────────────────────── /** Convert a size string from aria2c output (e.g. "258MiB", "2.4GiB") to bytes */ function parseAriaSize(str) { if (!str) return 0; const m = str.trim().match(/^([\d.]+)\s*(GiB|MiB|KiB|GB|MB|KB|B)?$/i); if (!m) return 0; const n = parseFloat(m[1]); switch ((m[2] || "B").toUpperCase()) { case "GIB": return n * 1024 ** 3; case "MIB": return n * 1024 ** 2; case "KIB": return n * 1024; case "GB": return n * 1e9; case "MB": return n * 1e6; case "KB": return n * 1e3; default: return n; } } app.post("/api/download-url", async (req, res) => { const { url, username, password, useAria2 } = req.body || {}; if (!url || typeof url !== "string") return res.status(400).json({ error: "url is required" }); let cleanUrl = url; let finalUsername = username; let finalPassword = password; try { const parsed = new URL(url); if (parsed.username || parsed.password) { finalUsername = finalUsername || decodeURIComponent(parsed.username); finalPassword = finalPassword || decodeURIComponent(parsed.password); parsed.username = ""; parsed.password = ""; cleanUrl = parsed.toString(); } } catch { // ignore invalid URL parsing and use original input } const dlJobId = randomId("dl"); const dlJob = { id: dlJobId, createdAt: Date.now(), status: "running", url: cleanUrl, filename: null, bytesDownloaded: 0, totalBytes: 0, speedBytesPerSec: 0, useAria2: !!useAria2, error: null, abortController: new AbortController(), _process: null, }; downloadJobs.set(dlJobId, dlJob); res.json({ ok: true, jobId: dlJobId }); // ── Fast path: aria2c direct (16 parallel connections) ──────────────────── if (useAria2) { (async () => { try { // 1. HEAD the URL to learn filename + size (best-effort) const headHeaders = {}; if (finalUsername && finalPassword) { headHeaders.Authorization = `Basic ${Buffer.from(`${finalUsername}:${finalPassword}`).toString("base64")}`; } let guessedName = null; let guessedSize = 0; try { const head = await fetch(cleanUrl, { method: "HEAD", headers: headHeaders, signal: AbortSignal.timeout(8000) }); guessedSize = Number(head.headers.get("content-length") || 0); guessedName = getFilenameFromHeaders(head, cleanUrl); } catch { /* ignore; aria2c will still download */ } const { name: filename, fullPath: destPath } = getUniqueFilePath(DOWNLOADS_DIR, guessedName || "download"); dlJob.filename = filename; if (guessedSize > 0) dlJob.totalBytes = guessedSize; // 2. Spawn aria2c const ariaArgs = [ `-x`, `16`, `-s`, `16`, `-k`, `1M`, `--file-allocation=none`, `--auto-file-renaming=false`, `--console-log-level=error`, // suppress NOTICE noise; we poll the file `-d`, DOWNLOADS_DIR, `-o`, filename, cleanUrl, ]; if (finalUsername && finalPassword) { ariaArgs.push(`--http-user=${finalUsername}`, `--http-passwd=${finalPassword}`); } const aria = spawn("aria2c", ariaArgs, { stdio: ["pipe", "pipe", "pipe"] }); dlJob._process = aria; // 3. Track progress by polling the destination file size every second. // aria2c writes directly to destPath while downloading, so stat() works. let lastPollBytes = 0; const sizePoller = setInterval(() => { if (dlJob.status !== "running") { clearInterval(sizePoller); return; } try { const st = fs.statSync(destPath); const now = st.size; dlJob.speedBytesPerSec = Math.max(0, now - lastPollBytes); lastPollBytes = now; dlJob.bytesDownloaded = now; } catch { /* file not created yet */ } }, 1000); // 4. Collect stderr for error messages (strip ANSI codes) const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, ""); let errBuf = ""; const stderrLines = []; aria.stderr.on("data", (chunk) => { errBuf += chunk.toString(); const parts = errBuf.split(/[\r\n]+/); errBuf = parts.pop(); for (const raw of parts) { const line = stripAnsi(raw).trim(); if (line) stderrLines.push(line); } }); // stdout is minimal with --console-log-level=error; drain it anyway aria.stdout.on("data", () => {}); aria.on("error", (err) => { clearInterval(sizePoller); dlJob._process = null; dlJob.status = "failed"; dlJob.error = `Failed to launch aria2c: ${err.message}`; }); aria.on("close", (code) => { clearInterval(sizePoller); dlJob._process = null; if (dlJob.status === "stopped") return; if (code === 0) { dlJob.status = "done"; // Final size from disk try { dlJob.bytesDownloaded = fs.statSync(destPath).size; } catch {} if (dlJob.totalBytes === 0) dlJob.totalBytes = dlJob.bytesDownloaded; dlJob.speedBytesPerSec = 0; } else { dlJob.status = "failed"; // Surface first meaningful error line from stderr const errLine = stderrLines.find((l) => /error|exception|fail/i.test(l)); dlJob.error = errLine || `aria2c exited with code ${code}`; } }); } catch (err) { dlJob.status = "failed"; dlJob.error = err.message || "Fast download failed"; } })(); return; } // ── Standard path: single-connection Node fetch ──────────────────────────── const headers = {}; if (finalUsername && finalPassword) { headers.Authorization = `Basic ${Buffer.from(`${finalUsername}:${finalPassword}`).toString("base64")}`; } (async () => { let lastBytes = 0, lastTime = Date.now(); try { const response = await fetch(cleanUrl, { headers, signal: dlJob.abortController.signal }); if (!response.ok || !response.body) { dlJob.status = "failed"; dlJob.error = `Server returned ${response.status} for ${cleanUrl}`; 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; const now = Date.now(); const elapsed = (now - lastTime) / 1000; if (elapsed >= 0.5) { dlJob.speedBytesPerSec = (dlJob.bytesDownloaded - lastBytes) / elapsed; lastBytes = dlJob.bytesDownloaded; lastTime = now; } }); await new Promise((resolve, reject) => { nodeReadable.on("error", reject); fileStream.on("error", reject); fileStream.on("finish", resolve); nodeReadable.pipe(fileStream); }); dlJob.status = "done"; dlJob.speedBytesPerSec = 0; } 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, _process: _p, ...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.status = "stopped"; if (dlJob._process) { try { dlJob._process.kill("SIGTERM"); } catch {} dlJob._process = null; } else if (dlJob.abortController) { dlJob.abortController.abort(); } } 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" }); } // Resolve input: prefer fileId (works for both downloaded + encoded), fall back to DOWNLOADS_DIR let inputPath; if (settings.fileId) { const info = resolveFileFromId(String(settings.fileId)); if (!info) return res.status(400).json({ error: "Invalid fileId" }); inputPath = info.filePath; } else { const rawInput = String(settings.inputFilename || ""); 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" }); } 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); job.progress.log.push(`ffmpeg ${args.map((a) => String(a)).join(" ")}`); const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "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; const speedMatch = line.match(/speed=\s*([0-9.]+)x/); if (speedMatch) latest.progress.speed = Number(speedMatch[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") { const stoppedOutputPath = tempOutputPath; const resolution = await getVideoResolution(stoppedOutputPath); const parsedOutput = path.parse(stoppedOutputPath); const cleanedBase = parsedOutput.name .replace(/_encoded(?:_\d+x\d+)?$/i, ""); const desiredName = `${cleanedBase}_stopped_${resolution}${parsedOutput.ext}`; const { name: finalName, fullPath: finalPath } = getUniqueFilePath(ENCODED_DIR, desiredName); let actualPath = stoppedOutputPath; try { await fsp.access(stoppedOutputPath); await safeMoveFile(stoppedOutputPath, finalPath); actualPath = finalPath; } catch { // keep original path if rename/access fails } latest.outputFolder = "/"; latest.outputSource = "encoded"; try { const st = await fsp.stat(actualPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ } latest.outputFilename = path.basename(actualPath); latest.progress.log.push(`Encode stopped. Partial output kept: ${path.basename(actualPath)}`); persistJobHistory(); return; } if (code === 0) { const resolution = await getVideoResolution(tempOutputPath); const parsedOutput = path.parse(tempOutputPath); const cleanedBase = parsedOutput.name .replace(/_encoded(?:_\d+x\d+)?$/i, ""); const desiredName = `${cleanedBase}_encoded_${resolution}${parsedOutput.ext}`; const { name: finalName, fullPath: finalPath } = getUniqueFilePath(ENCODED_DIR, desiredName); try { await safeMoveFile(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.outputFilename = path.basename(actualPath); 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 } persistJobHistory(); } else { latest.status = "failed"; latest.progress.log.push(`ffmpeg exited with code ${code}`); persistJobHistory(); } }); 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" }); stopFfmpegProcess(job); 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 }); }); app.delete("/api/jobs/finished", async (_req, res) => { for (const [id, job] of jobs.entries()) { if (job.status !== "running") jobs.delete(id); } await persistJobHistory(); return res.json({ ok: true }); }); // ── 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 audioStreams = streams.filter((s) => s.codec_type === "audio"); const subtitleStreams = streams.filter((s) => s.codec_type === "subtitle"); const audioStream = audioStreams[0]; 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; } } // Load saved crop settings from .crop.json sidecar (created by trim-segments) let savedCropSettings = null; try { const cropSettingsPath = `${info.filePath}.crop.json`; const cropRaw = await fsp.readFile(cropSettingsPath, "utf8"); savedCropSettings = JSON.parse(cropRaw); } catch { savedCropSettings = 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, audioStreams: audioStreams.map((stream) => { const streamBitrate = parseInt(stream.bit_rate || 0); const streamSize = durationSec > 0 && streamBitrate > 0 ? Math.round((streamBitrate / 8) * durationSec) : null; return { index: typeof stream.index === "number" ? stream.index : -1, codec: stream.codec_name || "unknown", sampleRate: stream.sample_rate ? `${stream.sample_rate} Hz` : "unknown", channels: stream.channels || "unknown", channelLayout: stream.channel_layout || "unknown", bitrate: fmtBitrate(streamBitrate), bitrateRaw: streamBitrate, streamSize: streamSize ? fmtBytes(streamSize) : "unknown", language: stream.tags?.language || "unknown", title: stream.tags?.title || "", }; }), subtitleStreams: subtitleStreams.map((stream) => ({ index: typeof stream.index === "number" ? stream.index : -1, codec: stream.codec_name || "unknown", language: stream.tags?.language || "unknown", title: stream.tags?.title || "", forced: Boolean(stream.disposition?.forced), default: Boolean(stream.disposition?.default), })), encodeSettings, savedCropSettings, }, }); } 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: ["pipe", "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); if (job.status === "stopped") { try { const st = await fsp.stat(outPath); job.progress.sizeOutBytes = st.size; } catch { /* ignore */ } job.progress.log.push(`Trim stopped. Partial output kept: ${outName}`); return; } 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: ["pipe", "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") { try { const st = await fsp.stat(outPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ } latest.progress.log.push(`Merge stopped. Partial output kept: ${outName}`); 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(); const isRoot = !rawFolder || rawFolder === "/"; let dirPath, zipFilename; if (isRoot) { dirPath = DOWNLOADS_DIR; zipFilename = "root"; } else { const safeFolder = sanitizeFolderPath(rawFolder); dirPath = path.join(DOWNLOADS_DIR, safeFolder); if (!dirPath.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" }); zipFilename = path.basename(dirPath); } try { await fsp.access(dirPath); } catch { return res.status(404).json({ error: "Folder not found" }); } res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Disposition", `attachment; filename="${encodeURIComponent(zipFilename)}.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, zipFilename); 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" }); } }); function isHfBucketUrl(url) { const m = String(url).match(/^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\/([^\/]+)\/([^\/]+)(?:\/tree(?:\/(.*))?)?$/); if (m) return { org: m[1], bucket: m[2], path: (m[3]||"").replace(/\/+$/, "") }; return null; } async function listHfBucket(org, bucket, prefix, hfToken) { const api = `https://huggingface.co/api/buckets/${encodeURIComponent(org)}/${encodeURIComponent(bucket)}/tree/${encodeURIComponent(prefix||"")}`; const headers = { "Accept": "application/json", "User-Agent": "Mozilla/5.0" }; if (hfToken) headers.Authorization = `Bearer ${hfToken}`; const r = await fetchWithTimeout(api, { headers }, 10000); if (!r.ok) throw new Error("HF Bucket API returned " + r.status); const items = await r.json(); const prefixStr = prefix ? prefix.replace(/\/+$/,"")+"/" : ""; const seen = new Set(); const out = []; for (const item of items) { const rel = item.path.startsWith(prefixStr) ? item.path.slice(prefixStr.length) : item.path; if (!rel) continue; if (item.type === "directory") { const n = rel.replace(/\/+$/,"").split("/")[0]; if (n && !seen.has("d:"+n)) { seen.add("d:"+n); out.push({name:n,isDir:true,size:0,sizeStr:"-",type:"directory"}); } } else { const parts = rel.split("/"); if (parts.length>1) { const n = parts[0]; if (!seen.has("d:"+n)) { seen.add("d:"+n); out.push({name:n,isDir:true,size:0,sizeStr:"-",type:"directory"}); } } else { const n = parts[0]; if (!seen.has("f:"+n)) { seen.add("f:"+n); out.push({name:n,isDir:false,size:item.size||0,sizeStr:item.size?fmtBytesSimple(item.size):"0 B",type:"file",hfPath:item.path,hfOrg:org,hfBucket:bucket}); } } } } return out; } async function listAllHfBucketFiles(org, bucket, prefix, hfToken) { const api = `https://huggingface.co/api/buckets/${encodeURIComponent(org)}/${encodeURIComponent(bucket)}/tree/${encodeURIComponent(prefix||"")}?recursive=true`; const headers = { "Accept": "application/json", "User-Agent": "Mozilla/5.0" }; if (hfToken) headers.Authorization = `Bearer ${hfToken}`; const r = await fetchWithTimeout(api, { headers }, 15000); if (!r.ok) throw new Error("HF Bucket recursive API returned " + r.status); const items = await r.json(); return items .filter((item) => item.type === "file") .map((item) => ({ name: item.path.split("/").pop() || item.path, hfPath: item.path, hfOrg: org, hfBucket: bucket, size: item.size || 0, })); } // ── TeleBox helpers ──────────────────────────────────────────────────────────── async function teleboxRequest(endpoint, params, options = {}) { const url = new URL(`https://www.telebox.online${endpoint}`); for (const [k, v] of Object.entries(params || {})) { if (v !== undefined && v !== null) url.searchParams.set(k, String(v)); } const r = await fetchWithTimeout(url.toString(), { headers: { "Accept": "application/json", "User-Agent": "Mozilla/5.0", }, }, 15000); const data = await r.json().catch(() => null); if (!r.ok) throw new Error(`TeleBox HTTP ${r.status}`); if (!data) throw new Error("TeleBox returned non-JSON"); const allowMsgs = Array.isArray(options.allowMsgs) ? options.allowMsgs : []; const msg = String(data.msg || ""); if (typeof data.status !== "undefined" && Number(data.status) !== 1) { if (allowMsgs.some((s) => msg.toLowerCase().includes(String(s).toLowerCase()))) { return data; } throw new Error(data.msg || `TeleBox status ${data.status}`); } return data; } // ── TeleBox API routes ───────────────────────────────────────────────────────── app.get("/api/telebox/list", async (req, res) => { const token = String(req.query.token || "").trim(); const pid = String(req.query.pid || "0").trim(); if (!token) return res.status(400).json({ error: "token is required" }); try { const data = await teleboxRequest("/api/open/file_search", { name: "", pid, pageNo: 1, pageSize: 200, token, }); const items = Array.isArray(data?.data?.list) ? data.data.list : []; const entries = items.map((item) => { const isDir = String(item.type || "").toLowerCase().includes("dir"); return { id: String(item.id || item.item_id || ""), itemId: item.item_id ? String(item.item_id) : undefined, name: String(item.name || "unknown"), isDir, size: Number(item.size || 0), sizeStr: isDir ? "-" : fmtBytesSimple(Number(item.size || 0)), type: String(item.type || (isDir ? "dir" : "file")), subType: item.sub_type ? String(item.sub_type) : undefined, pid: Number(item.pid || 0), }; }); return res.json({ ok: true, entries, pid: Number(pid) }); } catch (err) { return res.status(500).json({ error: err.message || "TeleBox list failed" }); } }); app.post("/api/telebox/folder-create", async (req, res) => { const { token, pid, name } = req.body || {}; if (!token) return res.status(400).json({ error: "token is required" }); if (!name) return res.status(400).json({ error: "name is required" }); try { const data = await teleboxRequest("/api/open/folder_create", { name, pid: Number(pid || 0), token, isShare: 0, canInvite: 0, canShare: 0, withBodyImg: 0, desc: "", }); return res.json({ ok: true, dirId: data?.data?.dirId ?? null }); } catch (err) { return res.status(500).json({ error: err.message || "TeleBox folder create failed" }); } }); app.post("/api/telebox/download", async (req, res) => { const { token, webToken, itemId, filename, targetFolder } = req.body || {}; const sessionToken = String(webToken || token || "").trim(); if (!sessionToken) return res.status(400).json({ error: "webToken (or token) is required" }); if (!itemId) return res.status(400).json({ error: "itemId is required" }); try { const detailUrl = new URL("https://www.telebox.online/api/file/detail"); detailUrl.searchParams.set("itemId", String(itemId)); detailUrl.searchParams.set("needUser", "1"); detailUrl.searchParams.set("needTpInfo", "1"); detailUrl.searchParams.set("token", sessionToken); detailUrl.searchParams.set("platform", "web"); detailUrl.searchParams.set("pf", "web"); detailUrl.searchParams.set("lan", "en"); const detailResp = await fetchWithTimeout(detailUrl.toString(), { headers: { "Accept": "application/json", "User-Agent": "Mozilla/5.0", }, }, 15000); const detail = await detailResp.json().catch(() => null); if (!detailResp.ok) { return res.status(500).json({ error: `TeleBox detail HTTP ${detailResp.status}`, debug: detail }); } const item = detail?.data?.itemInfo || null; const dlUrl = item?.resolutionList?.[0]?.url || item?.url || null; if (!dlUrl) { return res.status(500).json({ error: "TeleBox detail did not return a downloadable URL", debug: detail }); } 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("tbxdl"); const dlJob = { id: dlJobId, createdAt: Date.now(), status: "running", url: String(dlUrl), filename: filename || item?.name || 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(dlUrl, { signal: dlJob.abortController.signal, headers: { "user-agent": USER_AGENT, "accept": "*/*", }, redirect: "follow", }); if (!response.ok || !response.body) { throw new Error(`TeleBox download HTTP ${response.status}`); } const requestedName = filename || item?.name || getFilenameFromHeaders(response, dlUrl); const outName = ensureUniqueFilename(targetDir, sanitizeFilename(requestedName || "telebox.bin")); const outPath = path.join(targetDir, outName); dlJob.filename = outName; dlJob.totalBytes = Number(response.headers.get("content-length") || item?.size || 0); await streamResponseToFile(response, outPath, dlJob); dlJob.status = "done"; dlJob.completedAt = Date.now(); dlJob.localPath = outPath; } catch (err) { dlJob.status = "error"; dlJob.error = err?.message || "TeleBox download failed"; dlJob.completedAt = Date.now(); } })(); } catch (err) { return res.status(500).json({ error: err?.message || "TeleBox download setup failed" }); } }); app.post("/api/telebox/upload", upload.array("files"), async (req, res) => { const token = String(req.body?.token || "").trim(); const pid = Number(req.body?.pid || 0); if (!token) return res.status(400).json({ error: "token is required" }); const files = Array.isArray(req.files) ? req.files : []; if (!files.length) return res.status(400).json({ error: "No files uploaded" }); const results = []; try { for (const file of files) { const pre10m = file.buffer.subarray(0, Math.min(file.buffer.length, 10 * 1024 * 1024)); const crypto = await import("node:crypto"); const md5 = crypto.createHash("md5").update(pre10m).digest("hex"); const auth = await teleboxRequest("/api/open/get_upload_url", { fileMd5ofPre10m: md5, fileSize: file.size, token, }, { allowMsgs: ["not need upload"], }); console.log("TELEBOX UPLOAD auth response:", JSON.stringify(auth, null, 2)); const signUrl = auth?.data?.signUrl; const skipUpload = !signUrl && /not need upload/i.test(String(auth?.msg || "")); if (!signUrl && !skipUpload) { throw new Error(`TeleBox did not return signUrl: ${JSON.stringify(auth)}`); } if (!skipUpload) { const putResp = await fetch(signUrl, { method: "PUT", body: file.buffer, headers: { "Content-Length": String(file.size), }, }); if (!putResp.ok) { throw new Error(`TeleBox upload PUT failed with ${putResp.status}`); } } else { console.log("TELEBOX UPLOAD skipping PUT because API said not need upload"); } console.log("TELEBOX UPLOAD file:", JSON.stringify({ name: file.originalname, size: file.size, pid, md5 }, null, 2)); const finish = await teleboxRequest("/api/open/folder_upload_file", { fileMd5ofPre10m: md5, fileSize: file.size, pid, diyName: file.originalname, token, }); console.log("TELEBOX UPLOAD finish response:", JSON.stringify(finish, null, 2)); results.push({ ok: true, name: file.originalname, itemId: finish?.data?.itemId || finish?.data?.item_id || finish?.itemId || finish?.item_id || null, }); } return res.json({ ok: true, results }); } catch (err) { return res.status(500).json({ error: err.message || "TeleBox upload failed", results }); } }); // ── 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(/\/+$/, ""); const remotePath = String(req.query.path || "").trim().replace(/^\//, "").replace(/\/+$/, ""); const listPath = remotePath ? "/" + remotePath : ""; const hfToken = String(req.query.hfToken || "").trim(); 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 0: HuggingFace Storage Bucket let entries = null; let fetchError = null; console.log(`[Remote] Attempting to list files from: ${baseUrl}`); const hfBucket = isHfBucketUrl(baseUrl); if (hfBucket) { try { entries = await listHfBucket(hfBucket.org, hfBucket.bucket, hfBucket.path, hfToken); if (entries.length > 0) { 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) { fetchError = "HF Bucket: " + err.message; } } try { console.log(`[Remote] Strategy 1: GET ${baseUrl}/files${listPath ? "?path=" + encodeURIComponent(listPath) : ""}`); const fetchUrl1 = listPath ? `${baseUrl}/files?path=${encodeURIComponent(listPath)}` : `${baseUrl}/files`; const response = await fetchWithTimeout(fetchUrl1, { 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}/${listPath ? listPath.slice(1) + "/" : ""}`); const fetchUrl2 = listPath ? `${baseUrl}/${remotePath}/` : `${baseUrl}/`; const rootResponse = await fetchWithTimeout(fetchUrl2, {}, 5000); 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" }); } }); // AWS SigV4 requires the canonical query string to be built from individually // percent-encoded, alphabetically-sorted key/value pairs — NOT the raw query // string dropped in wholesale. Getting this wrong (e.g. lumping "?list-type=2& // delimiter=/" into the canonical URI with an empty canonical query string) // produces a signature that some providers (Backblaze B2) reject outright with // SignatureDoesNotMatch, while others tolerate it. Always build both the actual // request query string and the canonical one from the same encoding so they // can never drift apart. function awsUriEncode(str) { return encodeURIComponent(str).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()); } function buildCanonicalQueryString(queryParams) { if (!queryParams) return ""; const entries = Object.entries(queryParams).filter(([, v]) => v !== undefined && v !== null); entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); return entries.map(([k, v]) => `${awsUriEncode(k)}=${awsUriEncode(String(v))}`).join("&"); } // Generic AWS SigV4 signed request against any S3-compatible host (HF buckets, // Qencode media storage, Backblaze B2, etc). Signs only host/x-amz-content-sha256/ // x-amz-date — the minimal header set AWS SigV4 requires — since some gateways // (e.g. Backblaze-backed ones) reject requests that sign more than they're sent. // `queryParams` is an optional object of query key/value pairs (not a raw string). function s3SignedRequest(method, host, pathStr, queryParams, region, accessKeyId, secretAccessKey, body, contentType) { return new Promise((resolve, reject) => { const service = "s3"; const now = new Date(); const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z"); const dateStr = amzDate.slice(0, 8); const bodyBuf = body || Buffer.alloc(0); const bodyHash = crypto.createHash("sha256").update(bodyBuf).digest("hex"); const canonicalQueryString = buildCanonicalQueryString(queryParams); const requestPath = canonicalQueryString ? `${pathStr}?${canonicalQueryString}` : pathStr; const signedHeaders = "host;x-amz-content-sha256;x-amz-date"; const canonicalHeaders = `host:${host}\nx-amz-content-sha256:${bodyHash}\nx-amz-date:${amzDate}\n`; const canonicalRequest = [method, pathStr, canonicalQueryString, canonicalHeaders, signedHeaders, bodyHash].join("\n"); const credentialScope = `${dateStr}/${region}/${service}/aws4_request`; const stringToSign = [ "AWS4-HMAC-SHA256", amzDate, credentialScope, crypto.createHash("sha256").update(canonicalRequest).digest("hex"), ].join("\n"); function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); } const dateKey = hmac(`AWS4${secretAccessKey}`, dateStr); const regionKey = hmac(dateKey, region); const serviceKey = hmac(regionKey, service); const signingKey = hmac(serviceKey, "aws4_request"); const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex"); const authorization = `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; const headers = { Host: host, "x-amz-content-sha256": bodyHash, "x-amz-date": amzDate, Authorization: authorization, }; if (body) { headers["Content-Length"] = Buffer.byteLength(bodyBuf); headers["Content-Type"] = contentType || "application/octet-stream"; } const req2 = https.request({ hostname: host, port: 443, path: requestPath, method, headers }, (res) => { if (method === "GET" && res.statusCode >= 200 && res.statusCode < 300 && contentType === "__STREAM__") { resolve({ status: res.statusCode, stream: res, headers: res.headers }); return; } let data = ""; res.on("data", (chunk) => (data += chunk)); res.on("end", () => { if (res.statusCode >= 200 && res.statusCode < 300) resolve({ status: res.statusCode, body: data, headers: res.headers }); else reject(new Error(`S3 request failed: ${res.statusCode} ${data.slice(0, 500)}`)); }); }); req2.on("error", reject); req2.end(bodyBuf); }); } // Helper function for HF bucket copy operations (GET → PUT → DELETE) async function hfBucketCopyViaGetPut(hf, oldKey, newKey, accessKeyId, secretAccessKey, hfToken) { // oldKey is like "bucketname/optional/path/filename.mp4" // The HF resolve URL is: /buckets/{org}/{repo}/resolve/{path_within_repo} // where path_within_repo is everything after "{bucket}/" const oldObjectPath = oldKey.startsWith(hf.bucket + "/") ? oldKey.slice(hf.bucket.length + 1) : oldKey; // Encode each path segment individually (don't encode the slashes) const encodedPath = oldObjectPath.split("/").map(s => encodeURIComponent(s)).join("/"); const resolveUrl = `https://huggingface.co/buckets/${encodeURIComponent(hf.org)}/${encodeURIComponent(hf.bucket)}/resolve/${encodedPath}?download=true`; console.log("[HF copy] GET from:", resolveUrl); console.log("[HF copy] hfToken:", hfToken ? hfToken.slice(0, 8) + "..." : "MISSING"); if (!hfToken) { throw new Error("hfToken is required for HF bucket GET — add your HF token in the Remote tab"); } const getResp = await fetch(resolveUrl, { headers: { "Authorization": `Bearer ${hfToken}`, "User-Agent": "Mozilla/5.0", "Accept": "*/*", }, redirect: "follow", }); if (!getResp.ok) { const body = await getResp.text().catch(() => "(unreadable)"); throw new Error(`HF GET failed: ${getResp.status} ${getResp.statusText} — ${body}`); } const arrayBuffer = await getResp.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); const contentType = getResp.headers.get("content-type") || "application/octet-stream"; console.log("[HF copy] Downloaded bytes:", buffer.length, "| contentType:", contentType); const client = new S3Client({ endpoint: "https://s3.hf.co", region: "us-east-1", credentials: { accessKeyId, secretAccessKey }, forcePathStyle: true, }); await client.send(new PutObjectCommand({ Bucket: hf.org, Key: newKey, Body: buffer, ContentType: contentType, })); console.log("[HF copy] PUT to:", newKey, "— OK"); await client.send(new DeleteObjectCommand({ Bucket: hf.org, Key: oldKey, })); console.log("[HF copy] DELETE:", oldKey, "— OK"); } // PUT a file into an HF Storage Bucket via the S3 gateway. async function hfBucketUpload(hf, filename, buffer, accessKeyId, secretAccessKey) { const keyParts = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), filename].filter(Boolean); const pathStr = "/" + [hf.org, ...keyParts].map(encodeURIComponent).join("/"); await s3SignedRequest("PUT", "s3.hf.co", pathStr, null, "us-east-1", accessKeyId, secretAccessKey, buffer, "application/octet-stream"); } // Helpers for the generic S3-compatible storage integration (Qencode, Backblaze, // Wasabi, R2, etc). Callers pass the exact bucket endpoint URL they were given // (virtual-hosted style, e.g. https://.media-storage..qencode.com) — // we sign requests straight against that host with no bucket segment in the path. function s3KeyPath(prefix, name) { const parts = [...(prefix ? prefix.split("/") : []), name].filter(Boolean); return "/" + parts.map(encodeURIComponent).join("/"); } // ── Qencode CDN signed URLs (RS256 JWT, separate from the S3 access key/secret) ── const QENCODE_SIGNING_KEY_PATH = path.join(__dirname, ".secrets", "qencode_signing_key.pem"); const QENCODE_SIGNING_KEY_ID = "90be430d-8dc6-4f12-832c-08443bb0c3af"; function base64url(input) { return Buffer.from(input).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function signQencodeToken(kid, privateKeyPem, uri, expiresInSeconds) { const header = { alg: "RS256", typ: "JWT", kid }; const payload = { uri: uri || "", exp: Math.floor(Date.now() / 1000) + (expiresInSeconds || 3600) }; const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`; const signature = crypto.sign("RSA-SHA256", Buffer.from(signingInput), privateKeyPem); return `${signingInput}.${signature.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`; } app.post("/api/s3/signed-url", async (req, res) => { const endpointUrl = String(req.body?.endpointUrl || "").trim().replace(/\/+$/, ""); const objectKey = String(req.body?.objectKey || "").trim(); const expiresInSeconds = Number(req.body?.expiresInSeconds) || 3600; if (!endpointUrl || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" }); let privateKeyPem; try { privateKeyPem = fs.readFileSync(QENCODE_SIGNING_KEY_PATH, "utf8"); } catch { return res.status(400).json({ ok: false, error: "No Qencode signing key configured on the server" }); } try { const uriPath = "/" + objectKey.split("/").map(encodeURIComponent).join("/"); const token = signQencodeToken(QENCODE_SIGNING_KEY_ID, privateKeyPem, uriPath, expiresInSeconds); const url = `${endpointUrl}${uriPath}?auth=${token}`; return res.json({ ok: true, url, expiresInSeconds }); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Failed to sign URL" }); } }); 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`; } // ── Helper: build a remote file ID (downloaded:name) for proxying to this app's API ── function remoteFileId(name) { return encodeURIComponent(`downloaded:${name}`); } // ── Helper: create S3 client for HF bucket operations ── function hfS3Client(accessKeyId, secretAccessKey) { return new S3Client({ endpoint: "https://s3.hf.co", region: "us-east-1", credentials: { accessKeyId, secretAccessKey }, forcePathStyle: true, }); } // ── Helper: build HF bucket S3 key from URL and filename ── function hfS3Key(hf, name) { return [hf.bucket, ...(hf.path ? hf.path.split("/") : []), name].filter(Boolean).join("/"); } // Remote rename — try multiple strategies: // 1. S3 CopyObject + DeleteObject (HF bucket) // 2. {baseUrl}/api/files/{id}/rename (same app as remote) // 3. {baseUrl}/rename (custom Python server) // 4. {baseUrl}/ (generic fallback) app.post("/api/remote/rename", async (req, res) => { const { serverUrl, oldName, newName, hfAccessKeyId, hfSecretAccessKey, hfToken } = req.body || {}; if (!serverUrl || !oldName || !newName) { return res.status(400).json({ error: "serverUrl, oldName and newName are required" }); } console.log("[rename] body keys received:", Object.keys(req.body || {})); console.log("[rename] hfToken present:", !!hfToken, "| value:", hfToken ? hfToken.slice(0, 6) + "..." : "NONE"); // Handle Hugging Face Buckets via S3 Gateway const hf = isHfBucketUrl(serverUrl); if (hf) { if (!hfAccessKeyId || !hfSecretAccessKey) { return res.status(400).json({ error: "HF S3 credentials required. Add them in the Remote tab." }); } try { const oldKey = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), oldName].filter(Boolean).join("/"); const newKey = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), newName].filter(Boolean).join("/"); await hfBucketCopyViaGetPut(hf, oldKey, newKey, hfAccessKeyId, hfSecretAccessKey, hfToken); return res.json({ ok: true }); } catch (err) { console.error("HF rename failed:", err, err?.$metadata, err?.Code); return res.status(500).json({ error: err.message || "HF bucket rename failed" }); } } const baseUrl = String(serverUrl).trim().replace(/\/+$/, ""); const fileId = remoteFileId(oldName); const attempts = [ { url: `${baseUrl}/api/files/${fileId}/rename`, method: "POST", body: JSON.stringify({ newName }), headers: { "Content-Type": "application/json" } }, { url: `${baseUrl}/rename`, method: "POST", body: JSON.stringify({ old_name: oldName, new_name: newName, oldName, newName }), headers: { "Content-Type": "application/json" } }, { url: `${baseUrl}/`, method: "POST", body: JSON.stringify({ old_name: oldName, new_name: newName, oldName, newName }), headers: { "Content-Type": "application/json" } }, ]; let lastErr = null; for (const attempt of attempts) { try { const response = await fetchWithTimeout(attempt.url, { method: attempt.method, headers: attempt.headers, body: attempt.body }, 15000); if (response.ok) { const data = await response.json().catch(() => ({})); return res.json({ ok: true, ...data }); } if (response.status === 404) { lastErr = `Remote returned 404`; continue; } const text = await response.text(); return res.status(response.status).json({ error: text || `Remote returned ${response.status}` }); } catch (err) { lastErr = err.message || "Connection failed"; continue; } } return res.status(502).json({ error: `Remote rename failed: ${lastErr}` }); }); // Remote delete — try multiple strategies: // 1. S3 DeleteObject (HF bucket) // 2. DELETE {baseUrl}/api/files/{id} (same app as remote) // 3. POST {baseUrl}/delete (custom Python server) // 4. DELETE {baseUrl}/?name=... (generic fallback) app.post("/api/remote/delete", async (req, res) => { const { serverUrl, name, hfAccessKeyId, hfSecretAccessKey } = req.body || {}; if (!serverUrl || !name) { return res.status(400).json({ error: "serverUrl and name are required" }); } // Strategy 1: Hugging Face Bucket via S3 DeleteObject const hf = isHfBucketUrl(serverUrl); if (hf) { if (!hfAccessKeyId || !hfSecretAccessKey) { return res.status(400).json({ error: "HF S3 credentials required. Add them in the Remote tab." }); } try { const key = hfS3Key(hf, name); const client = hfS3Client(hfAccessKeyId, hfSecretAccessKey); await client.send(new DeleteObjectCommand({ Bucket: hf.org, Key: key })); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ error: err.message || "HF bucket delete failed" }); } } const baseUrl = String(serverUrl).trim().replace(/\/+$/, ""); const fileId = remoteFileId(name); const attempts = [ { url: `${baseUrl}/api/files/${fileId}`, method: "DELETE", body: null, headers: {} }, { url: `${baseUrl}/delete`, method: "POST", body: JSON.stringify({ name }), headers: { "Content-Type": "application/json" } }, { url: `${baseUrl}/?name=${encodeURIComponent(name)}`, method: "DELETE", body: null, headers: {} }, ]; let lastErr = null; for (const attempt of attempts) { try { const response = await fetchWithTimeout(attempt.url, { method: attempt.method, headers: attempt.headers, body: attempt.body }, 15000); if (response.ok) { const data = await response.json().catch(() => ({})); return res.json({ ok: true, ...data }); } if (response.status === 404) { lastErr = `Remote returned 404`; continue; } const text = await response.text(); return res.status(response.status).json({ error: text || `Remote returned ${response.status}` }); } catch (err) { lastErr = err.message || "Connection failed"; continue; } } return res.status(502).json({ error: `Remote delete failed: ${lastErr}` }); }); // Remote move: POST /api/remote/move // Tries multiple strategies: // 1. S3 CopyObject + DeleteObject (HF bucket) // 2. POST {baseUrl}/api/files/{id}/move (same app as remote) // 3. POST {baseUrl}/move (custom Python server) // 4. POST {baseUrl}/ (generic fallback) app.post("/api/remote/move", async (req, res) => { const { serverUrl, name, targetFolder, hfAccessKeyId, hfSecretAccessKey, hfToken } = req.body || {}; if (!serverUrl || !name || targetFolder === undefined) { return res.status(400).json({ error: "serverUrl, name and targetFolder are required" }); } console.log("[move] body keys received:", Object.keys(req.body || {})); console.log("[move] hfToken present:", !!hfToken, "| value:", hfToken ? hfToken.slice(0, 6) + "..." : "NONE"); // Handle Hugging Face Buckets via S3 Gateway const hf = isHfBucketUrl(serverUrl); if (hf) { if (!hfAccessKeyId || !hfSecretAccessKey) { return res.status(400).json({ error: "HF S3 credentials required. Add them in the Remote tab." }); } try { const oldKey = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), name].filter(Boolean).join("/"); const targetParts = targetFolder === "/" ? [] : targetFolder.replace(/^\//, "").split("/"); const newKey = [hf.bucket, ...targetParts, name].filter(Boolean).join("/"); if (oldKey !== newKey) { await hfBucketCopyViaGetPut(hf, oldKey, newKey, hfAccessKeyId, hfSecretAccessKey, hfToken); } return res.json({ ok: true }); } catch (err) { console.error("HF move failed:", err, err?.$metadata, err?.Code); return res.status(500).json({ error: err.message || "HF bucket move failed" }); } } const baseUrl = String(serverUrl).trim().replace(/\/+$/, ""); const fileId = remoteFileId(name); const attempts = [ { url: `${baseUrl}/api/files/${fileId}/move`, method: "POST", body: JSON.stringify({ targetFolder }), headers: { "Content-Type": "application/json" } }, { url: `${baseUrl}/move`, method: "POST", body: JSON.stringify({ name, targetFolder, target_folder: targetFolder }), headers: { "Content-Type": "application/json" } }, { url: `${baseUrl}/`, method: "POST", body: JSON.stringify({ name, targetFolder }), headers: { "Content-Type": "application/json" } }, ]; let lastErr = null; for (const attempt of attempts) { try { const response = await fetchWithTimeout(attempt.url, { method: attempt.method, headers: attempt.headers, body: attempt.body }, 15000); if (response.ok) { const data = await response.json().catch(() => ({})); return res.json({ ok: true, ...data }); } if (response.status === 404) { lastErr = `Remote returned 404`; continue; } const text = await response.text(); return res.status(response.status).json({ error: text || `Remote returned ${response.status}` }); } catch (err) { lastErr = err.message || "Connection failed"; continue; } } return res.status(502).json({ error: `Remote move failed: ${lastErr}` }); }); // 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" }); const hf = isHfBucketUrl(serverUrl); if (hf) { const accessKeyId = String(req.body?.hfAccessKeyId || "").trim(); const secretAccessKey = String(req.body?.hfSecretAccessKey || "").trim(); if (!accessKeyId || !secretAccessKey) { return res.status(400).json({ error: "This is a Hugging Face bucket. Enter its S3 access key ID and secret access key (generated from an HF access token with Write permission) to upload." }); } try { await hfBucketUpload(hf, req.file.originalname, req.file.buffer, accessKeyId, secretAccessKey); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ error: err.message || "HF bucket upload failed" }); } } 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/files/:id/remote-upload", 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 serverUrl = String(req.body?.serverUrl || "").trim().replace(/\/+$/, ""); if (!serverUrl) return res.status(400).json({ error: "serverUrl is required" }); const hf = isHfBucketUrl(serverUrl); if (hf) { const accessKeyId = String(req.body?.hfAccessKeyId || "").trim(); const secretAccessKey = String(req.body?.hfSecretAccessKey || "").trim(); if (!accessKeyId || !secretAccessKey) { return res.status(400).json({ error: "This is a Hugging Face bucket. Enter its S3 access key ID and secret access key (generated from an HF access token with Write permission) to upload." }); } try { const buffer = await fsp.readFile(info.filePath); await hfBucketUpload(hf, info.name.split("/").pop(), buffer, accessKeyId, secretAccessKey); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ error: err.message || "HF bucket upload failed" }); } } try { const buffer = await fsp.readFile(info.filePath); const formData = new FormData(); const blob = new Blob([buffer], { type: "application/octet-stream" }); formData.append("file", blob, info.name.split("/").pop()); const response = await fetchWithTimeout(`${serverUrl}/`, { method: "POST", body: formData, }, 120000); // 2min timeout for larger media files 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" }); } }); // Folder sync: use hf sync to upload a local folder to HuggingFace bucket app.post("/api/remote/sync-folder", async (req, res) => { const { localPath, bucketUrl, hfToken } = req.body || {}; if (!localPath || !bucketUrl) { return res.status(400).json({ error: "localPath and bucketUrl are required" }); } // Verify local path exists let stats; try { stats = await fsp.stat(localPath); if (!stats.isDirectory()) { return res.status(400).json({ error: "localPath must be a directory" }); } } catch (err) { return res.status(400).json({ error: `Local path not found or not readable: ${err.message}` }); } // Must be HF bucket const hfBucket = isHfBucketUrl(bucketUrl); if (!hfBucket) { return res.status(400).json({ error: "Only HuggingFace buckets are supported for folder sync" }); } const syncJobId = randomId("sync"); const syncJob = { id: syncJobId, status: "running", localPath, bucketUrl, createdAt: Date.now(), log: [], error: null, bytesUploaded: 0, totalBytes: 0, }; // Store job reference if (!global.syncJobs) global.syncJobs = new Map(); global.syncJobs.set(syncJobId, syncJob); res.json({ ok: true, jobId: syncJobId }); // Run sync in background (async () => { try { const hfSyncUrl = `hf://buckets/${encodeURIComponent(hfBucket.org)}/${encodeURIComponent(hfBucket.bucket)}`; const args = [ "sync", localPath, hfSyncUrl, "--private" // private upload ]; // Add token if provided (via env var to avoid exposing in process list) const env = { ...process.env }; if (hfToken) { env.HF_TOKEN = hfToken; } syncJob.log.push(`Running: hf ${args.join(" ")}`); return new Promise((resolve) => { const proc = spawn("hf", args, { stdio: ["pipe", "pipe", "pipe"], env, }); let stdout = ""; let stderr = ""; proc.stdout.on("data", (data) => { const text = String(data); stdout += text; syncJob.log.push(text); }); proc.stderr.on("data", (data) => { const text = String(data); stderr += text; syncJob.log.push(`[ERROR] ${text}`); }); proc.on("close", (code) => { if (code === 0) { syncJob.status = "done"; syncJob.log.push("Sync completed successfully"); } else { syncJob.status = "failed"; syncJob.error = `hf sync exited with code ${code}: ${stderr || stdout}`; syncJob.log.push(`Failed with code ${code}`); } resolve(); }); proc.on("error", (err) => { syncJob.status = "failed"; syncJob.error = err.message || "Unknown error"; syncJob.log.push(`[ERROR] ${err.message}`); resolve(); }); // 10 minute timeout for sync setTimeout(() => { if (syncJob.status === "running") { proc.kill(); syncJob.status = "failed"; syncJob.error = "Sync timed out after 10 minutes"; syncJob.log.push("Timeout: killed sync process"); } }, 10 * 60 * 1000); }); } catch (err) { syncJob.status = "failed"; syncJob.error = err.message || "Unknown error"; syncJob.log.push(`[ERROR] ${err.message}`); } })(); }); // Get sync job status app.get("/api/remote/sync-status/:id", async (req, res) => { const jobId = String(req.params.id || "").trim(); if (!jobId) return res.status(400).json({ error: "Job ID required" }); if (!global.syncJobs) global.syncJobs = new Map(); const job = global.syncJobs.get(jobId); if (!job) { return res.status(404).json({ error: "Job not found" }); } return res.json({ ok: true, job }); }); app.post("/api/remote/download", async (req, res) => { const { url, filename, targetFolder, serverUrl, remoteName, hfPath, hfOrg, hfBucket, hfToken } = req.body || {}; // Support both direct URL and serverUrl+remoteName for the custom Python server let downloadUrl = url || null; if (!downloadUrl && hfPath && hfOrg && hfBucket) { downloadUrl = `https://huggingface.co/buckets/${encodeURIComponent(String(hfOrg))}/${encodeURIComponent(String(hfBucket))}/resolve/${hfPath}?download=true`; } else if (!downloadUrl && serverUrl && remoteName) { const hf = isHfBucketUrl(String(serverUrl)); if (hf) { const prefix = hf.path ? hf.path + "/" : ""; downloadUrl = `https://huggingface.co/buckets/${encodeURIComponent(hf.org)}/${encodeURIComponent(hf.bucket)}/resolve/${prefix}${remoteName}?download=true`; } else { downloadUrl = `${String(serverUrl).trim().replace(/\/+$/, "")}/${encodeURIComponent(remoteName)}`; } } 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(downloadUrl || 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 headers = { "User-Agent": "Mozilla/5.0", "Accept": "*/*", }; if (hfToken) headers.Authorization = `Bearer ${hfToken}`; const response = await fetch(downloadUrl, { signal: dlJob.abortController.signal, redirect: "follow", headers, }); 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-folder", async (req, res) => { const { serverUrl, folderName, targetFolder, hfToken } = req.body || {}; const hf = isHfBucketUrl(String(serverUrl || "")); if (!hf) return res.status(400).json({ error: "Only HF bucket folder download is supported right now" }); if (!folderName) return res.status(400).json({ error: "folderName is required" }); try { const prefix = hf.path ? `${hf.path}/${folderName}` : String(folderName); const files = await listAllHfBucketFiles(hf.org, hf.bucket, prefix, String(hfToken || "").trim()); if (!files.length) { return res.status(404).json({ error: "No files found in remote folder" }); } const safeFolder = sanitizeFolderPath(String(targetFolder || "")); const targetDir = safeFolder && safeFolder !== "/" ? path.join(DOWNLOADS_DIR, safeFolder) : DOWNLOADS_DIR; await fsp.mkdir(targetDir, { recursive: true }); const jobIds = []; for (const file of files) { const dlJobId = randomId("rdl"); const dlJob = { id: dlJobId, createdAt: Date.now(), status: "running", url: `https://huggingface.co/buckets/${encodeURIComponent(file.hfOrg)}/${encodeURIComponent(file.hfBucket)}/resolve/${file.hfPath}?download=true`, filename: file.hfPath, bytesDownloaded: 0, totalBytes: 0, error: null, targetFolder: safeFolder || "/", abortController: new AbortController(), }; remoteDownloadJobs.set(dlJobId, dlJob); jobIds.push(dlJobId); (async () => { try { const downloadUrl = `https://huggingface.co/buckets/${encodeURIComponent(file.hfOrg)}/${encodeURIComponent(file.hfBucket)}/resolve/${file.hfPath}?download=true`; const headers = { "User-Agent": "Mozilla/5.0", "Accept": "*/*", }; if (hfToken) headers.Authorization = `Bearer ${hfToken}`; const response = await fetch(downloadUrl, { signal: dlJob.abortController.signal, redirect: "follow", headers, }); 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 subPath = file.hfPath.startsWith(prefix + "/") ? file.hfPath.slice(prefix.length + 1) : file.name; const destFull = path.join(targetDir, folderName, subPath); await fsp.mkdir(path.dirname(destFull), { recursive: true }); dlJob.filename = path.join(folderName, subPath); const fileStream = fs.createWriteStream(destFull); 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"; } } })(); } return res.json({ ok: true, jobIds, count: files.length }); } catch (err) { return res.status(500).json({ error: err.message || "Folder download failed" }); } }); 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 }); }); // ── Backblaze B2 (S3-compatible) ─────────────────────────────────────────────── function b2SignS3(method, pathStr, endpointUrl, keyId, appKey, body = null) { return new Promise((resolve, reject) => { const parsed = new URL(endpointUrl); const host = parsed.hostname; const dateStr = new Date().toISOString().replace(/[:\-]/g, "").substring(0, 8); const amzDate = dateStr + "T000000Z"; const service = "s3"; const region = "us-west-002"; const signedHeaders = "host;x-amz-content-sha256;x-amz-date"; const bodyHash = crypto.createHash("sha256").update(body || "").digest("hex"); const canonicalRequest = [ method, pathStr, "", `host:${host}`, `x-amz-content-sha256:${bodyHash}`, `x-amz-date:${amzDate}`, "", signedHeaders, bodyHash, ].join("\n"); const credentialScope = `${dateStr}/${region}/${service}/aws4_request`; const stringToSign = [ "AWS4-HMAC-SHA256", amzDate, credentialScope, crypto.createHash("sha256").update(canonicalRequest).digest("hex"), ].join("\n"); function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); } const dateKey = hmac(`AWS4${appKey}`, dateStr); const regionKey = hmac(dateKey, region); const serviceKey = hmac(regionKey, service); const signingKey = hmac(serviceKey, "aws4_request"); const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex"); const authorization = [ `AWS4-HMAC-SHA256 Credential=${keyId}/${credentialScope}`, `SignedHeaders=${signedHeaders}`, `Signature=${signature}`, ].join(", "); const options = { hostname: host, port: 443, path: pathStr, method, headers: { Host: host, "x-amz-content-sha256": bodyHash, "x-amz-date": amzDate, Authorization: authorization, ...(body ? { "Content-Length": Buffer.byteLength(body), "Content-Type": "application/octet-stream" } : {}), }, }; const req = https.request(options, (res) => { let data = ""; res.on("data", (chunk) => (data += chunk)); res.on("end", () => { if (res.statusCode >= 200 && res.statusCode < 300) { resolve({ status: res.statusCode, body: data, headers: res.headers }); } else { reject(new Error(`S3 request failed: ${res.statusCode} ${data.slice(0, 500)}`)); } }); }); req.on("error", reject); req.end(body || undefined); }); } function unescapeXml(str) { return str .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'"); } function parseB2XmlList(xml) { const entries = []; const nameMatch = xml.match(/([\s\S]*?)<\/Contents>/g) || []; for (const block of nameMatch) { const key = unescapeXml(block.match(/([^<]*)<\/Key>/)?.[1] || ""); const size = parseInt(block.match(/(\d+)<\/Size>/)?.[1] || "0", 10); const lastMod = block.match(/([^<]*)<\/LastModified>/)?.[1] || ""; entries.push({ key, name: key.split("/").pop(), isDir: false, size, sizeStr: `${(size / 1024).toFixed(1)} KB`, lastModified: lastMod, type: "file" }); } // Parse CommonPrefixes for directories const prefixMatch = xml.match(/[\s\S]*?([^<]*)<\/Prefix>[\s\S]*?<\/CommonPrefixes>/g) || []; for (const block of prefixMatch) { const prefix = unescapeXml(block.match(/([^<]*)<\/Prefix>/)?.[1] || ""); const name = prefix.replace(/\/$/, "").split("/").pop(); if (name && !entries.some((e) => e.key === prefix)) { entries.push({ key: prefix, name, isDir: true, size: 0, type: "folder" }); } } return entries; } app.get("/api/backblaze/list", async (req, res) => { const { bucketId, endpointUrl, keyId, appKey, prefix } = req.query; if (!bucketId || !endpointUrl || !keyId || !appKey) { return res.status(400).json({ ok: false, entries: [], error: "Missing required params (bucketId, endpointUrl, keyId, appKey)" }); } try { let pathStr = `/${bucketId}`; if (prefix) pathStr += `?prefix=${encodeURIComponent(prefix)}&delimiter=/`; const result = await b2SignS3("GET", pathStr, endpointUrl, keyId, appKey); const entries = parseB2XmlList(result.body); return res.json({ ok: true, entries }); } catch (err) { return res.status(500).json({ ok: false, entries: [], error: err.message || "Failed to list Backblaze bucket" }); } }); app.post("/api/backblaze/download", async (req, res) => { const { bucketId, endpointUrl, keyId, appKey, objectKey, targetFolder } = req.body; if (!bucketId || !endpointUrl || !keyId || !appKey || !objectKey) { return res.status(400).json({ ok: false, error: "Missing required params" }); } try { const downloadDir = targetFolder ? path.join(DOWNLOADS_DIR, targetFolder.replace(/^\//, "")) : DOWNLOADS_DIR; await fsp.mkdir(downloadDir, { recursive: true }); const filename = objectKey.split("/").pop() || objectKey; const filePath = path.join(downloadDir, filename); const destFile = fs.createWriteStream(filePath); const parsed = new URL(endpointUrl); const host = parsed.hostname; const dateStr = new Date().toISOString().replace(/[:\-]/g, "").substring(0, 8); const amzDate = dateStr + "T000000Z"; const bodyHash = crypto.createHash("sha256").update("").digest("hex"); const signedHeaders = "host;x-amz-content-sha256;x-amz-date"; const pathStr = `/${bucketId}/${encodeURIComponent(objectKey)}`; const canonicalRequest = ["GET", pathStr, "", `host:${host}`, `x-amz-content-sha256:${bodyHash}`, `x-amz-date:${amzDate}`, "", signedHeaders, bodyHash].join("\n"); const region = "us-west-002"; const service = "s3"; const credentialScope = `${dateStr}/${region}/${service}/aws4_request`; const stringToSign = ["AWS4-HMAC-SHA256", amzDate, credentialScope, crypto.createHash("sha256").update(canonicalRequest).digest("hex")].join("\n"); function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); } const signingKey = hmac(hmac(hmac(hmac(`AWS4${appKey}`, dateStr), region), service), "aws4_request"); const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex"); const authorization = `AWS4-HMAC-SHA256 Credential=${keyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; await new Promise((resolve, reject) => { const opts = { hostname: host, port: 443, path: pathStr, method: "GET", headers: { Host: host, "x-amz-content-sha256": bodyHash, "x-amz-date": amzDate, Authorization: authorization }, }; const req = https.request(opts, (res) => { if (res.statusCode >= 200 && res.statusCode < 300) { res.pipe(destFile); destFile.on("finish", resolve); } else { let data = ""; res.on("data", (chunk) => (data += chunk)); res.on("end", () => reject(new Error(`Download failed: ${res.statusCode} ${data.slice(0, 500)}`))); } }); req.on("error", reject); req.end(); }); return res.json({ ok: true, jobId: `b2_${Date.now()}` }); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Backblaze download failed" }); } }); // ── Generic S3-compatible storage (Qencode media storage, Backblaze B2, or any // other S3-style bucket). Callers provide the PATH-STYLE API host directly // (e.g. "us-west.s3.qencode.com" or "s3.us-east-005.backblazeb2.com") — we never // hardcode a provider-specific host, since that breaks every other provider. // For Qencode specifically, this path-style host is distinct from the // virtual-hosted CDN/playback host (https://.media-storage.. // qencode.com) used only for direct file reads and signed-URL playback; signing // against the CDN host looks like an auth/entitlement failure but is actually // the wrong endpoint entirely. ─────────────────────────────────────────────── // Generate an S3-compatible SigV4 presigned GET URL (credentials in query params, // no custom headers required — works from any browser or HTTP client). function s3PresignGetUrl(host, pathStr, region, accessKeyId, secretAccessKey, expiresInSeconds) { const service = "s3"; const now = new Date(); const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z"); const dateStr = amzDate.slice(0, 8); const credentialScope = `${dateStr}/${region}/${service}/aws4_request`; // Sorted query params (must NOT include X-Amz-Signature yet) const queryParams = { "X-Amz-Algorithm": "AWS4-HMAC-SHA256", "X-Amz-Credential": `${accessKeyId}/${credentialScope}`, "X-Amz-Date": amzDate, "X-Amz-Expires": String(expiresInSeconds || 3600), "X-Amz-SignedHeaders": "host", }; const canonicalQueryString = Object.keys(queryParams).sort() .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(queryParams[k])}`) .join("&"); const canonicalRequest = [ "GET", pathStr, canonicalQueryString, `host:${host}\n`, "host", "UNSIGNED-PAYLOAD", ].join("\n"); const stringToSign = [ "AWS4-HMAC-SHA256", amzDate, credentialScope, crypto.createHash("sha256").update(canonicalRequest).digest("hex"), ].join("\n"); function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); } const dateKey = hmac(`AWS4${secretAccessKey}`, dateStr); const regionKey = hmac(dateKey, region); const serviceKey = hmac(regionKey, service); const signingKey = hmac(serviceKey, "aws4_request"); const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex"); return `https://${host}${pathStr}?${canonicalQueryString}&X-Amz-Signature=${signature}`; } function parseS3ReqParams(q) { const bucketName = String(q.bucketName || "").trim(); const accessKeyId = String(q.accessKeyId || "").trim(); const secretAccessKey = String(q.secretAccessKey || "").trim(); const region = String(q.region || "us-west").trim(); let host = String(q.host || "").trim().replace(/^https?:\/\//, "").replace(/\/+$/, ""); if (!bucketName || !accessKeyId || !secretAccessKey || !region || !host) return null; return { host, bucketName, accessKeyId, secretAccessKey, region }; } app.post("/api/s3/presign", async (req, res) => { const p = parseS3ReqParams(req.body || {}); const objectKey = String(req.body?.objectKey || "").trim(); const expiresInSeconds = Number(req.body?.expiresInSeconds) || 3600; if (!p || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" }); try { const pathStr = `/${encodeURIComponent(p.bucketName)}/` + objectKey.split("/").map(encodeURIComponent).join("/"); const url = s3PresignGetUrl(p.host, pathStr, p.region, p.accessKeyId, p.secretAccessKey, expiresInSeconds); return res.json({ ok: true, url, expiresInSeconds }); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Failed to presign URL" }); } }); app.get("/api/s3/list", async (req, res) => { const p = parseS3ReqParams(req.query); if (!p) return res.status(400).json({ ok: false, entries: [], error: "Missing required params (bucketName, accessKeyId, secretAccessKey, region)" }); const prefix = String(req.query.prefix || ""); try { const pathStr = `/${encodeURIComponent(p.bucketName)}`; const queryParams = { "list-type": "2", delimiter: "/" }; if (prefix) queryParams.prefix = prefix; const result = await s3SignedRequest("GET", p.host, pathStr, queryParams, p.region, p.accessKeyId, p.secretAccessKey); const entries = parseB2XmlList(result.body); return res.json({ ok: true, entries }); } catch (err) { return res.status(500).json({ ok: false, entries: [], error: err.message || "Failed to list bucket" }); } }); app.post("/api/s3/upload", upload.single("file"), async (req, res) => { const p = parseS3ReqParams(req.body || {}); if (!p) return res.status(400).json({ ok: false, error: "Missing required params (bucketName, accessKeyId, secretAccessKey, region)" }); if (!req.file) return res.status(400).json({ ok: false, error: "No file uploaded" }); try { const pathStr = `/${encodeURIComponent(p.bucketName)}${s3KeyPath(req.body?.prefix, req.file.originalname)}`; await s3SignedRequest("PUT", p.host, pathStr, null, p.region, p.accessKeyId, p.secretAccessKey, req.file.buffer, req.file.mimetype || "application/octet-stream"); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Upload failed" }); } }); app.post("/api/s3/download", async (req, res) => { const objectKey = String(req.body?.objectKey || "").trim(); const cfProxyUrl = String(req.body?.cfProxyUrl || "").trim(); // When a Cloudflare proxy URL is set, we don't need S3 credentials — just do a // plain HTTPS fetch through the proxy (free, bypasses B2 bandwidth cap). // Otherwise fall back to authenticated S3 signed request. const p = cfProxyUrl ? { bucketName: String(req.body?.bucketName || "").trim() } : parseS3ReqParams(req.body || {}); if (!p || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" }); // Parse S3 creds separately — needed even on cfProxyUrl path for fileId HEAD lookup const s3ParamsCf = cfProxyUrl ? parseS3ReqParams(req.body || {}) : null; let downloadDir, rawFilename, destPath; try { const targetFolder = req.body?.targetFolder; downloadDir = targetFolder ? path.join(DOWNLOADS_DIR, String(targetFolder).replace(/^\//, "")) : DOWNLOADS_DIR; await fsp.mkdir(downloadDir, { recursive: true }); rawFilename = objectKey.split("/").pop() || objectKey; ({ fullPath: destPath } = getUniqueFilePath(downloadDir, rawFilename)); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Setup failed" }); } const filename = rawFilename; const displayUrl = cfProxyUrl ? `${cfProxyUrl.replace(/\/$/, "")}/${p.bucketName}/${objectKey}` : `s3://${req.body?.host || ""}/${p.bucketName}/${objectKey}`; const dlJobId = randomId("dl"); const dlJob = { id: dlJobId, createdAt: Date.now(), status: "running", url: displayUrl, filename, bytesDownloaded: 0, totalBytes: 0, error: null, abortController: new AbortController(), }; downloadJobs.set(dlJobId, dlJob); res.json({ ok: true, jobId: dlJobId }); (async () => { try { if (cfProxyUrl) { // ── Cloudflare proxy path ───────────────────────────────────────────── // Prefer native B2 download-by-name via the worker (?b2File= mode). // The worker calls b2_authorize_account itself and uses the B2 native // download URL — no S3 signing, no path-encoding issues for any filename. // Fall back to path-based AWS4 signing only when creds are unavailable. let fetchUrl, fetchHeaders; if (s3ParamsCf) { const b2File = Buffer.from(objectKey).toString("base64"); const b2Bucket = Buffer.from(s3ParamsCf.bucketName).toString("base64"); const kid = Buffer.from(s3ParamsCf.accessKeyId).toString("base64"); const key = Buffer.from(s3ParamsCf.secretAccessKey).toString("base64"); fetchUrl = `${cfProxyUrl.replace(/\/$/, "")}?b2File=${encodeURIComponent(b2File)}&b2Bucket=${encodeURIComponent(b2Bucket)}&kid=${encodeURIComponent(kid)}&key=${encodeURIComponent(key)}`; fetchHeaders = {}; } else { // No creds in request — fall back to path-based AWS4 signing const encodedKey = objectKey.split("/").map(encodeURIComponent).join("/"); fetchUrl = `${cfProxyUrl.replace(/\/$/, "")}/${encodeURIComponent(p.bucketName)}/${encodedKey}`; fetchHeaders = { "X-B2-Key-Id": Buffer.from(req.body?.accessKeyId || "").toString("base64"), "X-B2-App-Key": Buffer.from(req.body?.secretAccessKey || "").toString("base64"), "X-B2-Region": req.body?.region || "us-east-005", "X-B2-Host": req.body?.host || "s3.us-east-005.backblazeb2.com", }; } const fetchRes = await fetch(fetchUrl, { signal: dlJob.abortController.signal, headers: fetchHeaders, }); if (!fetchRes.ok) { const errText = await fetchRes.text().catch(() => ""); throw new Error(`CF proxy request failed: ${fetchRes.status} ${errText.slice(0, 300)}`); } const cl = fetchRes.headers.get("content-length"); if (cl) dlJob.totalBytes = Number(cl); const fileStream = fs.createWriteStream(destPath); const { Readable } = await import("stream"); const nodeStream = Readable.fromWeb(fetchRes.body); nodeStream.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; }); await new Promise((resolve, reject) => { nodeStream.on("error", reject); fileStream.on("error", reject); fileStream.on("finish", resolve); nodeStream.pipe(fileStream); }); } else { // ── Direct S3 signed request path ───────────────────────────────────── const pathStr = `/${encodeURIComponent(p.bucketName)}/` + objectKey.split("/").map(encodeURIComponent).join("/"); const result = await s3SignedRequest("GET", p.host, pathStr, null, p.region, p.accessKeyId, p.secretAccessKey, null, "__STREAM__"); const cl = result.headers?.["content-length"]; if (cl) dlJob.totalBytes = Number(cl); const fileStream = fs.createWriteStream(destPath); result.stream.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; }); await new Promise((resolve, reject) => { result.stream.on("error", reject); fileStream.on("error", reject); fileStream.on("finish", resolve); result.stream.pipe(fileStream); }); } dlJob.status = "done"; } catch (err) { if (err.name === "AbortError") dlJob.status = "stopped"; else { dlJob.status = "failed"; dlJob.error = err.message || "Download failed"; } try { fs.unlinkSync(destPath); } catch {} } })(); }); app.post("/api/s3/delete", async (req, res) => { const p = parseS3ReqParams(req.body || {}); const objectKey = String(req.body?.objectKey || "").trim(); if (!p || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" }); try { const pathStr = `/${encodeURIComponent(p.bucketName)}/` + objectKey.split("/").map(encodeURIComponent).join("/"); await s3SignedRequest("DELETE", p.host, pathStr, null, p.region, p.accessKeyId, p.secretAccessKey); return res.json({ ok: true }); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Delete failed" }); } }); // ── Stream-compute SHA-256 of a file (no full load into memory) ──────────────── function hashFileStream(filePath) { return new Promise((resolve, reject) => { const hash = crypto.createHash("sha256"); fs.createReadStream(filePath) .on("data", (chunk) => hash.update(chunk)) .on("end", () => resolve(hash.digest("hex"))) .on("error", reject); }); } // ── Streaming S3 PUT with real SHA-256 body hash (no full-file buffering) ────── function s3StreamUpload(host, pathStr, region, accessKeyId, secretAccessKey, bodyHash, fileStream, fileSize, contentType) { return new Promise((resolve, reject) => { const now = new Date(); const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z"); const dateStr = amzDate.slice(0, 8); const signedHeaders = "host;x-amz-content-sha256;x-amz-date"; const canonicalHeaders = `host:${host}\nx-amz-content-sha256:${bodyHash}\nx-amz-date:${amzDate}\n`; const canonicalRequest = ["PUT", pathStr, "", canonicalHeaders, signedHeaders, bodyHash].join("\n"); const credentialScope = `${dateStr}/${region}/s3/aws4_request`; const stringToSign = [ "AWS4-HMAC-SHA256", amzDate, credentialScope, crypto.createHash("sha256").update(canonicalRequest).digest("hex"), ].join("\n"); function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); } const sig = crypto.createHmac("sha256", hmac(hmac(hmac(hmac(`AWS4${secretAccessKey}`, dateStr), region), "s3"), "aws4_request") ).update(stringToSign).digest("hex"); const authorization = `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${sig}`; const req2 = https.request({ hostname: host, port: 443, path: pathStr, method: "PUT", headers: { Host: host, "x-amz-content-sha256": bodyHash, "x-amz-date": amzDate, Authorization: authorization, "Content-Length": fileSize, "Content-Type": contentType || "application/octet-stream", }, }, (res2) => { let data = ""; res2.on("data", (c) => (data += c)); res2.on("end", () => { if (res2.statusCode >= 200 && res2.statusCode < 300) resolve({ status: res2.statusCode }); else reject(new Error(`S3 upload failed: ${res2.statusCode} ${data.slice(0, 500)}`)); }); }); req2.on("error", reject); fileStream.pipe(req2); }); } // ── S3 multipart upload via AWS SDK (for files > 100 MB) ────────────────────── // Uses @aws-sdk/client-s3 which handles SigV4 signing correctly for all // S3-compatible providers including Backblaze B2. const MULTIPART_THRESHOLD = 100 * 1024 * 1024; // 100 MB — use single PUT below this const MULTIPART_PART_SIZE = 50 * 1024 * 1024; // 50 MB per part (B2 minimum is 5 MB) async function s3MultipartUpload(host, pathStr, region, accessKeyId, secretAccessKey, filePath, fileSize) { // pathStr is "/{bucket}/{key}" — split into bucket and key for the SDK const withoutLeadingSlash = pathStr.replace(/^\//, ""); const slashIdx = withoutLeadingSlash.indexOf("/"); const bucket = decodeURIComponent(withoutLeadingSlash.slice(0, slashIdx)); const key = withoutLeadingSlash.slice(slashIdx + 1).split("/").map(decodeURIComponent).join("/"); const client = new S3Client({ endpoint: `https://${host}`, region, credentials: { accessKeyId, secretAccessKey }, forcePathStyle: true, // required for Backblaze B2 and most non-AWS S3-compatible hosts }); // Step 1 — CreateMultipartUpload const { UploadId } = await client.send(new CreateMultipartUploadCommand({ Bucket: bucket, Key: key, ContentType: "application/octet-stream", })); if (!UploadId) throw new Error("CreateMultipartUpload: no UploadId returned"); const numParts = Math.ceil(fileSize / MULTIPART_PART_SIZE); const parts = []; try { // Step 2 — UploadPart × N for (let i = 0; i < numParts; i++) { const partNumber = i + 1; const start = i * MULTIPART_PART_SIZE; const end = Math.min(start + MULTIPART_PART_SIZE, fileSize) - 1; const partSize = end - start + 1; const { ETag } = await client.send(new UploadPartCommand({ Bucket: bucket, Key: key, UploadId, PartNumber: partNumber, ContentLength: partSize, Body: fs.createReadStream(filePath, { start, end }), })); if (!ETag) throw new Error(`UploadPart ${partNumber}: no ETag in response`); parts.push({ PartNumber: partNumber, ETag }); } } catch (err) { // Best-effort abort so orphaned parts don't accumulate in the bucket client.send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId })).catch(() => {}); throw err; } // Step 3 — CompleteMultipartUpload await client.send(new CompleteMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId, MultipartUpload: { Parts: parts }, })); } // ── Upload a local file (by job ID or file ID) directly to S3 ───────────────── app.post("/api/s3/upload-local", async (req, res) => { const { jobId, fileId, prefix, ...rest } = req.body || {}; const p = parseS3ReqParams(rest); if (!p) return res.status(400).json({ ok: false, error: "Missing S3 params (bucketName, accessKeyId, secretAccessKey, region, host)" }); let filePath; let filename; if (jobId) { const job = jobs.get(String(jobId)); if (!job) return res.status(404).json({ ok: false, error: "Job not found" }); if (!job.outputFilename) return res.status(400).json({ ok: false, error: "Job output filename not yet known (job may still be running)" }); filePath = path.join(ENCODED_DIR, job.outputFilename); filename = job.outputFilename; } else if (fileId) { const info = resolveFileFromId(decodeURIComponent(String(fileId))); if (!info) return res.status(400).json({ ok: false, error: "Invalid file id" }); filePath = info.filePath; filename = info.name; } else { return res.status(400).json({ ok: false, error: "jobId or fileId is required" }); } let stat; try { stat = await fsp.stat(filePath); } catch { return res.status(404).json({ ok: false, error: "File not found on disk" }); } try { const pathStr = `/${encodeURIComponent(p.bucketName)}${s3KeyPath(prefix || "", filename)}`; if (stat.size > MULTIPART_THRESHOLD) { // Large file: use multipart upload (CreateMultipartUpload → UploadPart × N → Complete) await s3MultipartUpload( p.host, pathStr, p.region, p.accessKeyId, p.secretAccessKey, filePath, stat.size ); } else { // Small file: single streaming PUT (existing path) const bodyHash = await hashFileStream(filePath); const fileStream = fs.createReadStream(filePath); await s3StreamUpload(p.host, pathStr, p.region, p.accessKeyId, p.secretAccessKey, bodyHash, fileStream, stat.size); } return res.json({ ok: true, filename }); } catch (err) { return res.status(500).json({ ok: false, error: err.message || "Upload failed" }); } }); // ── Trim Segments (Simple trim with saved crop settings) ───────────────────── app.post("/api/trim-segments", async (req, res) => { const { fileId, segments } = req.body || {}; if (!fileId || !segments || !Array.isArray(segments) || segments.length === 0) { return res.status(400).json({ error: "fileId and segments (non-empty array) 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" }); } // Validate segments for (const seg of segments) { const startSec = parseLooseClockToSeconds(String(seg.start)); const endSec = parseLooseClockToSeconds(String(seg.end)); if (startSec == null || endSec == null || endSec <= startSec) { return res.status(400).json({ error: "Invalid segment times" }); } } // Save output to same folder as source const sourceDir = path.dirname(info.filePath); const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR; const relOutDir = path.relative(base, sourceDir); const outputFolder = relOutDir ? `/${relOutDir}` : "/"; // Calculate total duration for progress const totalDuration = segments.reduce((sum, seg) => { return sum + (parseLooseClockToSeconds(String(seg.end)) - parseLooseClockToSeconds(String(seg.start))); }, 0); const jobId = randomId("trim_seg"); const job = { id: jobId, createdAt: Date.now(), status: "running", _process: null, outputFolder, outputSource: info.source, settings: { inputFilename: info.name, segmentCount: segments.length, type: "trim_segments" }, progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: ["Starting segment trimming..."] }, }; jobs.set(jobId, job); // Process each segment const outputFiles = []; let processedSegments = 0; try { for (let i = 0; i < segments.length; i++) { const seg = segments[i]; const startSec = parseLooseClockToSeconds(String(seg.start)); const endSec = parseLooseClockToSeconds(String(seg.end)); const duration = endSec - startSec; // Get unique output filename const { name: outName, fullPath: outPath } = getUniqueFilePath(sourceDir, String(seg.outputFilename)); const segJob = jobs.get(jobId); if (segJob) { segJob.progress.log.push(`Trimming segment ${i + 1}/${segments.length}: ${seg.start} - ${seg.end}`); } // Use stream copy for fast, lossless trimming const args = [ "-y", "-ss", String(startSec), "-t", String(duration), "-i", info.filePath, "-c", "copy", // Stream copy - fast and lossless "-avoid_negative_ts", "make_zero", outPath ]; await new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] }); 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); }); ffmpeg.on("error", reject); ffmpeg.on("close", (code) => { if (code === 0) resolve(); else reject(new Error(`ffmpeg exited with code ${code} for segment ${i + 1}`)); }); }); // Save crop settings to a JSON file alongside the trimmed segment if (seg.cropSettings && seg.cropSettings.enabled) { const cropSettingsPath = outPath + ".crop.json"; const cropData = { cropEnabled: true, cropLeft: seg.cropSettings.left || 0, cropRight: seg.cropSettings.right || 0, cropTop: seg.cropSettings.top || 0, cropBottom: seg.cropSettings.bottom || 0, sourceFile: info.name, segmentStart: seg.start, segmentEnd: seg.end, createdAt: Date.now() }; await fsp.writeFile(cropSettingsPath, JSON.stringify(cropData, null, 2)); const latest = jobs.get(jobId); if (latest) { latest.progress.log.push(`Saved crop settings for segment ${i + 1}`); } } outputFiles.push(outName); processedSegments++; // Update progress const latest = jobs.get(jobId); if (latest) { latest.progress.percent = Math.round((processedSegments / segments.length) * 100); } } const final = jobs.get(jobId); if (final) { final.status = "done"; final.progress.percent = 100; final.progress.etaSeconds = 0; final.progress.log.push(`Trimmed ${segments.length} segment(s) successfully.`); final.progress.log.push(`Output files: ${outputFiles.join(", ")}`); final.outputFilename = outputFiles.join(", "); persistJobHistory(); } const { _process: _p, ...safeJob } = job; return res.json({ job: safeJob, outputFiles }); } catch (err) { const failed = jobs.get(jobId); if (failed) { failed.status = "failed"; failed.progress.log.push(`Error: ${err.message}`); persistJobHistory(); } return res.status(500).json({ error: err.message }); } }); // ── Trim + Encode + Merge ────────────────────────────────────────────────────── // Each segment is trimmed + encoded (with its own crop settings) in one ffmpeg pass, // then all encoded segments are concatenated into a single output file. app.post("/api/trim-encode-merge", async (req, res) => { const { fileId, segments, encodeSettings } = req.body || {}; if (!fileId || !Array.isArray(segments) || segments.length === 0) { return res.status(400).json({ error: "fileId and segments (non-empty array) 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" }); } for (const seg of segments) { const startSec = parseLooseClockToSeconds(String(seg.start)); const endSec = parseLooseClockToSeconds(String(seg.end)); if (startSec == null || endSec == null || endSec <= startSec) { return res.status(400).json({ error: `Invalid times for segment: ${seg.start} → ${seg.end}` }); } } const totalDuration = segments.reduce((sum, seg) => { return sum + (parseLooseClockToSeconds(String(seg.end)) - parseLooseClockToSeconds(String(seg.start))); }, 0); const enc = encodeSettings || {}; const baseExt = enc.codec === "av1" ? ".mkv" : enc.codec === "h265" ? ".mkv" : ".mp4"; const baseName = info.name.replace(/\.[^.]+$/, ""); const desiredOutName = `${baseName}_encoded_merged${baseExt}`; const { name: outName, fullPath: outPath } = getUniqueFilePath(ENCODED_DIR, desiredOutName); const jobId = randomId("tem"); const job = { id: jobId, createdAt: Date.now(), startedAt: Date.now(), status: "running", _process: null, outputFolder: "/", outputSource: "encoded", batchIndex: null, batchTotal: null, settings: { type: "trim_encode_merge", inputFilename: info.name, outputFilename: outName, segmentCount: segments.length, codec: enc.codec || "h264", }, progress: { percent: 0, fps: 0, etaSeconds: totalDuration * 5, sizeOutBytes: 0, speed: 0, bitrateKbps: 0, log: [`Starting trim+encode+merge: ${segments.length} segment(s)...`], }, }; jobs.set(jobId, job); res.json({ ok: true, jobId }); let tempDir = null; (async () => { try { tempDir = path.join(os.tmpdir(), `tem-${jobId}`); await fsp.mkdir(tempDir, { recursive: true }); const segPaths = []; for (let i = 0; i < segments.length; i++) { const seg = segments[i]; const startSec = parseLooseClockToSeconds(String(seg.start)); const endSec = parseLooseClockToSeconds(String(seg.end)); const segOut = path.join(tempDir, `seg_${String(i).padStart(3, "0")}${baseExt}`); // Merge per-segment crop into encode settings const segSettings = { codec: enc.codec || "h264", mode: enc.mode || "crf-1pass", crf: enc.crf ?? (enc.codec === "av1" ? 45 : enc.codec === "h265" ? 28 : 23), videoBitrateKbps: enc.videoBitrateKbps || 2000, audioBitrateKbps: enc.audioBitrateKbps || 96, resolution: enc.resolution || "original", frameRate: "original", // prevent buildEncodeArgs pushing "-r undefined" sameAsOriginalAudio: Boolean(enc.sameAsOriginalAudio), sameAsOriginalVideo: false, // always re-encode so crop filter applies h26xPreset: enc.h26xPreset || "medium", preset: enc.av1Preset ?? enc.preset ?? 5, // SVT-AV1 preset (modal sends av1Preset) aqMode: enc.aqMode ?? 0, tiles: enc.tiles ?? "0", startTime: seg.start, endTime: seg.end, cropEnabled: Boolean(seg.cropEnabled), cropLeft: Number(seg.cropLeft) || 0, cropRight: Number(seg.cropRight) || 0, cropTop: Number(seg.cropTop) || 0, cropBottom: Number(seg.cropBottom) || 0, }; const args = buildEncodeArgs(segSettings, info.filePath, segOut); const current = jobs.get(jobId); if (current) { current.progress.log.push( `[Seg ${i + 1}/${segments.length}] Encoding ${seg.start}→${seg.end}${seg.cropEnabled ? " + crop" : ""}…` ); } const completedDuration = segments.slice(0, i).reduce( (sum, s) => sum + (parseLooseClockToSeconds(String(s.end)) - parseLooseClockToSeconds(String(s.start))), 0 ); await new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] }); job._process = ffmpeg; ffmpeg.stderr.on("data", (chunk) => { const line = chunk.toString(); const cur = jobs.get(jobId); if (!cur) return; cur.progress.log.push(line.trim()); if (cur.progress.log.length > 600) cur.progress.log = cur.progress.log.slice(-600); const timeMatch = line.match(/time=([0-9:.]+)/); if (timeMatch) { const secs = parseFfmpegTimeToSeconds(timeMatch[1]); const totalDone = completedDuration + secs; cur.progress.percent = Math.min(93, (totalDone / totalDuration) * 93); const elapsed = (Date.now() - job.startedAt) / 1000; const speed = elapsed > 0 ? totalDone / elapsed : 0; cur.progress.etaSeconds = speed > 0 ? Math.max(0, (totalDuration - totalDone) / speed) : 0; } const fpsMatch = line.match(/fps=\s*([0-9.]+)/); if (fpsMatch) cur.progress.fps = Number(fpsMatch[1]) || 0; const bitrateMatch = line.match(/bitrate=\s*([0-9.]+)kbits\/s/); if (bitrateMatch) cur.progress.bitrateKbps = Number(bitrateMatch[1]) || 0; }); ffmpeg.on("error", reject); ffmpeg.on("close", (code) => { job._process = null; const cur = jobs.get(jobId); if (cur?.status === "stopped") return resolve(null); if (code === 0) resolve(null); else reject(new Error(`ffmpeg exited with code ${code} for segment ${i + 1}`)); }); }); if (jobs.get(jobId)?.status === "stopped") throw new Error("__stopped__"); segPaths.push(segOut); const cur2 = jobs.get(jobId); if (cur2) cur2.progress.log.push(`[Seg ${i + 1}/${segments.length}] Done.`); } // Merge encoded segments const cur3 = jobs.get(jobId); if (cur3) { cur3.progress.percent = 95; cur3.progress.log.push(`Merging ${segPaths.length} segment(s)…`); } if (segPaths.length === 1) { await safeMoveFile(segPaths[0], outPath); } else { const concatList = path.join(tempDir, "concat.txt"); await fsp.writeFile(concatList, segPaths.map(p => `file '${p.replace(/'/g, "'\\''")}'`).join("\n"), "utf8"); const mergeArgs = ["-y", "-f", "concat", "-safe", "0", "-i", concatList, "-c", "copy", outPath]; await new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", mergeArgs, { stdio: ["pipe", "ignore", "pipe"] }); job._process = ffmpeg; ffmpeg.stderr.on("data", (chunk) => { const cur = jobs.get(jobId); if (cur) { cur.progress.log.push(chunk.toString().trim()); } }); ffmpeg.on("error", reject); ffmpeg.on("close", (code) => { job._process = null; if (code === 0) resolve(null); else reject(new Error(`Merge failed with code ${code}`)); }); }); } const final = jobs.get(jobId); if (final) { final.status = "done"; final.progress.percent = 100; final.progress.etaSeconds = 0; try { const st = await fsp.stat(outPath); final.progress.sizeOutBytes = st.size; } catch { /* ignore */ } final.progress.log.push(`Done! Output: ${outName}`); persistJobHistory(); } } catch (err) { const failed = jobs.get(jobId); if (failed) { if (err.message !== "__stopped__") { failed.status = "failed"; failed.progress.log.push(`Error: ${err.message}`); } persistJobHistory(); } } finally { if (tempDir) await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {}); } })(); }); // ── Advanced Trim & Crop ────────────────────────────────────────────────────── app.post("/api/advanced-trim-crop", async (req, res) => { const { fileId, segments, outputFilename, transitionSmoothness } = req.body || {}; if (!fileId || !segments || !Array.isArray(segments) || segments.length === 0 || !outputFilename) { return res.status(400).json({ error: "fileId, segments (non-empty array), 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" }); } // Validate segments for (const seg of segments) { const startSec = parseLooseClockToSeconds(String(seg.start)); const endSec = parseLooseClockToSeconds(String(seg.end)); if (startSec == null || endSec == null || endSec <= startSec) { return res.status(400).json({ error: "Invalid segment times" }); } if (seg.crop) { const { left, right, top, bottom } = seg.crop; if (left < 0 || right < 0 || top < 0 || bottom < 0 || left > 45 || right > 45 || top > 45 || bottom > 45) { return res.status(400).json({ error: "Crop values must be between 0 and 45" }); } } } // Save output to same folder as source const sourceDir = path.dirname(info.filePath); const { name: outName, fullPath: outPath } = getUniqueFilePath(sourceDir, String(outputFilename)); const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR; const relOutDir = path.relative(base, sourceDir); const outputFolder = relOutDir ? `/${relOutDir}` : "/"; // Calculate total duration const totalDuration = segments.reduce((sum, seg) => { return sum + (parseLooseClockToSeconds(String(seg.end)) - parseLooseClockToSeconds(String(seg.start))); }, 0); const transitionMs = Math.min(Math.max(Number(transitionSmoothness) || 300, 100), 1000); // 100-1000ms const jobId = randomId("adv_trim_crop"); const job = { id: jobId, createdAt: Date.now(), status: "running", _process: null, outputFolder, outputSource: info.source, settings: { inputFilename: info.name, outputFilename: outName, segments: segments.map(s => ({ start: s.start, end: s.end, crop: s.crop || null, transitionDuration: s.transitionDuration || transitionMs })), type: "advanced_trim_crop" }, progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: ["Starting advanced trim & crop..."] }, }; jobs.set(jobId, job); // Build FFmpeg concat file with per-segment filtering const concatDir = path.join(os.tmpdir(), `adv_trim_crop_${jobId}`); await fsp.mkdir(concatDir, { recursive: true }); const segmentFiles = []; let processedSeconds = 0; try { for (let i = 0; i < segments.length; i++) { const seg = segments[i]; const startSec = parseLooseClockToSeconds(String(seg.start)); const endSec = parseLooseClockToSeconds(String(seg.end)); const duration = endSec - startSec; const segOutput = path.join(concatDir, `segment_${String(i).padStart(3, "0")}.mkv`); const args = ["-y", "-ss", String(startSec), "-t", String(duration), "-i", info.filePath]; // Build filter chain const filters = []; if (seg.crop) { const { left = 0, right = 0, top = 0, bottom = 0 } = seg.crop; const cropW = 100 - left - right; const cropH = 100 - top - bottom; const cropX = left; const cropY = top; filters.push(`crop=iw*${Math.max(0, cropW) / 100}:ih*${Math.max(0, cropH) / 100}:iw*${Math.max(0, cropX) / 100}:ih*${Math.max(0, cropY) / 100}`); } args.push("-pix_fmt", "yuv420p"); args.push("-c:v", "libx264", "-preset", "fast", "-crf", "23"); args.push("-c:a", "libopus", "-b:a", "96k"); if (filters.length > 0) { args.push("-vf", filters.join(",")); } args.push(segOutput); const segJob = jobs.get(jobId); if (segJob) { segJob.progress.log.push(`Processing segment ${i + 1}/${segments.length}: ${seg.start} - ${seg.end}`); } await new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] }); 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, ((processedSeconds + secs) / totalDuration) * 100); latest.progress.etaSeconds = Math.max(0, totalDuration - (processedSeconds + secs)); } } }); ffmpeg.on("error", reject); ffmpeg.on("close", (code) => { if (code === 0) resolve(); else reject(new Error(`ffmpeg exited with code ${code} processing segment ${i + 1}`)); }); }); processedSeconds += duration; segmentFiles.push(segOutput); } // Create concat file const concatFilePath = path.join(concatDir, "concat_list.txt"); const concatContent = segmentFiles.map(f => `file '${f.replace(/'/g, "'\\''")}'`).join("\n"); await fsp.writeFile(concatFilePath, concatContent, "utf8"); // Join segments using concat demuxer const concatArgs = ["-y", "-f", "concat", "-safe", "0", "-i", concatFilePath, "-c:v", "libx264", "-preset", "fast", "-crf", "23", "-c:a", "libopus", "-b:a", "96k", "-pix_fmt", "yuv420p"]; // Add transition crossfade if we have multiple segments if (segmentFiles.length > 1) { // Use ffmpeg crossfade filters between segments const transitionSeconds = transitionMs / 1000; const crossfadeArgs = ["-y"]; for (let i = 0; i < segmentFiles.length; i++) { crossfadeArgs.push("-i", segmentFiles[i]); } // Build filter complex for crossfade const filterParts = []; let prevLabel = "0:v:0"; let prevALabel = "0:a:0"; for (let i = 1; i < segmentFiles.length; i++) { const offset = duration - transitionSeconds * (i); const label = `v${i}`; const aLabel = `a${i}`; filterParts.push( `[${prevLabel}][${i}:v:0]xfade=transition=fade:offset=${Math.max(0, offset)}:duration=${transitionSeconds}[${label}]`, `[${prevALabel}][${i}:a:0]acrossfade=d=${transitionSeconds}:c1=tri:curve1=nofade:curve2=nofade[${aLabel}]` ); prevLabel = label; prevALabel = aLabel; } if (filterParts.length > 0) { crossfadeArgs.push("-filter_complex", filterParts.join("; ")); crossfadeArgs.push("-map", `[${prevLabel}]`); crossfadeArgs.push("-map", `[${prevALabel}]`); } else { crossfadeArgs.push("-map", "0:v:0"); crossfadeArgs.push("-map", "0:a:0"); } crossfadeArgs.push("-c:v", "libx264", "-preset", "fast", "-crf", "23"); crossfadeArgs.push("-c:a", "libopus", "-b:a", "96k"); crossfadeArgs.push("-pix_fmt", "yuv420p"); crossfadeArgs.push(outPath); const latest = jobs.get(jobId); if (latest) { latest.progress.log.push("Applying smooth transitions between segments..."); } await new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", crossfadeArgs, { stdio: ["pipe", "ignore", "pipe"] }); 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); }); ffmpeg.on("error", reject); ffmpeg.on("close", (code) => { if (code === 0) resolve(); else reject(new Error(`ffmpeg exited with code ${code} during transition pass`)); }); }); } else { // Single segment - just copy const latest = jobs.get(jobId); if (latest) { latest.progress.log.push("Processing single segment..."); } await new Promise((resolve, reject) => { const ffmpeg = spawn("ffmpeg", concatArgs, { stdio: ["pipe", "ignore", "pipe"] }); 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); }); ffmpeg.on("error", reject); ffmpeg.on("close", (code) => { if (code === 0) resolve(); else reject(new Error(`ffmpeg exited with code ${code}`)); }); }); } // Cleanup temp files await fsp.rm(concatDir, { recursive: true, force: true }).catch(() => {}); const final = jobs.get(jobId); if (final) { final.status = "done"; final.progress.percent = 100; final.progress.etaSeconds = 0; try { const st = await fsp.stat(outPath); final.progress.sizeOutBytes = st.size; } catch {} final.progress.log.push(`Advanced trim & crop completed. Output: ${outName}`); final.outputFilename = outName; persistJobHistory(); } } catch (err) { await fsp.rm(concatDir, { recursive: true, force: true }).catch(() => {}); const failed = jobs.get(jobId); if (failed) { failed.status = "failed"; failed.progress.log.push(`Error: ${err.message}`); persistJobHistory(); } // Don't send error here since we already sent the response return; } const { _process: _p, ...safeJob } = job; return res.json({ job: safeJob }); }); // ── 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}`); });