telev / App.tsx
mozolla's picture
Upload 34 files
9df6ae5 verified
Raw History Blame Contribute Delete
211 kB
import { useCallback, useEffect, useRef, useState } from "react"; // ─── Types ──────────────────────────────────────────────────────────────────── interface FileEntry { id: string; name: string; relativePath: string; sizeBytes: number; source: "downloaded" | "encoded"; createdAt: number; folder: string; } interface Job { id: string; createdAt: number; status: "running" | "done" | "failed" | "stopped"; settings: Record<string, unknown>; batchIndex: number | null; batchTotal: number | null; outputFolder: string; outputSource: string; progress: { percent: number; fps: number; etaSeconds: number; sizeOutBytes: number; log: string[]; }; } interface DownloadJob { id: string; status: "running" | "done" | "failed" | "stopped"; url: string; filename: string | null; bytesDownloaded: number; totalBytes: number; error: string | null; } interface VideoInfo { fileSize: string; fileSizeBytes: number; duration: string; durationSeconds: number; video: { codec: string; profile: string | null; resolution: string; width: number; height: number; frameRate: string; bitrate: string; bitrateRaw: number; pixFmt: string; streamSize: string; } | null; audio: { codec: string; sampleRate: string; channels: number | string; channelLayout: string; bitrate: string; bitrateRaw: number; streamSize: string; } | null; encodeSettings?: { createdAt?: number; inputFilename?: string; outputFilename?: string; resolution?: string; settings?: Record<string, unknown>; } | null; } type Tab = "files" | "encode" | "jobs" | "remote"; interface RemoteEntry { name: string; isDir: boolean; size?: number; sizeStr?: string; type?: string; } interface PixeldrainJob { id: string; status: "running" | "done" | "failed"; filename: string; bytesUploaded: number; totalBytes: number; pixeldrainUrl: string | null; error: string | null; } interface QueueItem { uid: string; file: FileEntry; status: "waiting" | "encoding" | "done" | "failed"; jobId: string | null; settings: Record<string, unknown>; presetLabel?: string; } interface EncodePreset { id: number; label: string; settings: Record<string, unknown>; } // ─── Helpers ────────────────────────────────────────────────────────────────── function fmt(bytes: number): string { 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`; } function fmtEta(s: number): string { if (!Number.isFinite(s) || s <= 0) return "0s"; const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const sec = Math.floor(s % 60); return [h && `${h}h`, m && `${m}m`, `${sec}s`].filter(Boolean).join(" "); } function secondsToHms(total: number): string { const h = Math.floor(total / 3600); const m = Math.floor((total % 3600) / 60); const s = Math.floor(total % 60); return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; } function hmsToSeconds(hms: string): number { const parts = hms.split(":").map(Number); if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2]; if (parts.length === 2) return parts[0] * 60 + parts[1]; return parts[0] || 0; } function pad2(v: number): string { return String(Math.max(0, v)).padStart(2, "0"); } function toHmsString(h: number, m: number, s: number): string { return `${pad2(h)}:${pad2(m)}:${pad2(s)}`; } function clampParts(h: number, m: number, s: number, maxSeconds?: number): { h: number; m: number; s: number } { let hh = Math.max(0, h); let mm = Math.min(59, Math.max(0, m)); let ss = Math.min(59, Math.max(0, s)); if (maxSeconds !== undefined) { const total = Math.max(0, hh * 3600 + mm * 60 + ss); if (total > maxSeconds) { const clamped = Math.max(0, Math.floor(maxSeconds)); hh = Math.floor(clamped / 3600); mm = Math.floor((clamped % 3600) / 60); ss = Math.floor(clamped % 60); } } return { h: hh, m: mm, s: ss }; } function parseHmsParts(value: string): { h: number; m: number; s: number } { const parts = value.split(":").map((p) => parseInt(p, 10)); if (parts.length === 3) return { h: parts[0] || 0, m: parts[1] || 0, s: parts[2] || 0 }; if (parts.length === 2) return { h: 0, m: parts[0] || 0, s: parts[1] || 0 }; if (parts.length === 1 && parts[0]) return { h: 0, m: 0, s: parts[0] || 0 }; return { h: 0, m: 0, s: 0 }; } function TimePartsInput({ value, onChange, maxSeconds, allowEmpty = false, }: { value: string; onChange: (next: string) => void; maxSeconds?: number; allowEmpty?: boolean; }) { const parsed = parseHmsParts(value); const [hLocal, setHLocal] = useState(pad2(parsed.h)); const [mLocal, setMLocal] = useState(pad2(parsed.m)); const [sLocal, setSLocal] = useState(pad2(parsed.s)); const hRef = useRef<HTMLInputElement>(null); const mRef = useRef<HTMLInputElement>(null); const sRef = useRef<HTMLInputElement>(null); const vals = useRef({ h: pad2(parsed.h), m: pad2(parsed.m), s: pad2(parsed.s) }); // Sync from parent ONLY when no field is focused (external changes like slider drag) useEffect(() => { const active = document.activeElement; if (active === hRef.current || active === mRef.current || active === sRef.current) return; const p = parseHmsParts(value); const h = pad2(p.h), m = pad2(p.m), s = pad2(p.s); setHLocal(h); setMLocal(m); setSLocal(s); vals.current = { h, m, s }; }, [value]); const commit = () => { const hNum = parseInt(vals.current.h, 10) || 0; const mNum = Math.min(59, parseInt(vals.current.m, 10) || 0); const sNum = Math.min(59, parseInt(vals.current.s, 10) || 0); const clamped = clampParts(hNum, mNum, sNum, maxSeconds); onChange(toHmsString(clamped.h, clamped.m, clamped.s)); }; const handleInput = (field: "h" | "m" | "s", raw: string) => { const digits = raw.replace(/\D/g, "").slice(0, 2); vals.current[field] = digits; if (field === "h") setHLocal(digits); if (field === "m") setMLocal(digits); if (field === "s") setSLocal(digits); // Auto-jump after 2 digits typed if (digits.length >= 2) { if (field === "h") { setTimeout(() => { mRef.current?.focus(); mRef.current?.select(); }, 0); } if (field === "m") { setTimeout(() => { sRef.current?.focus(); sRef.current?.select(); }, 0); } commit(); } }; const handleBlur = (field: "h" | "m" | "s") => { const num = parseInt(vals.current[field], 10) || 0; const clamped = field === "h" ? num : Math.min(59, num); const padded = pad2(clamped); vals.current[field] = padded; if (field === "h") setHLocal(padded); if (field === "m") setMLocal(padded); if (field === "s") setSLocal(padded); commit(); }; const handleKeyDown = (field: "h" | "m" | "s", e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Backspace" && e.currentTarget.value === "") { if (field === "m") { hRef.current?.focus(); hRef.current?.select(); } if (field === "s") { mRef.current?.focus(); mRef.current?.select(); } } }; const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => { e.target.select(); }; const fieldCls = "w-12 rounded-lg border border-slate-200 px-1 py-2 text-sm font-mono text-center focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"; return ( <div className="flex items-center gap-1"> <input ref={hRef} type="text" inputMode="numeric" maxLength={2} value={allowEmpty && !value.trim() ? "" : hLocal} placeholder="HH" onChange={(e) => handleInput("h", e.target.value)} onBlur={() => handleBlur("h")} onKeyDown={(e) => handleKeyDown("h", e)} onFocus={handleFocus} className={fieldCls} /> <span className="text-slate-400 font-bold text-sm">:</span> <input ref={mRef} type="text" inputMode="numeric" maxLength={2} value={allowEmpty && !value.trim() ? "" : mLocal} placeholder="MM" onChange={(e) => handleInput("m", e.target.value)} onBlur={() => handleBlur("m")} onKeyDown={(e) => handleKeyDown("m", e)} onFocus={handleFocus} className={fieldCls} /> <span className="text-slate-400 font-bold text-sm">:</span> <input ref={sRef} type="text" inputMode="numeric" maxLength={2} value={allowEmpty && !value.trim() ? "" : sLocal} placeholder="SS" onChange={(e) => handleInput("s", e.target.value)} onBlur={() => handleBlur("s")} onKeyDown={(e) => handleKeyDown("s", e)} onFocus={handleFocus} className={fieldCls} /> {allowEmpty && value.trim() && ( <button type="button" onClick={() => onChange("")} className="ml-1 text-xs text-slate-400 hover:text-slate-600">Clear</button> )} </div> ); } // ─── File Type Helpers ──────────────────────────────────────────────────────── const MEDIA_EXTS = new Set([ ".mp4",".mkv",".avi",".mov",".webm",".ts",".m2ts",".flv",".wmv",".mpg",".mpeg", ".mp3",".aac",".opus",".flac",".wav",".m4a",".ogg",".wma",".m4v",".3gp",".vob", ]); const ARCHIVE_EXTS = new Set([ ".zip",".tar",".gz",".tgz",".bz2",".xz",".rar",".7z", ]); const SUBTITLE_EXTS = new Set([ ".srt", ".ass", ".ssa", ".vtt", ".sub", ]); function isMediaFile(name: string): boolean { const lower = name.toLowerCase(); for (const ext of MEDIA_EXTS) { if (lower.endsWith(ext)) return true; } // Handle double extensions like .tar.gz return false; } function isSubtitleFile(name: string): boolean { const lower = name.toLowerCase(); for (const ext of SUBTITLE_EXTS) { if (lower.endsWith(ext)) return true; } return false; } function isArchiveFile(name: string): boolean { const lower = name.toLowerCase(); if (lower.endsWith(".tar.gz") || lower.endsWith(".tar.xz") || lower.endsWith(".tar.bz2")) return true; for (const ext of ARCHIVE_EXTS) { if (lower.endsWith(ext)) return true; } return false; } // ─── Help Tooltip ──────────────────────────────────────────────────────────── function HelpTip({ text }: { text: string }) { const [show, setShow] = useState(false); return ( <span className="relative inline-flex ml-1"> <button type="button" onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)} onFocus={() => setShow(true)} onBlur={() => setShow(false)} onClick={(e) => { e.preventDefault(); setShow((v) => !v); }} className="inline-flex items-center justify-center h-4 w-4 rounded-full bg-slate-200 text-[9px] font-bold text-slate-500 hover:bg-violet-200 hover:text-violet-700 transition-colors cursor-help flex-shrink-0" aria-label="Help" >?</button> {show && ( <div className="absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-1.5 w-64 rounded-lg bg-slate-800 px-3 py-2 text-[11px] leading-relaxed text-slate-100 shadow-xl pointer-events-none"> {text} <div className="absolute left-1/2 -translate-x-1/2 top-full w-0 h-0 border-x-4 border-x-transparent border-t-4 border-t-slate-800" /> </div> )} </span> ); } // ─── Toast ─────────────────────────────────────────────────────────────────── function Toast({ message, onDone }: { message: string; onDone: () => void }) { useEffect(() => { const t = setTimeout(onDone, 2500); return () => clearTimeout(t); }, [onDone]); return ( <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[100] rounded-full bg-slate-800 px-5 py-2.5 text-xs font-semibold text-white shadow-xl"> {message} </div> ); } // ─── Pixeldrain Upload Progress ─────────────────────────────────────────────── function PixeldrainProgress({ jobId, onClose }: { jobId: string; onClose: () => void }) { const [job, setJob] = useState<PixeldrainJob | null>(null); const [copied, setCopied] = useState(false); useEffect(() => { const poll = async () => { try { const r = await fetch(`/api/pixeldrain-jobs/${jobId}`); const data = await r.json(); setJob(data.job); if (data.job.status !== "running") clearInterval(iv); } catch { /* ignore */ } }; poll(); const iv = setInterval(poll, 800); return () => clearInterval(iv); }, [jobId]); const copyUrl = () => { if (!job?.pixeldrainUrl) return; navigator.clipboard.writeText(job.pixeldrainUrl); setCopied(true); setTimeout(() => setCopied(false), 2000); }; if (!job) return null; const percent = job.totalBytes > 0 ? Math.min(100, (job.bytesUploaded / job.totalBytes) * 100) : null; return ( <div className="rounded-xl border border-slate-200 bg-white p-4 space-y-3"> <div className="flex items-start justify-between gap-2"> <div className="min-w-0 flex-1"> <p className="text-xs font-semibold text-slate-700 flex items-center gap-1.5"> <span>☁️</span> <span className="truncate">{job.filename}</span> </p> <p className="text-[10px] text-slate-400 mt-0.5">Uploading to Pixeldrain…</p> </div> <div className="flex items-center gap-2 flex-shrink-0"> <span className={`text-xs font-semibold capitalize ${ job.status === "done" ? "text-emerald-600" : job.status === "failed" ? "text-red-500" : "text-violet-600" }`}>{job.status}</span> <button onClick={onClose} className="rounded p-1 text-slate-400 hover:text-slate-600 hover:bg-slate-100"> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> </div> <div className="space-y-1"> <div className="relative h-2 w-full overflow-hidden rounded-full bg-slate-100"> {percent !== null ? ( <div className={`h-full rounded-full transition-all duration-300 ${ job.status === "done" ? "bg-emerald-500" : job.status === "failed" ? "bg-red-400" : "bg-violet-500" }`} style={{ width: `${percent}%` }} /> ) : ( <div className="h-full w-1/3 rounded-full bg-violet-500 animate-[slide_1.2s_ease-in-out_infinite]" /> )} </div> <div className="flex justify-between text-[10px] text-slate-400"> <span>{fmt(job.bytesUploaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""}</span> {percent !== null && <span>{percent.toFixed(1)}%</span>} </div> </div> {job.status === "done" && job.pixeldrainUrl && ( <div className="flex items-center gap-2 rounded-lg bg-emerald-50 border border-emerald-200 px-3 py-2"> <a href={job.pixeldrainUrl} target="_blank" rel="noreferrer" className="flex-1 truncate text-xs font-medium text-emerald-700 hover:underline"> {job.pixeldrainUrl} </a> <button onClick={copyUrl} className="flex-shrink-0 rounded-md bg-emerald-100 hover:bg-emerald-200 px-2 py-1 text-[10px] font-semibold text-emerald-700 transition-colors"> {copied ? "βœ“ Copied" : "Copy"} </button> </div> )} {job.status === "failed" && ( <p className="text-xs text-red-500">{job.error || "Upload failed"}</p> )} </div> ); } // ─── Merge Modal ────────────────────────────────────────────────────────────── interface MergeItem { uid: string; file: FileEntry; } function MergeModal({ files, onClose, onMergeStarted }: { files: FileEntry[]; onClose: () => void; onMergeStarted: () => void; }) { const [items, setItems] = useState<MergeItem[]>(() => files.map((f) => ({ uid: `${f.id}_${Math.random().toString(16).slice(2)}`, file: f })) ); const [outName, setOutName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const dragUid = useRef<string | null>(null); const dragOverUid = useRef<string | null>(null); useEffect(() => { if (!items[0]?.file) { setOutName("merged_output.mkv"); return; } const name = items[0].file.name; const ext = name.match(/(\.[^.]+)$/)?.[1] || ".mkv"; const baseName = name.replace(/(\.[^.]+)$/, ""); setOutName(`${baseName}_merged${ext}`); }, [items]); const moveUp = (idx: number) => { if (idx === 0) return; const next = [...items]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; setItems(next); }; const moveDown = (idx: number) => { if (idx === items.length - 1) return; const next = [...items]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; setItems(next); }; const handleDragStart = (uid: string) => { dragUid.current = uid; }; const handleDragOver = (e: React.DragEvent, uid: string) => { e.preventDefault(); dragOverUid.current = uid; }; const handleDrop = () => { if (!dragUid.current || !dragOverUid.current || dragUid.current === dragOverUid.current) return; const from = items.findIndex((i) => i.uid === dragUid.current); const to = items.findIndex((i) => i.uid === dragOverUid.current); if (from === -1 || to === -1) return; const next = [...items]; const [moved] = next.splice(from, 1); next.splice(to, 0, moved); setItems(next); dragUid.current = null; dragOverUid.current = null; }; const removeItem = (uid: string) => setItems((prev) => prev.filter((i) => i.uid !== uid)); const handleMerge = async () => { if (items.length < 2) { setError("Need at least 2 files to merge"); return; } if (!outName.trim()) { setError("Output filename is required"); return; } setError(null); setBusy(true); try { const r = await fetch("/api/merge", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileIds: items.map((i) => i.file.id), outputFilename: outName.trim() }), }); const data = await r.json(); if (data.error) { setError(data.error); setBusy(false); return; } onMergeStarted(); onClose(); } catch { setError("Failed to start merge"); setBusy(false); } }; return ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 flex-shrink-0"> <div className="flex items-center gap-2"> <span className="text-lg">πŸ”—</span> <h2 className="text-sm font-bold text-slate-800">Merge Files</h2> <span className="rounded-full bg-violet-100 px-2 py-0.5 text-xs font-semibold text-violet-700">{items.length} files</span> </div> <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="flex-1 overflow-y-auto p-5 space-y-3"> <div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2"> Drag rows or use ↑↓ to set order. Files joined topβ†’bottom via stream copy (lossless, instant). </div> <div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100"> {items.map((item, idx) => ( <div key={item.uid} draggable onDragStart={() => handleDragStart(item.uid)} onDragOver={(e) => handleDragOver(e, item.uid)} onDrop={handleDrop} className="flex items-center gap-3 px-4 py-3 hover:bg-slate-50 cursor-grab active:cursor-grabbing transition-colors"> <svg className="h-4 w-4 flex-shrink-0 text-slate-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" /> </svg> <span className="flex h-6 w-6 items-center justify-center rounded-full bg-violet-100 text-[11px] font-bold text-violet-700 flex-shrink-0">{idx + 1}</span> <div className="flex-1 min-w-0"> <p className="truncate text-sm font-medium text-slate-800" title={item.file.name}>{item.file.name}</p> <p className="text-[10px] text-slate-400">{fmt(item.file.sizeBytes)} Β· {item.file.folder}</p> </div> <div className="flex items-center gap-1 flex-shrink-0"> <button onClick={() => moveUp(idx)} disabled={idx === 0} className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" /> </svg> </button> <button onClick={() => moveDown(idx)} disabled={idx === items.length - 1} className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" /> </svg> </button> {items.length > 2 && ( <button onClick={() => removeItem(item.uid)} className="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-600"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> )} </div> </div> ))} </div> <div className="space-y-1"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Output Filename</label> <input type="text" value={outName} onChange={(e) => setOutName(e.target.value)} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> {error && <p className="text-xs text-red-500">{error}</p>} <div className="text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2"> πŸ’‘ Output saved to same folder as the first selected file. Stream copy = instant, lossless. </div> </div> <div className="px-5 pb-5 flex-shrink-0"> <button onClick={handleMerge} disabled={busy || items.length < 2 || !outName.trim()} className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50"> {busy ? "Starting Merge…" : `πŸ”— Merge ${items.length} Files`} </button> </div> </div> </div> ); } // ─── Move File Modal ────────────────────────────────────────────────────────── function MoveModal({ files, folders, onClose, onMoved }: { files: FileEntry[]; folders: string[]; onClose: () => void; onMoved: () => void; }) { const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const itemCount = files.length; const handleMove = async (targetFolder: string) => { if (files.every((f) => (f.folder || "/") === targetFolder)) { onClose(); return; } setBusy(true); setError(null); try { const ids = files.map((f) => f.id); const data = await api.batchMove(ids, targetFolder); if (data.error) { setError(data.error); setBusy(false); return; } onMoved(); onClose(); } catch { setError("Failed to move file(s)"); setBusy(false); } }; const allFolders = Array.from(new Set(["/", ...folders])).sort((a, b) => { if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b); }); return ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100"> <div className="flex items-center gap-2 min-w-0"> <span className="text-lg flex-shrink-0">↗️</span> <div className="min-w-0"> <h2 className="text-sm font-bold text-slate-800">Move {itemCount === 1 ? "File" : `${itemCount} Files`}</h2> <p className="text-[10px] text-slate-400 truncate"> {itemCount === 1 ? files[0].name : `${itemCount} selected files`} </p> </div> </div> <button onClick={onClose} className="flex-shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="p-4 space-y-2"> <p className="text-xs text-slate-500 mb-3">Select destination folder:</p> {error && <p className="text-xs text-red-500 mb-2">{error}</p>} <div className="rounded-xl border border-slate-200 overflow-hidden divide-y divide-slate-100 max-h-64 overflow-y-auto"> {allFolders.map((folder) => { const isCurrent = files.every((f) => (f.folder || "/") === folder); return ( <button key={folder} onClick={() => !busy && handleMove(folder)} disabled={busy || isCurrent} className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${ isCurrent ? "bg-violet-50 cursor-not-allowed" : "hover:bg-slate-50" }`}> <svg className={`h-4 w-4 flex-shrink-0 ${isCurrent ? "text-violet-500" : "text-amber-500"}`} fill="currentColor" viewBox="0 0 24 24"> <path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" /> </svg> <span className={`text-sm font-medium flex-1 truncate ${isCurrent ? "text-violet-700" : "text-slate-700"}`}> {folder === "/" ? "/ (root)" : folder} </span> {isCurrent && ( <span className="text-[10px] text-violet-500 font-semibold flex-shrink-0">current</span> )} </button> ); })} </div> {busy && <p className="text-xs text-slate-400 text-center">Moving…</p>} </div> </div> </div> ); } // ─── Create Folder Modal ────────────────────────────────────────────────────── function CreateFolderModal({ onClose, onCreated }: { onClose: () => void; onCreated: (name: string) => void }) { const [name, setName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const handleCreate = async () => { const trimmed = name.trim(); if (!trimmed) { setError("Folder name is required"); return; } setBusy(true); setError(null); try { const data = await api.createFolder(trimmed); if (data.error) { setError(data.error); setBusy(false); return; } onCreated(data.folder ?? `/${trimmed}`); onClose(); } catch { setError("Failed to create folder"); setBusy(false); } }; return ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xs" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100"> <div className="flex items-center gap-2"> <span className="text-lg">πŸ“</span> <h2 className="text-sm font-bold text-slate-800">New Folder</h2> </div> <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="p-5 space-y-4"> <input autoFocus type="text" placeholder="Folder name…" value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") handleCreate(); if (e.key === "Escape") onClose(); }} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> {error && <p className="text-xs text-red-500">{error}</p>} <button onClick={handleCreate} disabled={busy || !name.trim()} className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors"> {busy ? "Creating…" : "Create Folder"} </button> </div> </div> </div> ); } // ─── API helpers ────────────────────────────────────────────────────────────── const api = { async getFiles(): Promise<{ downloaded: FileEntry[]; encoded: FileEntry[]; folders: string[] }> { const r = await fetch("/api/files"); return r.json(); }, async deleteFile(id: string): Promise<void> { await fetch(`/api/files/${encodeURIComponent(id)}`, { method: "DELETE" }); }, async batchDelete(ids: string[]): Promise<void> { await fetch("/api/batch/delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids }), }); }, async batchPixeldrain(ids: string[]): Promise<{ jobIds: string[] }> { const r = await fetch("/api/batch/pixeldrain", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids }), }); return r.json(); }, async renameFile(id: string, newName: string): Promise<{ id: string; name: string }> { const r = await fetch(`/api/files/${encodeURIComponent(id)}/rename`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ newName }), }); return r.json(); }, async moveFile(id: string, targetFolder: string): Promise<{ ok: boolean; error?: string }> { const r = await fetch(`/api/files/${encodeURIComponent(id)}/move`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ targetFolder }), }); return r.json(); }, async batchMove(ids: string[], targetFolder: string): Promise<{ ok: boolean; error?: string; results?: unknown }> { const r = await fetch(`/api/batch/move`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids, targetFolder }), }); return r.json(); }, async createFolder(folderName: string): Promise<{ ok: boolean; folder?: string; error?: string }> { const r = await fetch("/api/folders/create", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ folderName }), }); return r.json(); }, async renameFolder(oldPath: string, newName: string): Promise<{ ok: boolean; error?: string }> { const r = await fetch("/api/folders/rename", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ oldPath, newName }), }); return r.json(); }, async deleteFolder(folderPath: string): Promise<{ ok: boolean; error?: string }> { const r = await fetch("/api/folders", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ folderPath }), }); return r.json(); }, async startDownloadUrl(url: string, username?: string, password?: string): Promise<{ jobId: string }> { const r = await fetch("/api/download-url", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url, username, password }), }); return r.json(); }, async getDownloadJob(id: string): Promise<{ job: DownloadJob }> { const r = await fetch(`/api/download-jobs/${id}`); return r.json(); }, async stopDownloadJob(id: string): Promise<void> { await fetch(`/api/download-jobs/${id}/stop`, { method: "POST" }); }, async startEncode(settings: Record<string, unknown>): Promise<Job> { const r = await fetch("/api/encode", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(settings), }); const data = await r.json(); return data.job; }, async stopJob(id: string): Promise<void> { await fetch(`/api/jobs/${id}/stop`, { method: "POST" }); }, async getFileInfo(id: string): Promise<{ ok: boolean; info: VideoInfo }> { const r = await fetch(`/api/files/${encodeURIComponent(id)}/info`); return r.json(); }, async trimFile(fileId: string, startTime: number, endTime: number, outputFilename: string): Promise<Job> { const r = await fetch("/api/trim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileId, startTime, endTime, outputFilename }), }); const data = await r.json(); return data.job; }, async trimSegments(fileId: string, segments: { startTime: number; endTime: number }[], outputFilename: string): Promise<Job> { const r = await fetch("/api/trim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileId, segments, outputFilename }), }); const data = await r.json(); return data.job; }, async getJobs(): Promise<Job[]> { const r = await fetch("/api/jobs"); const data = await r.json(); return data.jobs; }, async getJob(id: string): Promise<Job> { const r = await fetch(`/api/jobs/${id}`); const data = await r.json(); return data.job; }, async uploadToPixeldrain(id: string): Promise<{ jobId: string }> { const r = await fetch(`/api/files/${encodeURIComponent(id)}/pixeldrain`, { method: "POST" }); return r.json(); }, async unzipFile(id: string): Promise<{ ok: boolean; outputFolder?: string; fileCount?: number; error?: string }> { const r = await fetch(`/api/files/${encodeURIComponent(id)}/unzip`, { method: "POST" }); return r.json(); }, async batchZip(ids: string[]): Promise<{ ok: boolean; filename?: string; fileCount?: number; error?: string }> { const r = await fetch("/api/batch/zip", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileIds: ids }), }); return r.json(); }, async remoteList(url: string): Promise<{ ok: boolean; entries: RemoteEntry[]; error?: string }> { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 8000); // 8 second timeout try { const r = await fetch(`/api/remote/list?url=${encodeURIComponent(url)}`, { signal: controller.signal, }); clearTimeout(timeoutId); if (!r.ok) { const text = await r.text().catch(() => ""); return { ok: false, entries: [], error: `Server returned ${r.status}: ${text.slice(0, 200)}` }; } return r.json(); } catch (err) { clearTimeout(timeoutId); if (err instanceof Error && err.name === "AbortError") { return { ok: false, entries: [], error: "Connection timed out (8s). Check that the remote server is running and accessible." }; } return { ok: false, entries: [], error: err instanceof Error ? err.message : "Failed to fetch" }; } }, async remoteDownload(serverUrl: string, remoteName: string, targetFolder?: string): Promise<{ jobId: string }> { const r = await fetch("/api/remote/download", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serverUrl, remoteName, filename: remoteName, targetFolder }), }); return r.json(); }, async remoteRename(serverUrl: string, oldName: string, newName: string): Promise<{ ok: boolean; error?: string }> { const r = await fetch("/api/remote/rename", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serverUrl, oldName, newName }), }); return r.json(); }, async remoteDelete(serverUrl: string, name: string): Promise<{ ok: boolean; error?: string }> { const r = await fetch("/api/remote/delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serverUrl, name }), }); return r.json(); }, async remoteUpload(serverUrl: string, file: File): Promise<{ ok: boolean; error?: string }> { const fd = new FormData(); fd.append("file", file); fd.append("serverUrl", serverUrl); const r = await fetch("/api/remote/upload", { method: "POST", body: fd }); return r.json(); }, async getRemoteDownloadJob(id: string): Promise<{ job: DownloadJob }> { const r = await fetch(`/api/remote/download-jobs/${id}`); return r.json(); }, async stopRemoteDownloadJob(id: string): Promise<void> { await fetch(`/api/remote/download-jobs/${id}/stop`, { method: "POST" }); }, }; // ─── Sub-components ─────────────────────────────────────────────────────────── function Badge({ children, color }: { children: React.ReactNode; color: string }) { return ( <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${color}`}> {children} </span> ); } function IconBtn({ title, onClick, children, danger, active, disabled }: { title: string; onClick: () => void; children: React.ReactNode; danger?: boolean; active?: boolean; disabled?: boolean; }) { return ( <button title={title} onClick={onClick} disabled={disabled} className={`rounded p-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${ danger ? "text-red-400 hover:bg-red-50 hover:text-red-600" : active ? "bg-violet-100 text-violet-700" : "text-slate-400 hover:bg-slate-100 hover:text-slate-600" }`}> {children} </button> ); } // ─── Info Modal ─────────────────────────────────────────────────────────────── function InfoModal({ file, onClose, initialShowEncode }: { file: FileEntry; onClose: () => void; initialShowEncode?: boolean }) { const [info, setInfo] = useState<VideoInfo | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [showEncodeSettings, setShowEncodeSettings] = useState(!!initialShowEncode); useEffect(() => { api.getFileInfo(file.id) .then((res) => { if (res.ok) setInfo(res.info); else setError("Failed to load info"); }) .catch(() => setError("Failed to load info")) .finally(() => setLoading(false)); }, [file.id]); const Row = ({ label, value }: { label: string; value: string }) => ( <div className="flex items-baseline justify-between gap-4 py-2 border-b border-slate-100 last:border-0"> <span className="text-xs font-semibold text-slate-500 whitespace-nowrap w-36 flex-shrink-0">{label}</span> <span className="text-xs text-slate-800 text-right font-mono break-all">{value}</span> </div> ); return ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100"> <div className="flex items-center gap-2 min-w-0"> <span className="text-lg flex-shrink-0">🎬</span> <h2 className="text-sm font-bold text-slate-800 truncate">{file.name}</h2> </div> <button onClick={onClose} className="flex-shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="p-5"> {loading && ( <div className="py-10 text-center text-sm text-slate-400"> <svg className="animate-spin h-6 w-6 mx-auto mb-2 text-violet-500" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> Analyzing file… </div> )} {error && <div className="py-6 text-center text-sm text-red-500">{error}</div>} {info && ( <div className="space-y-5"> <div> <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">General</h3> <div className="rounded-xl bg-slate-50 px-4 py-1"> <Row label="File Size" value={info.fileSize} /> <Row label="Duration" value={info.duration} /> </div> </div> {info.video && ( <div> <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">Video Stream</h3> <div className="rounded-xl bg-slate-50 px-4 py-1"> <Row label="Resolution" value={info.video.resolution} /> <Row label="Video Codec" value={info.video.profile ? `${info.video.codec} (${info.video.profile})` : info.video.codec} /> <Row label="Frame Rate" value={info.video.frameRate} /> <Row label="Video Bitrate" value={info.video.bitrate} /> <Row label="Pixel Format" value={info.video.pixFmt} /> <Row label="Stream Size" value={info.video.streamSize} /> </div> </div> )} {info.audio && ( <div> <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2">Audio Stream</h3> <div className="rounded-xl bg-slate-50 px-4 py-1"> <Row label="Audio Codec" value={info.audio.codec} /> <Row label="Sample Rate" value={info.audio.sampleRate} /> <Row label="Channels" value={`${info.audio.channels}${info.audio.channelLayout ? ` (${info.audio.channelLayout})` : ""}`} /> <Row label="Audio Bitrate" value={info.audio.bitrate} /> <Row label="Stream Size" value={info.audio.streamSize} /> </div> </div> )} {!info.video && !info.audio && ( <p className="text-sm text-slate-400 text-center py-4">No stream information available</p> )} {info.encodeSettings && ( <div className="pt-2"> <button onClick={() => setShowEncodeSettings((v) => !v)} className="flex items-center gap-2 text-xs font-semibold text-violet-600 hover:text-violet-700" > <span>{showEncodeSettings ? "β–Ό" : "β–Ά"}</span> Encoding Settings </button> {showEncodeSettings && ( <div className="mt-2 rounded-xl bg-slate-50 px-4 py-3 space-y-2"> <Row label="Input" value={info.encodeSettings.inputFilename || "unknown"} /> <Row label="Output" value={info.encodeSettings.outputFilename || "unknown"} /> {info.encodeSettings.resolution && ( <Row label="Actual Resolution" value={info.encodeSettings.resolution} /> )} {info.encodeSettings.settings && (() => { const s = info.encodeSettings.settings as Record<string, unknown>; const rows: Array<{ label: string; value: string }> = []; if (s.codec) rows.push({ label: "Codec", value: String(s.codec).toUpperCase() }); if (s.mode) rows.push({ label: "Mode", value: s.mode === "crf-1pass" ? "CRF (1-pass)" : "VBR" }); if (s.crf !== undefined) rows.push({ label: "CRF", value: String(s.crf) }); if (s.videoBitrateKbps) rows.push({ label: "Video Bitrate", value: `${s.videoBitrateKbps} kbps` }); if (s.audioBitrateKbps) rows.push({ label: "Audio Bitrate", value: `${s.audioBitrateKbps} kbps (Opus)` }); if (s.resolution) rows.push({ label: "Resolution", value: String(s.resolution) }); if (s.frameRate) rows.push({ label: "Frame Rate", value: String(s.frameRate) }); if (s.preset !== undefined) rows.push({ label: "Preset", value: String(s.preset) }); if (s.h26xPreset) rows.push({ label: "H26x Preset", value: String(s.h26xPreset) }); if (s.aqMode !== undefined) rows.push({ label: "AQ Mode", value: s.aqMode === 0 ? "0 (Off)" : s.aqMode === 1 ? "1 (Variance)" : "2 (Complexity)" }); if (s.tiles) rows.push({ label: "Tiles", value: String(s.tiles) }); if (s.outputContainer) rows.push({ label: "Container", value: String(s.outputContainer).toUpperCase() }); if (s.audioChannels) rows.push({ label: "Audio Channels", value: String(s.audioChannels) }); if (s.forceStereo) rows.push({ label: "Force Stereo", value: "Yes" }); if (s.sceneChange !== undefined) rows.push({ label: "Scene Change", value: String(s.sceneChange) }); if (s.deinterlace) rows.push({ label: "Deinterlace", value: "Yes" }); if (s.denoise) rows.push({ label: "Denoise", value: "Yes" }); if (s.rotate && s.rotate !== "none") rows.push({ label: "Rotate", value: String(s.rotate) }); if (s.speed && Number(s.speed) !== 1) rows.push({ label: "Speed", value: `${s.speed}Γ—` }); if (s.brightness && Number(s.brightness) !== 0) rows.push({ label: "Brightness", value: String(s.brightness) }); if (s.contrast && Number(s.contrast) !== 1) rows.push({ label: "Contrast", value: String(s.contrast) }); if (s.saturation && Number(s.saturation) !== 1) rows.push({ label: "Saturation", value: String(s.saturation) }); if (s.stripSubtitles) rows.push({ label: "Strip Subtitles", value: "Yes" }); if (s.stripMetadata) rows.push({ label: "Strip Metadata", value: "Yes" }); if (s.subtitleFile) rows.push({ label: "Subtitle File", value: String(s.subtitleFile) }); if (s.subtitleLang) rows.push({ label: "Subtitle Language", value: String(s.subtitleLang) }); if (s.subtitleBurn) rows.push({ label: "Subtitle Burn-in", value: "Yes" }); if (s.startTime) rows.push({ label: "Start Time", value: String(s.startTime) }); if (s.endTime) rows.push({ label: "End Time", value: String(s.endTime) }); return rows.length > 0 ? ( <div className="space-y-1 mt-2"> {rows.map((r, i) => ( <div key={i} className="flex items-baseline justify-between gap-2 text-[11px]"> <span className="text-slate-500">{r.label}:</span> <span className="text-slate-700 font-medium">{r.value}</span> </div> ))} </div> ) : ( <p className="text-[10px] text-slate-400 mt-2">No settings available</p> ); })()} </div> )} </div> )} </div> )} </div> </div> </div> ); } function PreviewModal({ title, url, onClose }: { title: string; url: string; onClose: () => void }) { return ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={onClose}> <div className="w-full max-w-4xl rounded-3xl bg-slate-950 shadow-2xl overflow-hidden" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between gap-3 px-5 py-4 border-b border-slate-800 bg-slate-900"> <div className="min-w-0"> <p className="text-sm font-semibold text-white truncate">Preview: {title}</p> <p className="text-xs text-slate-400">Video playback uses the browser's media player.</p> </div> <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-800 hover:text-white transition-colors"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="bg-black p-4"> <video className="w-full max-h-[70vh] rounded-3xl bg-black" controls autoPlay playsInline src={url} /> <div className="mt-3 flex flex-wrap items-center justify-between gap-3 text-xs text-slate-400"> <p>If playback fails, open the file directly.</p> <a href={url} target="_blank" rel="noreferrer" className="rounded-full bg-slate-800 px-3 py-1 text-slate-200 hover:bg-slate-700 transition-colors">Open raw file</a> </div> </div> </div> </div> ); } // ─── Trim Modal ─────────────────────────────────────────────────────────────── function TrimModal({ file, onClose, onTrimStarted }: { file: FileEntry; onClose: () => void; onTrimStarted: () => void; }) { type TrimSegment = { id: string; start: string; end: string }; const [duration, setDuration] = useState<number | null>(null); const [segments, setSegments] = useState<TrimSegment[]>([{ id: `seg_${Math.random().toString(16).slice(2)}`, start: "00:00:00", end: "00:00:00" }]); const [activeSegmentId, setActiveSegmentId] = useState(segments[0].id); const [outName, setOutName] = useState(""); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); useEffect(() => { api.getFileInfo(file.id).then((res) => { if (res.ok && res.info.durationSeconds) { const d = res.info.durationSeconds; setDuration(d); const firstSegment = { id: `seg_${Math.random().toString(16).slice(2)}`, start: "00:00:00", end: secondsToHms(Math.floor(d)) }; setSegments([firstSegment]); setActiveSegmentId(firstSegment.id); } }).finally(() => setLoading(false)); const ext = file.name.match(/(\.[^.]+)$/)?.[1] || ""; const base = file.name.replace(/(\.[^.]+)$/, ""); setOutName(`${base}_trim${ext}`); }, [file]); useEffect(() => { if (!segments.length) { const id = `seg_${Math.random().toString(16).slice(2)}`; setSegments([{ id, start: "00:00:00", end: duration ? secondsToHms(Math.floor(duration)) : "00:00:00" }]); setActiveSegmentId(id); } else if (!segments.some((segment) => segment.id === activeSegmentId)) { setActiveSegmentId(segments[0].id); } }, [segments, activeSegmentId, duration]); const activeSegment = segments.find((segment) => segment.id === activeSegmentId) || segments[0]; const startSec = hmsToSeconds(activeSegment.start); const endSec = hmsToSeconds(activeSegment.end); const trimDuration = Math.max(0, endSec - startSec); const updateSegment = (id: string, field: "start" | "end", value: string) => { setSegments((prev) => prev.map((segment) => segment.id === id ? { ...segment, [field]: value } : segment)); }; const addSegment = () => { const id = `seg_${Math.random().toString(16).slice(2)}`; const lastEnd = segments.length ? hmsToSeconds(segments[segments.length - 1].end) : 0; const nextStart = duration ? Math.min(lastEnd, Math.floor(duration - 1)) : lastEnd; const nextEnd = duration ? secondsToHms(Math.floor(duration)) : "00:00:00"; const newSegment = { id, start: secondsToHms(nextStart), end: nextEnd }; setSegments((prev) => [...prev, newSegment]); setActiveSegmentId(id); }; const removeSegment = (id: string) => { setSegments((prev) => prev.filter((segment) => segment.id !== id)); }; const moveSegment = (idx: number, direction: -1 | 1) => { setSegments((prev) => { const next = [...prev]; const target = idx + direction; if (target < 0 || target >= next.length) return next; [next[idx], next[target]] = [next[target], next[idx]]; return next; }); }; const handleTrim = async () => { const normalized = segments.map((segment) => ({ startTime: hmsToSeconds(segment.start), endTime: hmsToSeconds(segment.end), })); for (const segment of normalized) { if (segment.endTime <= segment.startTime) { setError("Each segment needs an end time after its start time"); return; } if (duration && segment.endTime > duration) { setError("One or more segments exceed the file duration"); return; } } if (!outName.trim()) { setError("Output filename is required"); return; } setError(null); setBusy(true); try { await api.trimSegments(file.id, normalized, outName.trim()); onTrimStarted(); onClose(); } catch { setError("Failed to start trim job"); } finally { setBusy(false); } }; return ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 flex-shrink-0"> <div className="flex items-center gap-2 min-w-0"> <span className="text-lg flex-shrink-0">βœ‚οΈ</span> <div className="min-w-0"> <h2 className="text-sm font-bold text-slate-800 truncate">Trim & Merge segments</h2> <p className="text-[11px] text-slate-500 truncate">Create multiple ranges and merge them into one seamless file.</p> </div> </div> <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="flex-1 overflow-y-auto p-5 space-y-4"> {loading ? ( <div className="py-6 text-center text-sm text-slate-400">Loading file info…</div> ) : ( <> {duration && ( <div className="text-xs text-slate-500 bg-slate-50 rounded-lg px-3 py-2"> <span className="font-semibold">Total duration:</span> {secondsToHms(Math.floor(duration))} </div> )} <div className="space-y-3"> {segments.map((segment, idx) => { const segmentStart = hmsToSeconds(segment.start); const segmentEnd = hmsToSeconds(segment.end); const segmentLen = Math.max(0, segmentEnd - segmentStart); const isActive = segment.id === activeSegmentId; return ( <div key={segment.id} className={`rounded-2xl border px-4 py-3 ${isActive ? "border-violet-300 bg-violet-50" : "border-slate-200 bg-white"}`}> <div className="flex flex-wrap items-center gap-2"> <button type="button" onClick={() => setActiveSegmentId(segment.id)} className="text-[11px] font-semibold text-slate-600 hover:text-violet-600"> Segment {idx + 1} </button> <span className="text-[11px] text-slate-400">{segmentLen > 0 ? secondsToHms(Math.floor(segmentLen)) : "Empty"}</span> <div className="ml-auto flex items-center gap-1"> <button type="button" onClick={() => moveSegment(idx, -1)} disabled={idx === 0} className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" /> </svg> </button> <button type="button" onClick={() => moveSegment(idx, 1)} disabled={idx === segments.length - 1} className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" /> </svg> </button> {segments.length > 1 && ( <button type="button" onClick={() => removeSegment(segment.id)} className="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-600"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> )} </div> </div> <div className="mt-3 grid grid-cols-2 gap-3"> <div className="space-y-1"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Start</label> <TimePartsInput value={segment.start} maxSeconds={duration ?? undefined} onChange={(value) => updateSegment(segment.id, "start", value)} /> </div> <div className="space-y-1"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">End</label> <TimePartsInput value={segment.end} maxSeconds={duration ?? undefined} onChange={(value) => updateSegment(segment.id, "end", value)} /> </div> </div> </div> ); })} </div> <div className="flex items-center gap-2"> <button type="button" onClick={addSegment} className="rounded-full bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200"> + Add segment </button> <span className="text-xs text-slate-500">Use the segment list to trim multiple slices and merge them seamlessly.</span> </div> {duration && activeSegment && ( <div className="space-y-2"> <div className="grid grid-cols-2 gap-3"> <div> <div className="text-[11px] text-slate-500 uppercase tracking-wider">Start (drag)</div> <input type="range" min={0} max={Math.floor(duration)} step={1} value={startSec} onChange={(e) => updateSegment(activeSegment.id, "start", secondsToHms(Number(e.target.value)))} className="w-full accent-violet-600" /> </div> <div> <div className="text-[11px] text-slate-500 uppercase tracking-wider">End (drag)</div> <input type="range" min={0} max={Math.floor(duration)} step={1} value={endSec} onChange={(e) => updateSegment(activeSegment.id, "end", secondsToHms(Number(e.target.value)))} className="w-full accent-violet-600" /> </div> </div> <div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2"> Active segment: {secondsToHms(startSec)} β†’ {secondsToHms(endSec)} β€’ {trimDuration > 0 ? `Length ${secondsToHms(Math.floor(trimDuration))}` : "Empty range"} </div> </div> )} <div className="space-y-1"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Output Filename</label> <input type="text" value={outName} onChange={(e) => setOutName(e.target.value)} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> {error && <p className="text-xs text-red-500">{error}</p>} <div className="text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2"> πŸ’‘ Output saved to same folder as source. All segments are joined without pauses. </div> <button onClick={handleTrim} disabled={busy || !outName.trim()} className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50"> {busy ? "Starting Trim…" : segments.length > 1 ? "βœ‚οΈ Trim & Merge" : "βœ‚οΈ Trim"} </button> </> )} </div> </div> </div> ); } // ─── Download Job Progress Bar ──────────────────────────────────────────────── function DownloadProgress({ jobId, onDone }: { jobId: string; onDone: () => void }) { const [job, setJob] = useState<DownloadJob | null>(null); const doneRef = useRef(false); useEffect(() => { const poll = async () => { try { const res = await api.getDownloadJob(jobId); setJob(res.job); if (res.job.status !== "running") { if (!doneRef.current) { doneRef.current = true; onDone(); } } } catch { /* ignore */ } }; poll(); const iv = setInterval(poll, 600); return () => clearInterval(iv); }, [jobId, onDone]); if (!job) return null; const percent = job.totalBytes > 0 ? Math.min(100, (job.bytesDownloaded / job.totalBytes) * 100) : null; const isRunning = job.status === "running"; const statusColors: Record<string, string> = { running: "text-violet-600", done: "text-emerald-600", failed: "text-red-500", stopped: "text-slate-500", }; return ( <div className="rounded-xl border border-slate-200 bg-white p-4 space-y-2"> <div className="flex items-center justify-between gap-2"> <div className="min-w-0 flex-1"> <p className="text-xs font-semibold text-slate-700 truncate"> {job.filename ? `⬇ ${job.filename}` : "⬇ Downloading…"} </p> <p className="text-[10px] text-slate-400 truncate">{job.url}</p> </div> <div className="flex items-center gap-2 flex-shrink-0"> <span className={`text-xs font-semibold capitalize ${statusColors[job.status] ?? "text-slate-500"}`}>{job.status}</span> {isRunning && ( <button onClick={() => api.stopDownloadJob(jobId)} className="rounded-lg bg-red-50 border border-red-200 px-2 py-1 text-xs font-semibold text-red-600 hover:bg-red-100 transition-colors"> β–  Stop </button> )} </div> </div> <div className="space-y-1"> <div className="relative h-2 w-full overflow-hidden rounded-full bg-slate-100"> {percent !== null ? ( <div className={`h-full rounded-full transition-all duration-300 ${ job.status === "done" ? "bg-emerald-500" : job.status === "failed" ? "bg-red-400" : job.status === "stopped" ? "bg-slate-400" : "bg-violet-500" }`} style={{ width: `${percent}%` }} /> ) : isRunning ? ( <div className="h-full w-1/3 rounded-full bg-violet-500 animate-[slide_1.2s_ease-in-out_infinite]" /> ) : ( <div className={`h-full w-full rounded-full ${job.status === "done" ? "bg-emerald-500" : "bg-slate-300"}`} /> )} </div> <div className="flex justify-between text-[10px] text-slate-400"> <span>{fmt(job.bytesDownloaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""}</span> {percent !== null && <span>{percent.toFixed(1)}%</span>} {job.error && <span className="text-red-500">{job.error}</span>} </div> </div> </div> ); } // ─── Batch Action Bar ───────────────────────────────────────────────────────── function BatchBar({ selected, files, onClear, onRefresh, onEncodeFiles, onMergeFiles, onMoveFiles, setToast }: { selected: Set<string>; files: FileEntry[]; onClear: () => void; onRefresh: () => void; onEncodeFiles: (files: FileEntry[]) => void; onMergeFiles: (files: FileEntry[]) => void; onMoveFiles: (files: FileEntry[]) => void; setToast: (msg: string) => void; }) { const [busy, setBusy] = useState<string | null>(null); const [pdJobIds, setPdJobIds] = useState<string[]>([]); const [zipping, setZipping] = useState(false); const selectedFiles = files.filter((f) => selected.has(f.id)); const mediaFiles = selectedFiles.filter((f) => isMediaFile(f.name)); const downloadableMediaFiles = mediaFiles.filter((f) => f.source === "downloaded"); const handleBatchDelete = async () => { if (!confirm(`Delete ${selected.size} file(s)?`)) return; setBusy("delete"); try { await api.batchDelete([...selected]); onClear(); onRefresh(); setToast(`πŸ—‘ Deleted ${selected.size} file(s)`); } finally { setBusy(null); } }; const handleBatchDownload = () => { for (const f of selectedFiles) { const a = document.createElement("a"); a.href = `/api/files/${encodeURIComponent(f.id)}/download`; a.download = f.name; document.body.appendChild(a); a.click(); document.body.removeChild(a); } setToast(`⬇ Downloading ${selectedFiles.length} file(s)…`); }; const handleBatchEncode = () => { if (!downloadableMediaFiles.length) { setToast("⚠️ Select downloaded media files to encode"); return; } onEncodeFiles(downloadableMediaFiles); onClear(); }; const handleBatchPixeldrain = async () => { setBusy("pixeldrain"); try { const { jobIds } = await api.batchPixeldrain([...selected]); setPdJobIds((prev) => [...prev, ...jobIds]); setToast(`☁️ Uploading ${jobIds.length} file(s) to Pixeldrain…`); onClear(); } finally { setBusy(null); } }; const handleBatchMerge = () => { if (mediaFiles.length < 2) { setToast("⚠️ Select at least 2 media files to merge"); return; } const sorted = [...mediaFiles].sort((a, b) => a.createdAt - b.createdAt); onMergeFiles(sorted); }; const handleBatchZip = async () => { if (selected.size < 2) { setToast("⚠️ Select at least 2 files to zip"); return; } setZipping(true); try { const res = await api.batchZip([...selected]); if (res.error) { setToast(`❌ ${res.error}`); } else { setToast(`πŸ“¦ Created ${res.filename} with ${res.fileCount} files`); onClear(); onRefresh(); } } catch { setToast("❌ Failed to create zip"); } finally { setZipping(false); } }; return ( <div className="space-y-2"> {pdJobIds.map((jid) => ( <PixeldrainProgress key={jid} jobId={jid} onClose={() => setPdJobIds((p) => p.filter((x) => x !== jid))} /> ))} <div className="sticky top-[61px] z-10 grid gap-3 rounded-xl border border-violet-200 bg-violet-50 px-4 py-3 shadow-sm"> <div className="flex flex-wrap items-center gap-2"> <span className="flex h-6 w-6 items-center justify-center rounded-full bg-violet-600 text-[11px] font-bold text-white flex-shrink-0"> {selected.size} </span> <span className="text-sm font-semibold text-violet-800">selected</span> <button onClick={onClear} className="rounded-full p-0.5 text-violet-400 hover:text-violet-700 hover:bg-violet-100 transition-colors" title="Clear selection"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3"> <div className="flex flex-wrap items-center gap-2"> <button onClick={handleBatchEncode} disabled={!!busy || downloadableMediaFiles.length === 0} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-violet-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors whitespace-nowrap"> 🎬 Encode{downloadableMediaFiles.length > 0 ? ` (${downloadableMediaFiles.length})` : ""} </button> <button onClick={handleBatchDownload} disabled={!!busy} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-sky-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-sky-600 disabled:opacity-50 transition-colors whitespace-nowrap"> ⬇ Download{selected.size > 0 ? ` (${selected.size})` : ""} </button> <button onClick={() => onMoveFiles(selectedFiles)} disabled={!!busy || selectedFiles.length === 0} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-amber-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-amber-600 disabled:opacity-50 transition-colors whitespace-nowrap"> β†— Move{selectedFiles.length > 0 ? ` (${selectedFiles.length})` : ""} </button> </div> <div className="flex flex-wrap items-center gap-2"> <button onClick={handleBatchPixeldrain} disabled={!!busy} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-emerald-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-600 disabled:opacity-50 transition-colors whitespace-nowrap"> ☁️ Pixeldrain{selected.size > 0 ? ` (${selected.size})` : ""} </button> <button onClick={handleBatchMerge} disabled={!!busy || mediaFiles.length < 2} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-indigo-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-indigo-600 disabled:opacity-50 transition-colors whitespace-nowrap"> πŸ”— Merge{mediaFiles.length >= 2 ? ` (${mediaFiles.length})` : ""} </button> <button onClick={handleBatchZip} disabled={!!busy || zipping || selected.size < 2} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-teal-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-teal-600 disabled:opacity-50 transition-colors whitespace-nowrap"> {zipping ? ( <> <svg className="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> Zipping… </> ) : ( <>πŸ“¦ Zip{selected.size > 0 ? ` (${selected.size})` : ""}</> )} </button> </div> <div className="flex flex-wrap items-center gap-2"> <button onClick={handleBatchDelete} disabled={!!busy} className="min-w-[10rem] flex items-center gap-1.5 rounded-lg bg-red-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-600 disabled:opacity-50 transition-colors whitespace-nowrap"> πŸ—‘ Delete{selected.size > 0 ? ` (${selected.size})` : ""} </button> </div> </div> </div> </div> ); } // ─── Upload Progress Panel ──────────────────────────────────────────────────── interface UploadFileProgress { name: string; size: number; loaded: number; done: boolean; } interface UploadSession { files: UploadFileProgress[]; totalBytes: number; loadedBytes: number; startTime: number; speed: number; eta: number; done: boolean; } function UploadProgressPanel({ session, visible, onToggle, onDismiss }: { session: UploadSession; visible: boolean; onToggle: () => void; onDismiss: () => void; }) { const overallPct = session.totalBytes > 0 ? Math.min(100, (session.loadedBytes / session.totalBytes) * 100) : 0; return ( <div className={`rounded-xl border overflow-hidden transition-all ${ session.done ? "border-emerald-200 bg-emerald-50" : "border-violet-200 bg-violet-50" }`}> <div className="flex items-center gap-3 px-4 py-2.5"> <div className="flex-1 min-w-0"> <div className="flex items-center justify-between mb-1"> <span className={`text-xs font-semibold ${session.done ? "text-emerald-700" : "text-violet-700"}`}> {session.done ? `βœ“ Upload complete β€” ${session.files.length} file${session.files.length !== 1 ? "s" : ""}` : `Uploading ${session.files.length} file${session.files.length !== 1 ? "s" : ""}…`} </span> <div className="flex items-center gap-2 flex-shrink-0"> {!session.done && ( <span className="text-[10px] font-mono text-violet-600">{overallPct.toFixed(0)}%</span> )} <button onClick={onToggle} className={`text-[10px] font-semibold px-2 py-0.5 rounded-full transition-colors ${ session.done ? "bg-emerald-100 text-emerald-700 hover:bg-emerald-200" : "bg-violet-100 text-violet-700 hover:bg-violet-200" }`}> {visible ? "Hide" : "Show"} details </button> {session.done && ( <button onClick={onDismiss} className="text-emerald-400 hover:text-emerald-600 transition-colors"> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> )} </div> </div> <div className="relative h-1.5 w-full overflow-hidden rounded-full bg-white/60"> <div className={`h-full rounded-full transition-all duration-200 ${ session.done ? "bg-emerald-500" : "bg-violet-500" }`} style={{ width: `${overallPct}%` }} /> </div> {!session.done && ( <div className="flex justify-between mt-0.5 text-[10px] text-violet-500"> <span>{fmt(session.loadedBytes)} / {fmt(session.totalBytes)}</span> <span className="font-mono"> {session.speed > 0 ? `${fmt(session.speed)}/s` : ""} {session.eta > 0 && session.speed > 0 ? ` Β· ETA ${fmtEta(session.eta)}` : ""} </span> </div> )} </div> </div> {visible && ( <div className="border-t border-white/40 bg-white/60 divide-y divide-slate-100"> {session.files.map((f, i) => { const pct = f.size > 0 ? Math.min(100, (f.loaded / f.size) * 100) : (f.done ? 100 : 0); return ( <div key={i} className="px-4 py-2 space-y-1"> <div className="flex items-center justify-between gap-2"> <span className="text-xs text-slate-700 truncate flex-1" title={f.name}> {f.done ? "βœ“ " : ""}{f.name} </span> <span className="text-[10px] text-slate-400 flex-shrink-0 font-mono"> {f.done ? fmt(f.size) : `${fmt(f.loaded)} / ${fmt(f.size)}`} </span> </div> <div className="relative h-1 w-full overflow-hidden rounded-full bg-slate-100"> <div className={`h-full rounded-full transition-all duration-200 ${ f.done ? "bg-emerald-400" : "bg-violet-400" }`} style={{ width: `${pct}%` }} /> </div> </div> ); })} </div> )} </div> ); } // ─── Upload Area ────────────────────────────────────────────────────────────── function UploadArea({ onUploaded }: { onUploaded: () => void }) { const [dragging, setDragging] = useState(false); const [urlVal, setUrlVal] = useState(""); const [urlUser, setUrlUser] = useState(""); const [urlPass, setUrlPass] = useState(""); const [activeDownloadJobs, setActiveDownloadJobs] = useState<string[]>([]); const [uploadSession, setUploadSession] = useState<UploadSession | null>(null); const [showUploadDetail, setShowUploadDetail] = useState(false); const fileInputRef = useRef<HTMLInputElement>(null); const folderInputRef = useRef<HTMLInputElement>(null); const handleFiles = useCallback(async (fileList: FileList | File[]) => { const arr = Array.from(fileList); if (!arr.length) return; const folderPaths = arr.map((f) => { const rel = (f as File & { webkitRelativePath?: string }).webkitRelativePath || ""; if (!rel) return ""; const parts = rel.split("/"); if (parts.length > 1) return parts.slice(0, -1).join("/"); return ""; }); const totalBytes = arr.reduce((s, f) => s + f.size, 0); const fileProgress: UploadFileProgress[] = arr.map((f) => ({ name: f.name, size: f.size, loaded: 0, done: false, })); const session: UploadSession = { files: fileProgress, totalBytes, loadedBytes: 0, startTime: Date.now(), speed: 0, eta: 0, done: false, }; setUploadSession({ ...session }); setShowUploadDetail(false); await new Promise<void>((resolve, reject) => { const fd = new FormData(); arr.forEach((f, i) => { fd.append("files", f); if (folderPaths[i]) fd.append(`folderPath_${i}`, folderPaths[i]); }); const xhr = new XMLHttpRequest(); xhr.open("POST", "/api/files/upload"); xhr.upload.onprogress = (e) => { if (!e.lengthComputable) return; const loaded = e.loaded; const elapsed = (Date.now() - session.startTime) / 1000; const speed = elapsed > 0 ? loaded / elapsed : 0; const remaining = speed > 0 ? (totalBytes - loaded) / speed : 0; let remaining2 = loaded; const updatedFiles = fileProgress.map((fp) => { const take = Math.min(fp.size, remaining2); remaining2 -= take; return { ...fp, loaded: take, done: take >= fp.size }; }); setUploadSession({ files: updatedFiles, totalBytes, loadedBytes: loaded, startTime: session.startTime, speed, eta: remaining, done: false, }); }; xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { setUploadSession((prev) => prev ? { ...prev, loadedBytes: totalBytes, files: prev.files.map((f) => ({ ...f, loaded: f.size, done: true })), speed: 0, eta: 0, done: true, } : null); onUploaded(); resolve(); } else { reject(new Error(`Upload failed: ${xhr.status}`)); } }; xhr.onerror = () => reject(new Error("Network error")); xhr.send(fd); }).catch(() => { setUploadSession(null); }); }, [onUploaded]); const onDrop = (e: React.DragEvent) => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files); }; const handleUrlDownload = async () => { if (!urlVal.trim()) return; try { const { jobId } = await api.startDownloadUrl(urlVal.trim(), urlUser || undefined, urlPass || undefined); setActiveDownloadJobs((prev) => [...prev, jobId]); setUrlVal(""); setUrlUser(""); setUrlPass(""); } catch { /* ignore */ } }; const handleJobDone = useCallback(() => { onUploaded(); }, [onUploaded]); const isUploading = uploadSession !== null && !uploadSession.done; return ( <div className="space-y-3"> <input ref={fileInputRef} type="file" multiple className="hidden" onChange={(e) => e.target.files && handleFiles(e.target.files)} /> <input ref={folderInputRef} type="file" className="hidden" {...{ webkitdirectory: "true", mozdirectory: "true" } as React.InputHTMLAttributes<HTMLInputElement>} onChange={(e) => e.target.files && handleFiles(e.target.files)} /> <div onDragOver={(e) => { e.preventDefault(); setDragging(true); }} onDragLeave={() => setDragging(false)} onDrop={onDrop} className={`flex flex-col items-center justify-center rounded-xl border-2 border-dashed px-6 py-6 transition-colors ${ dragging ? "border-violet-400 bg-violet-50" : "border-slate-300 bg-slate-50" }`}> <svg className="mb-3 h-8 w-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" /> </svg> <p className="text-sm font-medium text-slate-600 mb-3">Drop files or folders here, or use buttons below</p> <div className="flex gap-3"> <button onClick={() => fileInputRef.current?.click()} disabled={isUploading} className="flex items-center gap-2 rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m6.75 12-3-3m0 0-3 3m3-3v6m-1.5-15H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" /> </svg> Upload Files </button> <button onClick={() => folderInputRef.current?.click()} disabled={isUploading} className="flex items-center gap-2 rounded-lg border border-violet-300 bg-white px-4 py-2 text-sm font-semibold text-violet-700 hover:bg-violet-50 disabled:opacity-50 transition-colors"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 0 0-1.883 2.542l.857 6a2.25 2.25 0 0 0 2.227 1.932H19.05a2.25 2.25 0 0 0 2.227-1.932l.857-6a2.25 2.25 0 0 0-1.883-2.542m-16.5 0V6A2.25 2.25 0 0 1 6 3.75h3.879a1.5 1.5 0 0 1 1.06.44l2.122 2.12a1.5 1.5 0 0 0 1.06.44H18A2.25 2.25 0 0 1 20.25 9v.776" /> </svg> Upload Folder </button> </div> </div> {uploadSession && ( <UploadProgressPanel session={uploadSession} visible={showUploadDetail} onToggle={() => setShowUploadDetail((v) => !v)} onDismiss={() => { setUploadSession(null); setShowUploadDetail(false); }} /> )} {activeDownloadJobs.length > 0 && ( <div className="space-y-2"> {activeDownloadJobs.map((id) => ( <DownloadProgress key={id} jobId={id} onDone={handleJobDone} /> ))} </div> )} <details className="rounded-xl border border-slate-200 bg-white"> <summary className="cursor-pointer select-none px-4 py-3 text-sm font-medium text-slate-700 hover:text-violet-700"> Download from URL </summary> <div className="space-y-2 border-t border-slate-100 p-4"> <input type="url" placeholder="https://example.com/video.mp4" value={urlVal} onChange={(e) => setUrlVal(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleUrlDownload()} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> <div className="flex gap-2"> <input type="text" placeholder="Username (optional)" value={urlUser} onChange={(e) => setUrlUser(e.target.value)} className="flex-1 rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="password" placeholder="Password (optional)" value={urlPass} onChange={(e) => setUrlPass(e.target.value)} className="flex-1 rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> <button onClick={handleUrlDownload} disabled={!urlVal.trim()} className="rounded-lg bg-violet-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-violet-700 disabled:opacity-50"> Download </button> </div> </details> </div> ); } // ─── Folder Row with actions ────────────────────────────────────────────────── function FolderRow({ folder, fileCount, isOpen, onToggle, onRename, onDelete, onDownloadZip, onCopyZipLink, onUploadZip }: { folder: string; fileCount: number; isOpen: boolean; onToggle: () => void; onRename: () => void; onDelete: () => void; onDownloadZip: () => void; onCopyZipLink: () => void; onUploadZip: () => void; }) { return ( <div className="flex items-center gap-1 px-3 py-2 bg-amber-50 hover:bg-amber-100/60 transition-colors border-b border-amber-100"> {/* Expand toggle */} <button onClick={onToggle} className="flex items-center gap-2 flex-1 min-w-0 text-left"> <svg className={`h-3.5 w-3.5 flex-shrink-0 text-slate-400 transition-transform ${isOpen ? "rotate-90" : ""}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" /> </svg> <svg className="h-4 w-4 flex-shrink-0 text-amber-500" fill="currentColor" viewBox="0 0 24 24"> <path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" /> </svg> <span className="flex-1 text-sm font-semibold text-slate-700 truncate">{folder}</span> <span className="text-xs text-slate-400 flex-shrink-0 mr-2">{fileCount} file{fileCount !== 1 ? "s" : ""}</span> </button> {/* Folder action buttons */} <div className="flex items-center gap-0.5 flex-shrink-0"> <IconBtn title="Rename folder" onClick={onRename}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125" /> </svg> </IconBtn> <IconBtn title="Download folder as ZIP" onClick={onDownloadZip}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" /> </svg> </IconBtn> <IconBtn title="Copy ZIP download link" onClick={onCopyZipLink}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244" /> </svg> </IconBtn> <IconBtn title="Upload ZIP into folder" onClick={onUploadZip}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" /> </svg> </IconBtn> <IconBtn title="Delete folder and all files" onClick={onDelete} danger> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /> </svg> </IconBtn> </div> </div> ); } // ─── File Row ───────────────────────────────────────────────────────────────── function FileRow({ f, selected, onToggle, onInfo, onShowSettings, onTrim, onEncode, onUnzip, onPixeldrain, onCopyLink, onPlay, onRename, onMove, onDelete, infoFileId, trimFileId, unzipping, allFolders }: { f: FileEntry; selected: boolean; onToggle: () => void; onInfo: () => void; onShowSettings: () => void; onTrim: () => void; onEncode: () => void; onUnzip: () => void; onPixeldrain: () => void; onCopyLink: () => void; onPlay?: () => void; onRename: () => void; onMove: () => void; onDelete: () => void; infoFileId: string | null; trimFileId: string | null; unzipping: boolean; allFolders: string[]; }) { const media = isMediaFile(f.name); const archive = isArchiveFile(f.name); const fileIcon = archive ? "πŸ“¦" : media ? (f.source === "encoded" ? "🎬" : "🎞") : "πŸ“„"; return ( <div className={`flex items-center gap-2 px-4 py-2.5 transition-colors ${selected ? "bg-violet-50" : "hover:bg-slate-50/60"}`}> <input type="checkbox" className="h-4 w-4 accent-violet-600 rounded flex-shrink-0 cursor-pointer" checked={selected} onChange={onToggle} onClick={(e) => e.stopPropagation()} /> <span className="flex-shrink-0 text-base">{fileIcon}</span> <div className="flex-1 min-w-0"> <p className="truncate text-sm font-medium text-slate-800" title={f.name}>{f.name}</p> <p className="mt-0.5 text-xs text-slate-400">{fmt(f.sizeBytes)}</p> </div> <Badge color={f.source === "encoded" ? "bg-emerald-100 text-emerald-700" : "bg-sky-100 text-sky-700"}> {f.source} </Badge> <div className="flex items-center gap-0.5 flex-shrink-0 flex-wrap"> {/* Info β€” show for all files */} <IconBtn title="File info" onClick={onInfo} active={infoFileId === f.id}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z" /> </svg> </IconBtn> {f.source === "encoded" && ( <IconBtn title="Show encoding settings" onClick={onShowSettings} active={infoFileId === f.id}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M9.75 3v1.5m4.5-1.5V4.5m-8.25 3h12.75a2.25 2.25 0 0 1 2.25 2.25v9A2.25 2.25 0 0 1 18.75 21H5.25A2.25 2.25 0 0 1 3 18.75v-9A2.25 2.25 0 0 1 5.25 7.5ZM9 12h6m-6 3h6" /> </svg> </IconBtn> )} {/* Unzip β€” only for archive files */} {archive && ( <IconBtn title={unzipping ? "Unzipping…" : "Unzip archive"} onClick={onUnzip} disabled={unzipping}> {unzipping ? ( <svg className="animate-spin h-3.5 w-3.5" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> ) : ( <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m8.25 3v6.75m0 0l-3-3m3 3l3-3M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" /> </svg> )} </IconBtn> )} {/* Preview β€” only for media files */} {media && onPlay && ( <IconBtn title={f.source === "downloaded" ? "Preview downloaded file" : "Preview encoded file"} onClick={onPlay}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" /> </svg> </IconBtn> )} {media && ( <IconBtn title="Trim" onClick={onTrim} active={trimFileId === f.id}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M7.848 8.25l1.536.887M7.848 8.25a3 3 0 1 1-5.196-3 3 3 0 0 1 5.196 3Zm1.536.887a2.165 2.165 0 0 1 1.083 1.839c.005.351.054.695.14 1.024M9.384 9.137l2.077 1.199M7.848 15.75l1.536-.887m-1.536.887a3 3 0 1 1-5.196 3 3 3 0 0 1 5.196-3Zm1.536-.887a2.165 2.165 0 0 1 1.083-1.838c.05-.18.09-.366.12-.556m-1.203 2.394 2.077-1.199m0-3.328a4.323 4.323 0 0 1 2.068-1.379l5.325-1.628a4.5 4.5 0 0 1 2.48-.044l.803.215-7.794 4.5m-2.882-1.664A4.331 4.331 0 0 0 10.607 12m3.736 0 7.794 4.5-.802.215a4.5 4.5 0 0 1-2.48-.043l-5.326-1.629a4.324 4.324 0 0 1-2.068-1.379M14.343 12l-2.882 1.664" /> </svg> </IconBtn> )} {/* Encode β€” only for downloaded media files */} {media && f.source === "downloaded" && ( <IconBtn title="Use for encode" onClick={onEncode}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" /> </svg> </IconBtn> )} <IconBtn title="Upload to Pixeldrain" onClick={onPixeldrain}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.338-2.32 3.75 3.75 0 0 1 3.827 6.097l-.141-.097" /> </svg> </IconBtn> <IconBtn title="Copy download link" onClick={onCopyLink}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244" /> </svg> </IconBtn> <IconBtn title="Rename" onClick={onRename}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125" /> </svg> </IconBtn> {allFolders.length > 0 && ( <IconBtn title="Move to folder" onClick={onMove}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 0 0-1.883 2.542l.857 6a2.25 2.25 0 0 0 2.227 1.932H19.05a2.25 2.25 0 0 0 2.227-1.932l.857-6a2.25 2.25 0 0 0-1.883-2.542m-16.5 0V6A2.25 2.25 0 0 1 6 3.75h3.879a1.5 1.5 0 0 1 1.06.44l2.122 2.12a1.5 1.5 0 0 0 1.06.44H18A2.25 2.25 0 0 1 20.25 9v.776" /> </svg> </IconBtn> )} <a href={`/api/files/${encodeURIComponent(f.id)}/download`} title="Download file" className="rounded p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600"> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" /> </svg> </a> <IconBtn title="Delete" onClick={onDelete} danger> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /> </svg> </IconBtn> </div> </div> ); } // ─── File List ──────────────────────────────────────────────────────────────── function FileList({ files, folders, onRefresh, onSelectForEncode, onJobStarted, onBatchEncode, openFolders, onToggleFolder }: { files: FileEntry[]; folders: string[]; onRefresh: () => void; onSelectForEncode: (f: FileEntry) => void; onJobStarted: () => void; onBatchEncode: (files: FileEntry[]) => void; openFolders: Set<string>; onToggleFolder: (folder: string) => void; }) { const [selected, setSelected] = useState<Set<string>>(new Set()); const [renamingId, setRenamingId] = useState<string | null>(null); const [renameVal, setRenameVal] = useState(""); const [renamingFolder, setRenamingFolder] = useState<string | null>(null); const [renameFolderVal, setRenameFolderVal] = useState(""); const [infoFile, setInfoFile] = useState<FileEntry | null>(null); const [infoShowEncode, setInfoShowEncode] = useState(false); const [trimFile, setTrimFile] = useState<FileEntry | null>(null); const [moveFiles, setMoveFiles] = useState<FileEntry[] | null>(null); const [toast, setToast] = useState<string | null>(null); const [previewFile, setPreviewFile] = useState<FileEntry | null>(null); const [pdJobs, setPdJobs] = useState<Record<string, string>>({}); const [mergeFiles, setMergeFiles] = useState<FileEntry[] | null>(null); const [unzippingId, setUnzippingId] = useState<string | null>(null); const zipInputRef = useRef<HTMLInputElement>(null); const zipFolderRef = useRef<string | null>(null); useEffect(() => { setSelected(new Set()); }, [files]); const toggleSelect = (id: string) => { setSelected((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; const selectAll = () => setSelected(new Set(files.map((f) => f.id))); const clearSelection = () => setSelected(new Set()); const allSelected = files.length > 0 && selected.size === files.length; const someSelected = selected.size > 0 && !allSelected; const startRename = (f: FileEntry) => { setRenamingId(f.id); setRenameVal(f.name); }; const commitRename = async (f: FileEntry) => { if (renameVal.trim() && renameVal !== f.name) { await api.renameFile(f.id, renameVal.trim()); onRefresh(); } setRenamingId(null); }; const handleDelete = async (f: FileEntry) => { if (!confirm(`Delete "${f.name}"?`)) return; await api.deleteFile(f.id); onRefresh(); }; const handleCopyLink = (f: FileEntry) => { const url = `${window.location.origin}/api/files/${encodeURIComponent(f.id)}/download`; navigator.clipboard.writeText(url).then(() => setToast("πŸ“‹ Download link copied!")); }; const handlePixeldrain = async (f: FileEntry) => { try { const { jobId } = await api.uploadToPixeldrain(f.id); setPdJobs((prev) => ({ ...prev, [f.id]: jobId })); } catch { setToast("Failed to start Pixeldrain upload"); } }; // Folder actions const handleFolderRename = async (folder: string) => { const newName = renameFolderVal.trim(); if (!newName || newName === folder) { setRenamingFolder(null); return; } const res = await api.renameFolder(folder, newName); if (res.error) { setToast(`Error: ${res.error}`); } else { onRefresh(); } setRenamingFolder(null); }; const handleFolderDelete = async (folder: string) => { if (!confirm(`Delete folder "${folder}" and ALL files inside it?`)) return; const res = await api.deleteFolder(folder); if (res.error) { setToast(`Error: ${res.error}`); } else { onRefresh(); } }; const handleFolderDownloadZip = (folder: string) => { const url = `/api/folders/zip?folder=${encodeURIComponent(folder)}`; const a = document.createElement("a"); a.href = url; a.download = `${folder.replace(/\//g, "_")}.zip`; document.body.appendChild(a); a.click(); document.body.removeChild(a); }; const handleFolderCopyZipLink = (folder: string) => { const url = `${window.location.origin}/api/folders/zip?folder=${encodeURIComponent(folder)}`; navigator.clipboard.writeText(url).then(() => setToast("πŸ“‹ ZIP link copied!")); }; const handleFolderUploadZip = (folder: string) => { zipFolderRef.current = folder; zipInputRef.current?.click(); }; const handleZipFileSelected = async (e: React.ChangeEvent<HTMLInputElement>) => { const file = e.target.files?.[0]; const folder = zipFolderRef.current; if (!file || !folder) return; const fd = new FormData(); fd.append("zip", file); fd.append("folderPath", folder); try { const r = await fetch("/api/folders/upload-zip", { method: "POST", body: fd }); const data = await r.json(); if (data.error) { setToast(`Error: ${data.error}`); } else { setToast("βœ“ ZIP extracted!"); onRefresh(); } } catch { setToast("Failed to upload ZIP"); } if (zipInputRef.current) zipInputRef.current.value = ""; zipFolderRef.current = null; }; // Group files by folder const folderMap = new Map<string, FileEntry[]>(); for (const folder of folders) { if (!folderMap.has(folder)) folderMap.set(folder, []); } for (const f of files) { const key = f.folder || "/"; if (!folderMap.has(key)) folderMap.set(key, []); folderMap.get(key)!.push(f); } const sortedFolders = Array.from(folderMap.keys()).sort((a, b) => { if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b); }); const subfolders = sortedFolders.filter((f) => f !== "/"); const allFolders = subfolders; // for move modal if (!files.length) { return ( <div className="rounded-xl border border-dashed border-slate-200 py-10 text-center text-sm text-slate-400"> No files yet </div> ); } return ( <> <input ref={zipInputRef} type="file" accept=".zip" className="hidden" onChange={handleZipFileSelected} /> {toast && <Toast message={toast} onDone={() => setToast(null)} />} {infoFile && <InfoModal file={infoFile} onClose={() => setInfoFile(null)} initialShowEncode={infoShowEncode} />} {trimFile && ( <TrimModal file={trimFile} onClose={() => setTrimFile(null)} onTrimStarted={() => { onRefresh(); onJobStarted(); }} /> )} {mergeFiles && ( <MergeModal files={mergeFiles} onClose={() => setMergeFiles(null)} onMergeStarted={() => { setMergeFiles(null); onJobStarted(); }} /> )} {moveFiles && ( <MoveModal files={moveFiles} folders={allFolders} onClose={() => setMoveFiles(null)} onMoved={() => { onRefresh(); setMoveFiles(null); }} /> )} {Object.entries(pdJobs).length > 0 && ( <div className="space-y-2 mb-2"> {Object.entries(pdJobs).map(([fileId, jobId]) => ( <PixeldrainProgress key={jobId} jobId={jobId} onClose={() => setPdJobs((prev) => { const n = { ...prev }; delete n[fileId]; return n; }) } /> ))} </div> )} {previewFile && ( <PreviewModal title={previewFile.name} url={`/api/files/${encodeURIComponent(previewFile.id)}/download`} onClose={() => setPreviewFile(null)} /> )} {selected.size > 0 && ( <BatchBar selected={selected} files={files} onClear={clearSelection} onRefresh={onRefresh} onEncodeFiles={onBatchEncode} onMergeFiles={(f) => { setMergeFiles(f); clearSelection(); }} onMoveFiles={(items) => { setMoveFiles(items); clearSelection(); }} setToast={setToast} /> )} {/* Select all header */} <div className="flex items-center gap-2 px-4 py-2 rounded-t-xl border border-b-0 border-slate-200 bg-slate-50"> <input type="checkbox" className="h-4 w-4 accent-violet-600 rounded cursor-pointer" checked={allSelected} ref={(el) => { if (el) el.indeterminate = someSelected; }} onChange={() => allSelected ? clearSelection() : selectAll()} title={allSelected ? "Deselect all" : "Select all"} /> <span className="text-xs text-slate-500 select-none"> {selected.size === 0 ? `${files.length} file${files.length !== 1 ? "s" : ""}` : `${selected.size} / ${files.length} selected`} </span> {selected.size > 0 && ( <button onClick={clearSelection} className="ml-auto text-xs text-violet-600 hover:underline">Clear</button> )} </div> {/* Folder tree */} <div className="rounded-b-xl border border-slate-200 bg-white overflow-hidden"> {sortedFolders.map((folder, folderIdx) => { const folderFiles = folderMap.get(folder)!; const isRoot = folder === "/"; const isOpen = isRoot || openFolders.has(folder); return ( <div key={folder} className={folderIdx > 0 ? "border-t border-slate-100" : ""}> {/* Folder header row with actions */} {!isRoot && ( renamingFolder === folder ? ( <div className="flex items-center gap-2 px-4 py-2 bg-amber-50 border-b border-amber-100"> <svg className="h-4 w-4 flex-shrink-0 text-amber-500" fill="currentColor" viewBox="0 0 24 24"> <path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" /> </svg> <input autoFocus value={renameFolderVal} onChange={(e) => setRenameFolderVal(e.target.value)} onBlur={() => handleFolderRename(folder)} onKeyDown={(e) => { if (e.key === "Enter") handleFolderRename(folder); if (e.key === "Escape") setRenamingFolder(null); }} className="flex-1 rounded border border-amber-400 px-2 py-0.5 text-sm focus:outline-none focus:ring-2 focus:ring-amber-100" /> </div> ) : ( <FolderRow folder={folder} fileCount={folderFiles.length} isOpen={openFolders.has(folder)} onToggle={() => onToggleFolder(folder)} onRename={() => { setRenamingFolder(folder); setRenameFolderVal(folder); }} onDelete={() => handleFolderDelete(folder)} onDownloadZip={() => handleFolderDownloadZip(folder)} onCopyZipLink={() => handleFolderCopyZipLink(folder)} onUploadZip={() => handleFolderUploadZip(folder)} /> ) )} {/* Root label */} {isRoot && sortedFolders.length > 1 && ( <div className="flex items-center gap-2 px-4 py-2 bg-slate-50 border-b border-slate-100"> <svg className="h-4 w-4 flex-shrink-0 text-slate-400" fill="currentColor" viewBox="0 0 24 24"> <path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" /> </svg> <span className="text-xs font-semibold text-slate-500">/ root</span> <span className="text-xs text-slate-400 ml-auto">{folderFiles.length} file{folderFiles.length !== 1 ? "s" : ""}</span> </div> )} {/* Files */} {isOpen && ( <div className={`divide-y divide-slate-100 ${!isRoot ? "border-t border-slate-100" : ""}`}> {folderFiles.map((f) => ( <div key={f.id}> {renamingId === f.id ? ( <div className="flex items-center gap-3 px-4 py-3 bg-violet-50"> <input autoFocus value={renameVal} onChange={(e) => setRenameVal(e.target.value)} onBlur={() => commitRename(f)} onKeyDown={(e) => { if (e.key === "Enter") commitRename(f); if (e.key === "Escape") setRenamingId(null); }} className="flex-1 rounded border border-violet-400 px-2 py-0.5 text-sm focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> ) : ( <FileRow f={f} selected={selected.has(f.id)} onToggle={() => toggleSelect(f.id)} onInfo={() => { setInfoFile(f); setInfoShowEncode(false); }} onShowSettings={() => { setInfoFile(f); setInfoShowEncode(true); }} onTrim={() => setTrimFile(f)} onEncode={() => onSelectForEncode(f)} onUnzip={async () => { setUnzippingId(f.id); try { const res = await api.unzipFile(f.id); if (res.error) { setToast(`❌ ${res.error}`); } else { setToast(`πŸ“¦ Extracted to ${res.outputFolder || "folder"}/ (${res.fileCount ?? 0} files)`); onRefresh(); if (res.outputFolder) onToggleFolder(res.outputFolder); } } catch { setToast("❌ Unzip failed"); } finally { setUnzippingId(null); } }} unzipping={unzippingId === f.id} onPixeldrain={() => handlePixeldrain(f)} onCopyLink={() => handleCopyLink(f)} onPlay={() => setPreviewFile(f)} onRename={() => startRename(f)} onMove={() => setMoveFiles([f])} onDelete={() => handleDelete(f)} infoFileId={infoFile?.id ?? null} trimFileId={trimFile?.id ?? null} allFolders={allFolders} /> )} </div> ))} </div> )} </div> ); })} </div> </> ); } // ─── Files Tab ──────────────────────────────────────────────────────────────── function FilesTab({ onSelectForEncode, onJobStarted, onBatchEncode, initialOpenFolder }: { onSelectForEncode: (f: FileEntry) => void; onJobStarted: () => void; onBatchEncode: (files: FileEntry[]) => void; initialOpenFolder?: string; }) { const [downloaded, setDownloaded] = useState<FileEntry[]>([]); const [encoded, setEncoded] = useState<FileEntry[]>([]); const [folders, setFolders] = useState<string[]>([]); const [loading, setLoading] = useState(true); const [filter, setFilter] = useState<"all" | "downloaded" | "encoded">("all"); const [openFolders, setOpenFolders] = useState<Set<string>>(new Set()); const [showCreateFolder, setShowCreateFolder] = useState(false); const load = useCallback(async () => { try { const data = await api.getFiles(); setDownloaded(data.downloaded ?? []); setEncoded(data.encoded ?? []); setFolders(data.folders ?? []); } finally { setLoading(false); } }, []); useEffect(() => { load(); }, [load]); useEffect(() => { if (initialOpenFolder) { setOpenFolders((prev) => new Set([...prev, initialOpenFolder])); } }, [initialOpenFolder]); const toggleFolder = (folder: string) => { setOpenFolders((prev) => { const next = new Set(prev); if (next.has(folder)) next.delete(folder); else next.add(folder); return next; }); }; const allFiles = [...downloaded, ...encoded].sort((a, b) => b.createdAt - a.createdAt); const shown = filter === "all" ? allFiles : filter === "downloaded" ? [...downloaded].sort((a, b) => b.createdAt - a.createdAt) : [...encoded].sort((a, b) => b.createdAt - a.createdAt); const handleDeleteAll = async () => { if (!confirm("Delete ALL files (downloads + encoded)?")) return; await fetch("/api/files", { method: "DELETE" }); load(); }; const handleFolderCreated = (folder: string) => { load(); setOpenFolders((prev) => new Set([...prev, folder])); }; return ( <div className="space-y-6"> {showCreateFolder && ( <CreateFolderModal onClose={() => setShowCreateFolder(false)} onCreated={handleFolderCreated} /> )} <section> <h2 className="mb-3 text-sm font-semibold uppercase tracking-widest text-slate-500">Upload / Add Files</h2> <UploadArea onUploaded={load} /> </section> <section> <div className="mb-3 flex items-center justify-between gap-3 flex-wrap"> <h2 className="text-sm font-semibold uppercase tracking-widest text-slate-500">File Library</h2> <div className="flex items-center gap-2 flex-wrap"> <div className="flex rounded-lg border border-slate-200 bg-white overflow-hidden text-xs"> {(["all", "downloaded", "encoded"] as const).map((v) => ( <button key={v} onClick={() => setFilter(v)} className={`px-3 py-1.5 capitalize transition-colors ${filter === v ? "bg-violet-600 text-white" : "text-slate-600 hover:bg-slate-50"}`}> {v} </button> ))} </div> {/* Create folder button */} <button onClick={() => setShowCreateFolder(true)} className="flex items-center gap-1.5 rounded-lg border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs font-semibold text-amber-700 hover:bg-amber-100 transition-colors"> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 10.5v6m3-3H9m4.06-7.19-2.12-2.12a1.5 1.5 0 0 0-1.061-.44H4.5A2.25 2.25 0 0 0 2.25 6v12a2.25 2.25 0 0 0 2.25 2.25h15A2.25 2.25 0 0 0 21.75 18V9a2.25 2.25 0 0 0-2.25-2.25h-5.379a1.5 1.5 0 0 1-1.06-.44Z" /> </svg> New Folder </button> <button onClick={load} className="rounded-lg border border-slate-200 bg-white p-1.5 text-slate-500 hover:bg-slate-50" title="Refresh"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" /> </svg> </button> {allFiles.length > 0 && ( <button onClick={handleDeleteAll} className="rounded-lg border border-red-200 bg-white px-2.5 py-1.5 text-xs font-medium text-red-500 hover:bg-red-50 transition-colors"> Delete All </button> )} </div> </div> {loading ? ( <div className="py-10 text-center text-sm text-slate-400">Loading…</div> ) : ( <FileList files={shown} folders={folders} onRefresh={load} onSelectForEncode={onSelectForEncode} onJobStarted={onJobStarted} onBatchEncode={onBatchEncode} openFolders={openFolders} onToggleFolder={toggleFolder} /> )} </section> </div> ); } // ─── Encode Queue Manager ───────────────────────────────────────────────────── function EncodeQueueManager({ queue, onReorder, onRemove, onClear, encodeSettings, onPromote, runningUid }: { queue: QueueItem[]; onReorder: (newQueue: QueueItem[]) => void; onRemove: (uid: string) => void; onClear: () => void; encodeSettings: Record<string, unknown>; onPromote: (uid: string) => void; runningUid: string | null; }) { const dragUid = useRef<string | null>(null); const dragOverUid = useRef<string | null>(null); const moveUp = (idx: number) => { if (idx === 0) return; const next = [...queue]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; onReorder(next); }; const moveDown = (idx: number) => { if (idx === queue.length - 1) return; const next = [...queue]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; onReorder(next); }; const handleDragStart = (uid: string) => { dragUid.current = uid; }; const handleDragOver = (e: React.DragEvent, uid: string) => { e.preventDefault(); dragOverUid.current = uid; }; const handleDrop = () => { if (!dragUid.current || !dragOverUid.current || dragUid.current === dragOverUid.current) return; const from = queue.findIndex((q) => q.uid === dragUid.current); const to = queue.findIndex((q) => q.uid === dragOverUid.current); if (from === -1 || to === -1) return; const next = [...queue]; const [moved] = next.splice(from, 1); next.splice(to, 0, moved); onReorder(next); dragUid.current = null; dragOverUid.current = null; }; const statusBadge = (status: QueueItem["status"], idx: number) => { if (status === "waiting") return ( <span className="flex h-6 w-6 items-center justify-center rounded-full bg-slate-200 text-[11px] font-bold text-slate-600 flex-shrink-0">{idx + 1}</span> ); if (status === "encoding") return ( <span className="flex h-6 w-6 items-center justify-center rounded-full bg-amber-100 flex-shrink-0"> <svg className="animate-spin h-3.5 w-3.5 text-amber-600" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> </span> ); if (status === "done") return ( <span className="flex h-6 w-6 items-center justify-center rounded-full bg-emerald-100 flex-shrink-0"> <svg className="h-3.5 w-3.5 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}> <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" /> </svg> </span> ); return ( <span className="flex h-6 w-6 items-center justify-center rounded-full bg-red-100 flex-shrink-0"> <svg className="h-3.5 w-3.5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </span> ); }; return ( <div className="space-y-2"> <div className="flex items-center justify-between"> <p className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Encode Queue β€” {queue.length} file{queue.length !== 1 ? "s" : ""} </p> <button onClick={onClear} className="text-xs text-red-500 hover:underline">Clear queue</button> </div> <div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-1.5"> Drag rows or use ↑↓ to reorder. Files encode one by one in order. </div> <div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100"> {queue.map((item, idx) => ( <div key={item.uid} draggable={item.status === "waiting"} onDragStart={() => handleDragStart(item.uid)} onDragOver={(e) => handleDragOver(e, item.uid)} onDrop={handleDrop} className={`flex items-center gap-3 px-4 py-3 transition-colors ${ item.status === "encoding" ? "bg-amber-50" : item.status === "done" ? "bg-emerald-50" : item.status === "failed" ? "bg-red-50" : "hover:bg-slate-50" } ${item.status === "waiting" ? "cursor-grab active:cursor-grabbing" : ""}`}> <svg className={`h-4 w-4 flex-shrink-0 ${item.status === "waiting" ? "text-slate-300" : "text-slate-200"}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" /> </svg> {statusBadge(item.status, idx)} <div className="flex-1 min-w-0"> <p className="truncate text-sm font-medium text-slate-800">{item.file.name}</p> <p className="text-[10px] text-slate-400 mt-0.5"> {item.status === "waiting" && `Position ${idx + 1} Β· ${fmt(item.file.sizeBytes)}`} {item.status === "encoding" && "Encoding now…"} {item.status === "done" && "βœ“ Done"} {item.status === "failed" && "βœ— Failed"} </p> </div> {item.status === "waiting" && ( <div className="flex items-center gap-1 flex-shrink-0"> <button onClick={() => moveUp(idx)} disabled={idx === 0} className="rounded p-1 text-slate-400 hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" /> </svg> </button> <button onClick={() => moveDown(idx)} disabled={idx === queue.length - 1} className="rounded p-1 text-slate-400 hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" /> </svg> </button> <button onClick={() => onPromote(item.uid)} className="rounded p-1 text-violet-500 hover:bg-violet-50" title="Move to top (priority)"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 11h18M12 5v6m0 0 3-3m-3 3-3-3" /> </svg> </button> <button onClick={() => onRemove(item.uid)} className="rounded p-1 text-red-400 hover:bg-red-50"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> </div> )} {item.status === "encoding" && runningUid && item.uid !== runningUid && ( <button onClick={() => onPromote(item.uid)} className="rounded p-1 text-violet-500 hover:bg-violet-50" title="Make next in queue"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 11h18M12 5v6m0 0 3-3m-3 3-3-3" /> </svg> </button> )} {item.status === "waiting" && ( <span className="hidden sm:inline-flex items-center rounded-full bg-violet-100 px-2 py-0.5 text-[10px] font-medium text-violet-700 flex-shrink-0"> {String(encodeSettings.codec ?? "av1").toUpperCase()} Β· {String(encodeSettings.resolution ?? "480p")} Β· CRF {String(encodeSettings.crf ?? 40)} </span> )} </div> ))} </div> </div> ); } // ─── Encode Tab ─────────────────────────────────────────────────────────────── const CODECS = ["av1", "h265", "h264"] as const; const RESOLUTIONS = ["original", "1080p", "720p", "480p", "custom"] as const; const FRAME_RATES = ["original", "24", "25", "30", "60"] as const; const PRESETS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] as const; const H26X_PRESETS = [ "ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", ] as const; const AUDIO_BITRATES = [32, 48, 64, 72, 96, 128, 160, 192, 256] as const; function EncodeTab({ preselectedFiles, onJobStarted }: { preselectedFiles: FileEntry[]; onJobStarted: () => void }) { const [files, setFiles] = useState<FileEntry[]>([]); const [selectedId, setSelectedId] = useState(""); const [codec, setCodec] = useState<"av1" | "h265" | "h264">("av1"); const [mode, setMode] = useState<"crf-1pass" | "vbr">("crf-1pass"); const [crf, setCrf] = useState(40); const [videoBitrateKbps, setVideoBitrateKbps] = useState("800"); const [audioBitrateKbps, setAudioBitrateKbps] = useState("72"); const [resolution, setResolution] = useState("480p"); const [scaleWidth, setScaleWidth] = useState("1280"); const [scaleHeight, setScaleHeight] = useState("720"); const [frameRate, setFrameRate] = useState("original"); const [preset, setPreset] = useState(5); const [aqMode, setAqMode] = useState(0); const [tiles, setTiles] = useState("2x2"); const [h26xPreset, setH26xPreset] = useState<string>("medium"); const [forceStereo, setForceStereo] = useState(false); const [outputContainer, setOutputContainer] = useState<"mkv" | "mp4" | "webm">("mkv"); const [audioChannels, setAudioChannels] = useState<"original" | "stereo" | "mono">("original"); const [startTime, setStartTime] = useState(""); const [endTime, setEndTime] = useState(""); const [startTimeInput, setStartTimeInput] = useState(""); const [endTimeInput, setEndTimeInput] = useState(""); const [deinterlace, setDeinterlace] = useState(false); const [denoise, setDenoise] = useState(false); const [rotate, setRotate] = useState<"none" | "90cw" | "90ccw" | "180">("none"); const [speed, setSpeed] = useState(1); const [brightness, setBrightness] = useState(0); const [contrast, setContrast] = useState(1); const [saturation, setSaturation] = useState(1); const [stripSubtitles, setStripSubtitles] = useState(true); const [stripMetadata, setStripMetadata] = useState(true); const [sceneChange, setSceneChange] = useState(40); const [subtitleFile, setSubtitleFile] = useState(""); const [subtitleLang, setSubtitleLang] = useState("eng"); const [subtitleBurn, setSubtitleBurn] = useState(false); const [outputName, setOutputName] = useState("output.mkv"); const [queue, setQueue] = useState<QueueItem[]>([]); const [presets, setPresets] = useState<(EncodePreset | null)[]>([null, null, null]); const [activePreset, setActivePreset] = useState<number | null>(null); const [isRunningQueue, setIsRunningQueue] = useState(false); const [queueMsg, setQueueMsg] = useState<string | null>(null); const [runningUid, setRunningUid] = useState<string | null>(null); const abortQueue = useRef(false); const queueRef = useRef<QueueItem[]>([]); const [sameAsOriginalAudio, setSameAsOriginalAudio] = useState(false); const [sameAsOriginalVideo, setSameAsOriginalVideo] = useState(false); const [outputFormat, setOutputFormat] = useState<'video' | 'audio'>('video'); useEffect(() => { if (selectedId) { const f = files.find((x) => x.id === selectedId); if (f) { const suffix = outputFormat === 'audio' ? '_audio' : '_encoded'; setOutputName(f.name.replace(/(\.[^.]+)$/, `${suffix}.mkv`) || "output.mkv"); } } }, [outputFormat, selectedId, files]); useEffect(() => { if (outputFormat === 'audio') { setSameAsOriginalVideo(false); } }, [outputFormat]); const loadFiles = useCallback(async () => { const data = await api.getFiles(); setFiles(data.downloaded ?? []); }, []); useEffect(() => { loadFiles(); }, [loadFiles]); useEffect(() => { if (preselectedFiles.length > 0) { if (preselectedFiles.length === 1) { setSelectedId(preselectedFiles[0].id); setOutputName(preselectedFiles[0].name.replace(/(\.[^.]+)$/, "_encoded.mkv") || "output.mkv"); setQueue([]); } else { const presetLabel = activePreset != null && presets[activePreset] ? presets[activePreset]?.label : undefined; const currentSettings = { codec, mode, crf, videoBitrateKbps, audioBitrateKbps, resolution, scaleWidth, scaleHeight, frameRate, preset, aqMode, tiles, forceStereo, h26xPreset, outputContainer, audioChannels, startTime: startTimeInput, endTime: endTimeInput, deinterlace, denoise, rotate, speed, brightness, contrast, saturation, stripSubtitles, stripMetadata, sceneChange, subtitleFile, subtitleLang, subtitleBurn, outputFormat, sameAsOriginalAudio, sameAsOriginalVideo, }; const newItems: QueueItem[] = preselectedFiles.map((f) => ({ uid: `${f.id}_${Math.random().toString(16).slice(2)}`, file: f, status: "waiting", jobId: null, settings: { ...currentSettings }, presetLabel, })); setQueue(newItems); setSelectedId(""); } } }, [ preselectedFiles, activePreset, presets, codec, mode, crf, videoBitrateKbps, audioBitrateKbps, resolution, scaleWidth, scaleHeight, frameRate, preset, aqMode, tiles, forceStereo, h26xPreset, outputContainer, audioChannels, startTime, endTime, deinterlace, denoise, rotate, speed, brightness, contrast, saturation, stripSubtitles, stripMetadata, sceneChange, subtitleFile, subtitleLang, outputFormat, sameAsOriginalAudio, sameAsOriginalVideo, ]); useEffect(() => { queueRef.current = queue; }, [queue]); useEffect(() => { try { const raw = localStorage.getItem("ve_presets"); if (raw) { const parsed = JSON.parse(raw); if (Array.isArray(parsed)) setPresets(parsed); } } catch { /* ignore */ } }, []); useEffect(() => { try { localStorage.setItem("ve_presets", JSON.stringify(presets)); } catch { /* ignore */ } }, [presets]); const encodeSettings = { codec, mode, crf, videoBitrateKbps: Number(videoBitrateKbps || 0), audioBitrateKbps: Number(audioBitrateKbps || 0), resolution, scaleWidth: Number(scaleWidth || 0), scaleHeight: Number(scaleHeight || 0), frameRate, preset, aqMode, tiles, forceStereo, h26xPreset, outputContainer, audioChannels, startTime: startTimeInput, endTime: endTimeInput, deinterlace, denoise, rotate, speed, brightness, contrast, saturation, stripSubtitles, stripMetadata, sceneChange, subtitleFile, subtitleLang, subtitleBurn, outputFormat, sameAsOriginalAudio, sameAsOriginalVideo, }; const buildSettings = (f: FileEntry, outFilename: string) => ({ inputFilename: f.relativePath || f.name, outputFilename: outFilename, ...encodeSettings, }); const runQueue = async () => { setIsRunningQueue(true); abortQueue.current = false; setQueueMsg(null); let completed = 0; let failed = 0; let started = 0; while (true) { if (abortQueue.current) break; const currentQueue = queueRef.current; const nextItem = currentQueue.find((q) => q.status === "waiting"); if (!nextItem) break; started += 1; setRunningUid(nextItem.uid); setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: "encoding" } : q)); const totalInQueue = currentQueue.length; try { const base = nextItem.file.name.replace(/(\.[^.]+)$/, "_encoded"); const ext = outputContainer === "mp4" ? ".mp4" : outputContainer === "webm" ? ".webm" : ".mkv"; const outFilename = `${base}${ext}` || "output.mkv"; const job = await api.startEncode({ ...buildSettings(nextItem.file, outFilename), batchIndex: started, batchTotal: totalInQueue, }); setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, jobId: job.id } : q)); await new Promise<void>((resolve) => { const iv = setInterval(async () => { if (abortQueue.current) { clearInterval(iv); resolve(); return; } try { const updated = await api.getJob(job.id); if (updated.status !== "running") { clearInterval(iv); const finalStatus = updated.status === "done" ? "done" : "failed"; setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: finalStatus } : q)); if (updated.status === "done") completed++; else failed++; resolve(); } } catch { clearInterval(iv); resolve(); } }, 2000); }); } catch { setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: "failed" } : q)); failed++; } finally { setRunningUid(null); } } setIsRunningQueue(false); if (!abortQueue.current) { setQueueMsg(`βœ“ Queue complete: ${completed} done, ${failed} failed`); onJobStarted(); } else { setQueueMsg("Queue stopped."); } }; const handleSingleEncode = async () => { const selectedFile = files.find((f) => f.id === selectedId); if (!selectedFile) return; const baseName = outputName.replace(/\.[^.]+$/, ""); const ext = outputContainer === "mp4" ? ".mp4" : outputContainer === "webm" ? ".webm" : ".mkv"; const finalOut = `${baseName}${ext}`; try { await api.startEncode(buildSettings(selectedFile, finalOut)); setQueueMsg("βœ“ Encode job started!"); onJobStarted(); } catch { setQueueMsg("βœ— Failed to start encode job."); } }; const Field = ({ label, children, help }: { label: string; children: React.ReactNode; help?: string }) => ( <div className="space-y-1"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 flex items-center flex-wrap"> {label} {help && <HelpTip text={help} />} </label> {children} </div> ); const handleSavePreset = (index: number) => { const label = `Preset ${index + 1}`; setPresets((prev) => { const next = [...prev]; next[index] = { id: index + 1, label, settings: { ...encodeSettings } }; return next; }); setActivePreset(index); setQueueMsg(`βœ“ Saved ${label}`); }; const handleLoadPreset = (index: number) => { const p = presets[index]; if (!p) return; const s = p.settings as Record<string, any>; setActivePreset(index); setCodec((s.codec ?? "av1") as any); setMode((s.mode ?? "crf-1pass") as any); setCrf(Number(s.crf ?? 40)); setVideoBitrateKbps(String(s.videoBitrateKbps ?? 800)); setAudioBitrateKbps(String(s.audioBitrateKbps ?? 72)); setResolution(String(s.resolution ?? "480p")); setScaleWidth(String(s.scaleWidth ?? 1280)); setScaleHeight(String(s.scaleHeight ?? 720)); setFrameRate(String(s.frameRate ?? "original")); setPreset(Number(s.preset ?? 5)); setAqMode(Number(s.aqMode ?? 0)); setTiles(String(s.tiles ?? "2x2")); setForceStereo(Boolean(s.forceStereo ?? false)); setH26xPreset(String(s.h26xPreset ?? "medium")); setOutputContainer((s.outputContainer ?? "mkv") as any); setAudioChannels((s.audioChannels ?? "original") as any); setStartTime(String(s.startTime ?? "")); setEndTime(String(s.endTime ?? "")); setStartTimeInput(String(s.startTime ?? "")); setEndTimeInput(String(s.endTime ?? "")); setDeinterlace(Boolean(s.deinterlace ?? false)); setDenoise(Boolean(s.denoise ?? false)); setRotate((s.rotate ?? "none") as any); setSpeed(Number(s.speed ?? 1)); setBrightness(Number(s.brightness ?? 0)); setContrast(Number(s.contrast ?? 1)); setSaturation(Number(s.saturation ?? 1)); setStripSubtitles(Boolean(s.stripSubtitles ?? true)); setStripMetadata(Boolean(s.stripMetadata ?? true)); setSceneChange(Number(s.sceneChange ?? 40)); setSubtitleFile(String(s.subtitleFile ?? "")); setSubtitleLang(String(s.subtitleLang ?? "eng")); setSubtitleBurn(Boolean(s.subtitleBurn ?? false)); setQueueMsg(`βœ“ Loaded ${p.label}`); }; const handleApplyPresetToQueue = (index: number) => { const p = presets[index]; if (!p) return; setQueue((prev) => prev.map((q) => ({ ...q, settings: { ...p.settings }, presetLabel: p.label }))); setQueueMsg(`βœ“ Applied ${p.label} to queue`); setActivePreset(index); }; const subtitleFiles = files.filter((f) => isSubtitleFile(f.name)); const subtitleOptions = subtitleFiles.map((f) => ({ label: f.folder && f.folder !== "/" ? `${f.folder}/${f.name}` : f.name, value: f.relativePath || f.name, })); const selectCls = "w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"; const inputCls = "w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"; const waitingCount = queue.filter((q) => q.status === "waiting").length; return ( <div className="space-y-6"> {queue.length > 0 && ( <EncodeQueueManager queue={queue} onReorder={setQueue} onRemove={(uid) => setQueue((prev) => prev.filter((q) => q.uid !== uid))} onClear={() => { setQueue([]); abortQueue.current = true; setIsRunningQueue(false); setQueueMsg(null); }} encodeSettings={encodeSettings} onPromote={(uid) => { setQueue((prev) => { const idx = prev.findIndex((q) => q.uid === uid); if (idx <= 0) return prev; const next = [...prev]; const [item] = next.splice(idx, 1); next.unshift(item); return next; }); }} runningUid={runningUid} /> )} <div className="rounded-xl border border-slate-200 bg-white p-5 space-y-5"> {queue.length === 0 && ( <> <Field label="Input File"> <div className="flex gap-2"> <select className={selectCls} value={selectedId} onChange={(e) => { setSelectedId(e.target.value); const f = files.find((x) => x.id === e.target.value); if (f) { const suffix = outputFormat === 'audio' ? '_audio' : '_encoded'; setOutputName(f.name.replace(/(\.[^.]+)$/, `${suffix}.mkv`) || "output.mkv"); } }}> <option value="">β€” select a downloaded file β€”</option> {files.map((f) => <option key={f.id} value={f.id}>{f.name} ({fmt(f.sizeBytes)})</option>)} </select> <button onClick={loadFiles} className="flex-shrink-0 rounded-lg border border-slate-200 p-2 text-slate-500 hover:bg-slate-50" title="Refresh"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" /> </svg> </button> </div> </Field> <Field label="Output Filename"> <input className={inputCls} value={outputName} onChange={(e) => setOutputName(e.target.value)} /> </Field> </> )} <div className="grid grid-cols-3 gap-4"> <Field label="Codec" help="AV1 (SVT-AV1): best compression, slow. H265: good compression, faster. H264: widest compatibility, largest files."> <select className={selectCls} value={codec} onChange={(e) => setCodec(e.target.value as typeof codec)} disabled={outputFormat === 'audio'}> {CODECS.map((c) => <option key={c} value={c}>{c.toUpperCase()}</option>)} </select> </Field> <Field label="Mode" help="CRF: constant quality (recommended β€” let encoder decide bitrate). VBR: target bitrate (less predictable quality)."> <select className={selectCls} value={mode} onChange={(e) => setMode(e.target.value as typeof mode)} disabled={outputFormat === 'audio'}> <option value="crf-1pass">CRF (1-pass)</option> <option value="vbr">VBR</option> </select> </Field> <Field label="Output Format" help="Video: encode to video with audio. Audio: extract audio only."> <select className={selectCls} value={outputFormat} onChange={(e) => setOutputFormat(e.target.value as typeof outputFormat)}> <option value="video">Video</option> <option value="audio">Audio</option> </select> </Field> </div> <div className="rounded-xl border border-slate-200 bg-slate-50 p-4"> <div className="flex items-center justify-between mb-2"> <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">Presets</p> <span className="text-[10px] text-slate-400">Save/load 3 workflows</span> </div> <div className="grid grid-cols-1 sm:grid-cols-3 gap-3"> {presets.map((p, idx) => ( <div key={idx} className={`rounded-lg border px-3 py-2 ${activePreset === idx ? "border-violet-400 bg-violet-50" : "border-slate-200 bg-white"}`}> <p className="text-xs font-semibold text-slate-700 mb-2">Preset {idx + 1}</p> <div className="flex items-center gap-2"> <button onClick={() => handleSavePreset(idx)} className="flex-1 rounded-md bg-violet-600 px-2 py-1 text-[11px] font-semibold text-white hover:bg-violet-700"> Save </button> <button onClick={() => handleLoadPreset(idx)} disabled={!p} className="flex-1 rounded-md border border-slate-200 bg-white px-2 py-1 text-[11px] font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40"> Load </button> </div> {p && ( <p className="mt-2 text-[10px] text-slate-500">{p.label}</p> )} {queue.length > 0 && p && ( <button onClick={() => handleApplyPresetToQueue(idx)} className="mt-2 w-full rounded-md bg-slate-100 px-2 py-1 text-[10px] font-semibold text-slate-600 hover:bg-slate-200"> Apply to queue </button> )} </div> ))} </div> </div> <div className="grid grid-cols-2 gap-4"> {mode === "crf-1pass" ? ( <Field label={`CRF (${crf})`} help="Constant Rate Factor. Lower = better quality + larger file. Higher = smaller file + lower quality. AV1: 30-45 typical. H265: 22-32. H264: 18-28."> <input type="range" min={0} max={63} value={crf} onChange={(e) => setCrf(Number(e.target.value))} className="w-full accent-violet-600" disabled={sameAsOriginalVideo || outputFormat === 'audio'} /> </Field> ) : ( <Field label="Video Bitrate (kbps)" help="Target video bitrate in kilobits/sec. Higher = better quality + larger file. 480p: 400-800k. 720p: 1000-2000k. 1080p: 2000-4000k."> <input type="number" min={100} className={inputCls} value={videoBitrateKbps} onChange={(e) => setVideoBitrateKbps(e.target.value)} disabled={sameAsOriginalVideo || outputFormat === 'audio'} /> </Field> )} <Field label="Opus Audio (kbps)" help="Audio bitrate using Opus codec. 48-72: speech. 96-128: music. 64-72 is transparent for most content. Opus sounds better than AAC at same bitrate."> <select className={selectCls} value={audioBitrateKbps} onChange={(e) => setAudioBitrateKbps(e.target.value)} disabled={sameAsOriginalAudio}> {AUDIO_BITRATES.map((b) => <option key={b} value={b}>{b}</option>)} </select> </Field> </div> <div className="flex gap-6"> {outputFormat === 'video' && ( <label className="flex items-center gap-2"> <input type="checkbox" checked={sameAsOriginalVideo} onChange={(e) => setSameAsOriginalVideo(e.target.checked)} /> <span className="text-sm">Same as original quality (video)</span> </label> )} <label className="flex items-center gap-2"> <input type="checkbox" checked={sameAsOriginalAudio} onChange={(e) => setSameAsOriginalAudio(e.target.checked)} /> <span className="text-sm">Same as original quality (audio)</span> </label> </div> <div className="grid grid-cols-2 gap-4"> <Field label="Resolution" help="Output video resolution. Aspect ratio is always preserved. 480p is good for mobile/small screens. 720p for tablets. 1080p for desktops."> <select className={selectCls} value={resolution} onChange={(e) => setResolution(e.target.value)} disabled={sameAsOriginalVideo || outputFormat === 'audio'}> {RESOLUTIONS.map((r) => <option key={r} value={r}>{r}</option>)} </select> </Field> <Field label="Frame Rate" help="Output frame rate. 'Original' keeps source fps. 24fps = cinematic. 30fps = standard. Lower fps = smaller file but less smooth motion."> <select className={selectCls} value={frameRate} onChange={(e) => setFrameRate(e.target.value)} disabled={outputFormat === 'audio'}> {FRAME_RATES.map((r) => <option key={r} value={r}>{r === "original" ? "original" : `${r} fps`}</option>)} </select> </Field> </div> {resolution === "custom" && ( <div className="grid grid-cols-2 gap-4"> <Field label="Width (px)" help="Custom output width in pixels. Must be even number. Use -2 for auto-calculate from height while preserving aspect ratio."><input type="number" className={inputCls} value={scaleWidth} onChange={(e) => setScaleWidth(e.target.value)} /></Field> <Field label="Height (px)" help="Custom output height in pixels. Must be even number. Aspect ratio is NOT preserved with custom dimensions β€” set one dimension and use -2 for the other if needed."><input type="number" className={inputCls} value={scaleHeight} onChange={(e) => setScaleHeight(e.target.value)} /></Field> </div> )} {codec === "av1" && ( <div className="grid grid-cols-3 gap-4"> <Field label={`Preset (${preset})`} help="SVT-AV1 speed preset. 0 = slowest/best quality. 13 = fastest/worst quality. 4-6 is a good balance. Lower = much slower but smaller files."> <select className={selectCls} value={preset} onChange={(e) => setPreset(Number(e.target.value))}> {PRESETS.map((p) => <option key={p} value={p}>{p}</option>)} </select> </Field> <Field label="AQ Mode" help="Adaptive Quantization. Off = even bitrate distribution (faster, smaller). Variance = allocates more bits to flat areas. Complexity = allocates more bits to complex areas (better quality but larger/slower)."> <select className={selectCls} value={aqMode} onChange={(e) => setAqMode(Number(e.target.value))}> <option value={0}>0 - Off</option> <option value={1}>1 - Variance</option> <option value={2}>2 - Complexity</option> </select> </Field> <Field label="Tiles" help="Split video into 2Γ—2 tiles for parallel encoding. Faster on multi-core CPUs. Slight quality tradeoff at tile borders. Recommended for 480p+ content."> <select className={selectCls} value={tiles} onChange={(e) => setTiles(e.target.value)}> <option value="none">None</option> <option value="2x2">2Γ—2</option> </select> </Field> </div> )} {(codec === "h265" || codec === "h264") && ( <Field label="Encoder Speed (Preset)" help="Encoder speed vs compression. 'ultrafast' = huge files, instant encode. 'veryslow' = tiny files, very slow encode. 'medium' is the default balance. Each step slower saves ~5-10% file size."> <select className={selectCls} value={h26xPreset} onChange={(e) => setH26xPreset(e.target.value)}> {H26X_PRESETS.map((p) => ( <option key={p} value={p}> {p}{p === "medium" ? " (default)" : p === "ultrafast" ? " β€” fastest, largest" : p === "veryslow" ? " β€” slowest, smallest" : ""} </option> ))} </select> <p className="text-[10px] text-slate-400 mt-1"> Slower preset = smaller file + better quality. Faster preset = quicker encode + larger file. </p> </Field> )} <label className="flex cursor-pointer items-center gap-2 text-sm text-slate-700"> <input type="checkbox" checked={forceStereo} onChange={(e) => setForceStereo(e.target.checked)} className="h-4 w-4 accent-violet-600 rounded" /> Force stereo audio <HelpTip text="Downmix all audio to stereo (2 channels). Useful when source has 5.1/7.1 surround but target device only supports stereo. Saves space." /> </label> {queueMsg && ( <p className={`text-sm ${queueMsg.startsWith("βœ“") ? "text-green-600" : queueMsg.startsWith("βœ—") ? "text-red-500" : "text-slate-500"}`}> {queueMsg} </p> )} <details className="rounded-xl border border-slate-200 bg-slate-50 p-4"> <summary className="cursor-pointer select-none text-sm font-semibold text-slate-700"> βš™ Advanced Options (quality + size + speed tuned for SVT-AV1) </summary> <div className="mt-4 space-y-4"> <div className="grid grid-cols-2 gap-4"> <Field label="Container" help="MKV: supports all codecs, subtitles, and chapters. Best for archival. MP4: widest device/browser compatibility but no Opus in older players. WebM: web-optimized, AV1+Opus only."> <select className={selectCls} value={outputContainer} onChange={(e) => setOutputContainer(e.target.value as "mkv" | "mp4" | "webm")}> <option value="mkv">MKV (recommended)</option> <option value="mp4">MP4 (wider compatibility)</option> <option value="webm">WebM (AV1 only)</option> </select> </Field> <Field label="Audio Channels" help="Original: keep source channels (5.1/7.1/etc). Stereo: downmix to 2 channels. Mono: single channel. Stereo/mono saves space."> <select className={selectCls} value={audioChannels} onChange={(e) => setAudioChannels(e.target.value as "original" | "stereo" | "mono")}> <option value="original">Original</option> <option value="stereo">Stereo</option> <option value="mono">Mono</option> </select> </Field> </div> <div className="grid grid-cols-2 gap-4"> <Field label="Start Time (HH:MM:SS)" help="Encode only a portion of the video starting from this timestamp. Leave blank to start from beginning. Format: HH:MM:SS or MM:SS or just seconds."> <TimePartsInput value={startTimeInput} allowEmpty onChange={setStartTimeInput} /> </Field> <Field label="End Time (HH:MM:SS)" help="Stop encoding at this timestamp. Leave blank to encode to the end. Combine with Start Time to encode a specific segment."> <TimePartsInput value={endTimeInput} allowEmpty onChange={setEndTimeInput} /> </Field> </div> <Field label={`Scene Change Sensitivity (${sceneChange})`} help="Controls keyframe insertion at scene changes. 0 = detect all scene changes (more keyframes = better seeking but larger file). 100 = keyframes only at GOP boundaries (smaller file but worse seeking). Default 40 is balanced."> <input type="range" min={0} max={100} step={1} value={sceneChange} onChange={(e) => setSceneChange(Number(e.target.value))} className="w-full accent-violet-600" /> </Field> <div className="grid grid-cols-2 gap-4"> <label className="flex items-center gap-2 text-sm text-slate-700"> <input type="checkbox" className="h-4 w-4 accent-violet-600" checked={deinterlace} onChange={(e) => setDeinterlace(e.target.checked)} /> Deinterlace (yadif) <HelpTip text="Removes interlacing artifacts (horizontal lines) from old TV recordings, DVDs, or broadcast captures. Only use if source is interlaced. ~5% slower encode." /> </label> <label className="flex items-center gap-2 text-sm text-slate-700"> <input type="checkbox" className="h-4 w-4 accent-violet-600" checked={denoise} onChange={(e) => setDenoise(e.target.checked)} /> Denoise (hqdn3d) <HelpTip text="Reduces grain/noise in video. Cleaner video compresses much better = smaller files. But can soften details if overused. Good for old/noisy sources. ~10% slower encode." /> </label> </div> <div className="grid grid-cols-2 gap-4"> <Field label="Rotate" help="Rotate the video. 90Β° CW/CCW for vertical videos. 180Β° to flip upside down. Uses fast transpose β€” no quality loss, minimal speed impact."> <select className={selectCls} value={rotate} onChange={(e) => setRotate(e.target.value as "none" | "90cw" | "90ccw" | "180")}> <option value="none">None</option> <option value="90cw">90Β° CW</option> <option value="90ccw">90Β° CCW</option> <option value="180">180Β°</option> </select> </Field> <Field label={`Speed (${speed.toFixed(2)}Γ—)`} help="Playback speed. 0.5Γ— = slow motion (2Γ— duration). 2Γ— = fast forward (half duration). Audio pitch is preserved. 1.0 = normal speed."> <input type="range" min={0.5} max={2} step={0.05} value={speed} onChange={(e) => setSpeed(Number(e.target.value))} className="w-full accent-violet-600" /> </Field> </div> <div className="grid grid-cols-3 gap-4"> <Field label={`Brightness (${brightness.toFixed(2)})`} help="Adjust video brightness. -1.0 = black. 0 = no change. +1.0 = full white. Use small values like Β±0.1 for subtle correction."> <input type="range" min={-1} max={1} step={0.05} value={brightness} onChange={(e) => setBrightness(Number(e.target.value))} className="w-full accent-violet-600" /> </Field> <Field label={`Contrast (${contrast.toFixed(2)})`} help="Adjust video contrast. 0 = grey. 1.0 = no change. 2.0 = maximum contrast. Higher contrast makes colors pop but can clip highlights/shadows."> <input type="range" min={0} max={2} step={0.05} value={contrast} onChange={(e) => setContrast(Number(e.target.value))} className="w-full accent-violet-600" /> </Field> <Field label={`Saturation (${saturation.toFixed(2)})`} help="Color intensity. 0 = black & white. 1.0 = no change. 3.0 = extremely vivid. Use 1.1-1.3 for subtle color boost."> <input type="range" min={0} max={3} step={0.05} value={saturation} onChange={(e) => setSaturation(Number(e.target.value))} className="w-full accent-violet-600" /> </Field> </div> <div className="grid grid-cols-2 gap-4"> <label className="flex items-center gap-2 text-sm text-slate-700"> <input type="checkbox" className="h-4 w-4 accent-violet-600" checked={stripSubtitles} onChange={(e) => setStripSubtitles(e.target.checked)} /> Strip subtitles <HelpTip text="Removes all embedded subtitle tracks from the output. Saves ~1-5 MB per track. Enable this unless you want to keep existing subtitles." /> </label> <label className="flex items-center gap-2 text-sm text-slate-700"> <input type="checkbox" className="h-4 w-4 accent-violet-600" checked={stripMetadata} onChange={(e) => setStripMetadata(e.target.checked)} /> Strip metadata <HelpTip text="Removes all file metadata (title, author, GPS location, creation date, etc). Good for privacy. Saves ~10-50 KB. No effect on video/audio quality." /> </label> </div> <div className="rounded-xl border border-violet-200 bg-violet-50/30 p-3 space-y-2"> <p className="text-xs font-semibold text-violet-700 flex items-center gap-1"> πŸ“ Add Subtitle Track <HelpTip text="Embed an external .srt/.ass/.vtt subtitle file into the video. Choose a language code (e.g., 'eng', 'ara', 'fra') so players can show the subtitle name. Upload subtitle files first via the Files tab." /> </p> <div className="grid grid-cols-2 gap-3"> <select className={selectCls} value={subtitleFile} onChange={(e) => setSubtitleFile(e.target.value)}> <option value="">No subtitle</option> {subtitleOptions.map((opt) => ( <option key={opt.value} value={opt.value}>{opt.label}</option> ))} </select> <input className={inputCls} placeholder="Language code (e.g., eng, ara)" value={subtitleLang} onChange={(e) => setSubtitleLang(e.target.value)} /> </div> <label className="flex items-center gap-2 text-sm text-slate-700"> <input type="checkbox" className="h-4 w-4 accent-violet-600" checked={subtitleBurn} onChange={(e) => setSubtitleBurn(e.target.checked)} /> Burn subtitles into video (hardcode) <HelpTip text="ON = subtitles are permanently drawn onto the video pixels. Cannot be turned off during playback. Useful for sharing. OFF = subtitles are a separate track that can be toggled on/off in the player." /> </label> <p className="text-[10px] text-slate-400">If not burned, subtitle will be included as a toggleable track in the player.</p> </div> <div className="text-[10px] text-slate-500 bg-white rounded-lg px-3 py-2 border border-slate-200"> βœ… Defaults chosen for faster SVT-AV1 encodes with smaller files and good quality. Use deinterlace/denoise only when needed (they slow encode). </div> </div> </details> {queue.length > 0 ? ( <div className="flex gap-3"> <button onClick={runQueue} disabled={isRunningQueue || waitingCount === 0} className="flex-1 rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50"> {isRunningQueue ? `⏳ Encoding ${queue.filter((q) => q.status === "encoding").map((q) => q.file.name)[0] ?? "…"}` : `β–Ά Start Queue (${waitingCount} file${waitingCount !== 1 ? "s" : ""})`} </button> {isRunningQueue && ( <button onClick={() => { abortQueue.current = true; }} className="rounded-xl bg-red-50 border border-red-200 px-4 py-2.5 text-sm font-semibold text-red-600 hover:bg-red-100 transition-colors"> β–  Stop Queue </button> )} </div> ) : ( <button onClick={handleSingleEncode} disabled={!selectedId} className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50"> Start Encode </button> )} </div> </div> ); } // ─── Jobs Tab ───────────────────────────────────────────────────────────────── function JobCard({ job: initial, onStopped, onDone }: { job: Job; onStopped: () => void; onDone: (job: Job) => void; }) { const [job, setJob] = useState(initial); const [showLog, setShowLog] = useState(false); const [stopping, setStopping] = useState(false); const witnessed = useRef(false); const onDoneRef = useRef(onDone); useEffect(() => { onDoneRef.current = onDone; }, [onDone]); useEffect(() => { witnessed.current = false; if (job.status !== "running") { if (job.status === "done" && !witnessed.current) { witnessed.current = true; setTimeout(() => onDoneRef.current(job), 1800); } return; } const iv = setInterval(async () => { try { const updated = await api.getJob(job.id); setJob(updated); if (updated.status !== "running") { clearInterval(iv); if (updated.status === "done" && !witnessed.current) { witnessed.current = true; setTimeout(() => onDoneRef.current(updated), 1800); } } } catch { /* ignore */ } }, 1500); return () => clearInterval(iv); }, [job.id, job.status]); const handleStop = async () => { setStopping(true); try { await api.stopJob(job.id); const updated = await api.getJob(job.id); setJob(updated); onStopped(); } finally { setStopping(false); } }; const statusColor = job.status === "done" ? "bg-emerald-100 text-emerald-700" : job.status === "failed" ? "bg-red-100 text-red-600" : job.status === "stopped" ? "bg-slate-100 text-slate-600" : "bg-amber-100 text-amber-700"; const settings = job.settings as Record<string, unknown>; const isTrim = settings.type === "trim"; const isMerge = settings.type === "merge"; return ( <div className="rounded-xl border border-slate-200 bg-white overflow-hidden"> <div className="flex items-center justify-between gap-4 px-4 py-3"> <div className="min-w-0 flex-1"> <p className="truncate text-sm font-semibold text-slate-800"> {isMerge ? "πŸ”— " : isTrim ? "βœ‚οΈ " : "🎬 "} {isMerge ? `Merge ${(settings.inputFilenames as string[] | undefined)?.length ?? "?"} files β†’ ${String(settings.outputFilename ?? "β€”")}` : `${String(settings.inputFilename ?? "β€”")} β†’ ${String(settings.outputFilename ?? "β€”")}`} </p> <p className="mt-0.5 text-xs text-slate-400"> {isMerge ? `Stream copy merge Β· ${(settings.inputFilenames as string[] | undefined)?.join(", ") ?? ""}` : isTrim ? `Trim ${secondsToHms(Number(settings.startTime ?? 0))} β†’ ${secondsToHms(Number(settings.endTime ?? 0))} Β· stream copy` : `${String(settings.codec ?? "").toUpperCase()} Β· ${String(settings.resolution ?? "original")} Β· ${String(settings.mode ?? "")}${settings.mode === "crf-1pass" ? ` CRF ${settings.crf}` : ` ${settings.videoBitrateKbps}kbps`}` } </p> </div> <div className="flex items-center gap-2 flex-shrink-0"> {job.batchIndex != null && job.batchTotal != null && ( <span className="inline-flex items-center rounded-full bg-violet-100 px-2.5 py-0.5 text-xs font-bold text-violet-700 border border-violet-200"> {job.batchIndex} of {job.batchTotal} </span> )} <Badge color={statusColor}>{job.status}</Badge> {job.status === "running" && ( <button onClick={handleStop} disabled={stopping} className="flex items-center gap-1 rounded-lg bg-red-50 border border-red-200 px-2.5 py-1 text-xs font-semibold text-red-600 hover:bg-red-100 transition-colors disabled:opacity-50"> <svg className="h-3 w-3" fill="currentColor" viewBox="0 0 24 24"> <rect x="4" y="4" width="16" height="16" rx="2" /> </svg> {stopping ? "Stopping…" : "Stop"} </button> )} </div> </div> {job.status === "running" && ( <div className="px-4 pb-1"> <div className="relative h-2 w-full overflow-hidden rounded-full bg-slate-100"> <div className="h-full rounded-full bg-violet-500 transition-all duration-500" style={{ width: `${job.progress.percent}%` }} /> </div> <div className="mt-1 flex justify-between text-xs text-slate-400"> <span> {job.progress.percent.toFixed(1)}% Β· {job.progress.fps.toFixed(0)} fps {(() => { const bitrateKbps = (job.progress as { bitrateKbps?: number }).bitrateKbps; if (bitrateKbps && bitrateKbps > 0) { const displayBitrate = bitrateKbps >= 1000 ? `${(bitrateKbps / 1000).toFixed(1)} Mbps` : `${Math.round(bitrateKbps)} kbps`; return <span className="ml-1 text-violet-500">Β· {displayBitrate}</span>; } return null; })()} </span> <span> ETA {fmtEta(job.progress.etaSeconds)} {(() => { const speed = (job.progress as { speed?: number }).speed; return speed && speed > 0 ? ( <span className="ml-1 text-violet-500">Β· {speed.toFixed(2)}Γ— speed</span> ) : null; })()} </span> <span>{fmt(job.progress.sizeOutBytes)}</span> </div> </div> )} {job.status === "stopped" && ( <div className="px-4 pb-3 text-xs text-slate-400"> Job stopped Β· {fmt(job.progress.sizeOutBytes)} written </div> )} {job.status === "done" && ( <div className="px-4 pb-3 text-xs text-slate-400"> Output size: {fmt(job.progress.sizeOutBytes)} </div> )} <button onClick={() => setShowLog((v) => !v)} className="flex w-full items-center justify-between border-t border-slate-100 px-4 py-2 text-xs text-slate-500 hover:bg-slate-50 transition-colors"> <span>ffmpeg log</span> <svg className={`h-3.5 w-3.5 transition-transform ${showLog ? "rotate-180" : ""}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" /> </svg> </button> {showLog && ( <pre className="max-h-48 overflow-y-auto border-t border-slate-100 bg-slate-900 p-3 text-[10px] leading-relaxed text-slate-300 whitespace-pre-wrap"> {job.progress.log.join("\n") || "No output yet"} </pre> )} </div> ); } function JobsTab({ onJobDone }: { onJobDone: (job: Job) => void }) { const [jobs, setJobs] = useState<Job[]>([]); const [loading, setLoading] = useState(true); const load = useCallback(async () => { const data = await api.getJobs(); setJobs(data); setLoading(false); }, []); useEffect(() => { load(); const iv = setInterval(load, 2000); return () => clearInterval(iv); }, [load]); return ( <div className="space-y-4"> <div className="flex items-center justify-between"> <h2 className="text-sm font-semibold uppercase tracking-widest text-slate-500">Encode Jobs</h2> <button onClick={load} className="rounded-lg border border-slate-200 bg-white p-1.5 text-slate-500 hover:bg-slate-50" title="Refresh"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" /> </svg> </button> </div> {loading ? ( <div className="py-10 text-center text-sm text-slate-400">Loading…</div> ) : jobs.length === 0 ? ( <div className="rounded-xl border border-dashed border-slate-200 py-10 text-center text-sm text-slate-400"> No jobs yet β€” start an encode from the Encode tab </div> ) : ( <div className="space-y-3"> {jobs.map((j) => <JobCard key={j.id} job={j} onStopped={load} onDone={onJobDone} />)} </div> )} </div> ); } // ─── App ────────────────────────────────────────────────────────────────────── export function App() { const [tab, setTab] = useState<Tab>("files"); const [encodeFiles, setEncodeFiles] = useState<FileEntry[]>([]); const [filesRefreshKey, setFilesRefreshKey] = useState(0); const [openFolderOnReturn, setOpenFolderOnReturn] = useState<string | undefined>(undefined); const handleSelectForEncode = (f: FileEntry) => { setEncodeFiles([f]); setTab("encode"); }; const handleBatchEncode = (files: FileEntry[]) => { setEncodeFiles(files); setTab("encode"); }; const handleJobStarted = () => { setTab("jobs"); }; const handleJobDone = useCallback((job: Job) => { const folder = job.outputFolder || "/"; setOpenFolderOnReturn(folder === "/" ? undefined : folder); setFilesRefreshKey((k) => k + 1); setTab("files"); }, []); const tabs: { key: Tab; label: string; icon: React.ReactNode }[] = [ { key: "files", label: "Files", icon: ( <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 0 0-1.883 2.542l.857 6a2.25 2.25 0 0 0 2.227 1.932H19.05a2.25 2.25 0 0 0 2.227-1.932l.857-6a2.25 2.25 0 0 0-1.883-2.542m-16.5 0V6A2.25 2.25 0 0 1 6 3.75h3.879a1.5 1.5 0 0 1 1.06.44l2.122 2.12a1.5 1.5 0 0 0 1.06.44H18A2.25 2.25 0 0 1 20.25 9v.776" /> </svg> ), }, { key: "encode", label: "Encode", icon: ( <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" /> </svg> ), }, { key: "jobs", label: "Jobs", icon: ( <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 0 1 0 3.75H5.625a1.875 1.875 0 0 1 0-3.75Z" /> </svg> ), }, { key: "remote", label: "Remote", icon: ( <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418" /> </svg> ), }, ]; return ( <div className="min-h-screen bg-gradient-to-br from-slate-100 via-slate-50 to-violet-50"> <header className="sticky top-0 z-20 border-b border-slate-200/80 bg-white/80 backdrop-blur-md"> <div className="mx-auto flex max-w-3xl items-center justify-between px-4 py-3"> <div className="flex items-center gap-2.5"> <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-violet-600 text-white"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" /> </svg> </span> <span className="text-base font-bold tracking-tight text-slate-900">VideoEncoder</span> </div> <nav className="flex items-center gap-1 rounded-xl bg-slate-100 p-1"> {tabs.map((t) => ( <button key={t.key} onClick={() => setTab(t.key)} className={`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-all ${ tab === t.key ? "bg-white text-violet-700 shadow-sm" : "text-slate-500 hover:text-slate-700" }`}> {t.icon}{t.label} </button> ))} </nav> </div> </header> <main className="mx-auto max-w-3xl px-4 py-8"> {tab === "files" && ( <FilesTab key={filesRefreshKey} onSelectForEncode={handleSelectForEncode} onJobStarted={handleJobStarted} onBatchEncode={handleBatchEncode} initialOpenFolder={openFolderOnReturn} /> )} {tab === "encode" && <EncodeTab preselectedFiles={encodeFiles} onJobStarted={handleJobStarted} />} {tab === "jobs" && <JobsTab onJobDone={handleJobDone} />} {tab === "remote" && ( <RemoteTab onSelectForEncode={handleSelectForEncode} onJobStarted={handleJobStarted} onBatchEncode={handleBatchEncode} /> )} </main> </div> ); } // ─── Remote Tab ─────────────────────────────────────────────────────────────── function RemoteTab({ onSelectForEncode, onJobStarted, onBatchEncode, }: { onSelectForEncode: (f: FileEntry) => void; onJobStarted: () => void; onBatchEncode: (files: FileEntry[]) => void; }) { const [mode, setMode] = useState<"local" | "remote">("local"); const [serverUrl, setServerUrl] = useState("http://bore.pub:5469"); // NOTE: All remote operations go DIRECTLY from the browser to the remote server. // This avoids HuggingFace's server-side network restrictions on outbound ports. const [entries, setEntries] = useState<RemoteEntry[]>([]); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [selected, setSelected] = useState<Set<string>>(new Set()); const [downloadJobs, setDownloadJobs] = useState<string[]>([]); const [toast, setToast] = useState<string | null>(null); const [previewUrl, setPreviewUrl] = useState<string | null>(null); const [previewTitle, setPreviewTitle] = useState<string>(""); const [renamingName, setRenamingName] = useState<string | null>(null); const [renameVal, setRenameVal] = useState(""); const [deleting, setDeleting] = useState<string | null>(null); const [uploading, setUploading] = useState(false); const uploadRef = useRef<HTMLInputElement>(null); const fetchListing = useCallback(async (url: string) => { setLoading(true); setError(null); setSelected(new Set()); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 8000); try { // Direct browser β†’ remote server fetch (bypasses HF network restrictions) const base = url.replace(/\/+$/, ""); const res = await fetch(`${base}/files`, { signal: controller.signal, mode: "cors", }); clearTimeout(timer); if (!res.ok) { setError(`Server returned ${res.status}. Check URL and CORS settings.`); setEntries([]); return; } const data = await res.json() as { name: string; size: number; type: string }[]; const mapped: RemoteEntry[] = data.map((item) => ({ name: String(item.name || ""), isDir: item.type === "folder" || item.type === "directory" || item.type === "dir", size: typeof item.size === "number" ? item.size : parseInt(String(item.size)) || 0, sizeStr: item.type === "folder" || item.type === "directory" ? "-" : (item.size > 0 ? fmt(item.size) : "0 B"), type: item.type, })); setEntries(mapped); } catch (err) { clearTimeout(timer); if (err instanceof Error && err.name === "AbortError") { setError("Connection timed out (8s). Is the server running and reachable from your browser?"); } else if (err instanceof TypeError && err.message.includes("fetch")) { setError("Cannot connect. Check: 1) Server is running, 2) URL is correct, 3) Server allows CORS (Access-Control-Allow-Origin: *)"); } else { setError(err instanceof Error ? err.message : "Failed to connect"); } setEntries([]); } finally { setLoading(false); } }, []); const refresh = useCallback(() => { if (serverUrl.trim()) fetchListing(serverUrl.trim()); }, [serverUrl, fetchListing]); const toggleSelect = (name: string) => { setSelected((prev) => { const next = new Set(prev); if (next.has(name)) next.delete(name); else next.add(name); return next; }); }; // Direct browser download: fetch file from remote, save via our server's download-url proxy const handleDownload = async (entry: RemoteEntry) => { try { const base = serverUrl.trim().replace(/\/+$/, ""); const fileUrl = `${base}/${encodeURIComponent(entry.name)}`; // Use our server as a proxy to download to local storage const { jobId } = await api.startDownloadUrl(fileUrl); setDownloadJobs((prev) => [...prev, jobId]); setToast(`⬇ Downloading ${entry.name} to local storage…`); } catch { setToast("Failed to start download"); } }; const handleBatchDownload = async () => { const fileEntries = entries.filter((e) => !e.isDir && selected.has(e.name)); const base = serverUrl.trim().replace(/\/+$/, ""); for (const entry of fileEntries) { try { const fileUrl = `${base}/${encodeURIComponent(entry.name)}`; const { jobId } = await api.startDownloadUrl(fileUrl); setDownloadJobs((prev) => [...prev, jobId]); } catch { /* skip */ } } setToast(`⬇ Downloading ${fileEntries.length} file(s) to local storage…`); setSelected(new Set()); }; const handleBatchDelete = async () => { const toDelete = entries.filter((e) => selected.has(e.name)); if (!confirm(`Delete ${toDelete.length} item(s) from remote server?`)) return; const base = serverUrl.trim().replace(/\/+$/, ""); let count = 0; for (const entry of toDelete) { try { // Direct browser β†’ remote DELETE /?name=filename const res = await fetch(`${base}/?name=${encodeURIComponent(entry.name)}`, { method: "DELETE", mode: "cors", }); if (res.ok) count++; } catch { /* skip */ } } setToast(`πŸ—‘ Deleted ${count} item(s) from remote`); setSelected(new Set()); refresh(); }; const handleRename = async (oldName: string) => { const newName = renameVal.trim(); if (!newName || newName === oldName) { setRenamingName(null); return; } const base = serverUrl.trim().replace(/\/+$/, ""); try { // Direct browser β†’ remote PUT / with JSON body const res = await fetch(`${base}/`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ old_name: oldName, new_name: newName }), mode: "cors", }); if (res.ok) { setToast(`✏️ Renamed to ${newName}`); refresh(); } else { setToast(`Error: Server returned ${res.status}`); } } catch { setToast("Failed to rename β€” check CORS settings"); } setRenamingName(null); }; const handleDelete = async (name: string) => { if (!confirm(`Delete "${name}" from remote server?`)) return; setDeleting(name); const base = serverUrl.trim().replace(/\/+$/, ""); try { // Direct browser β†’ remote DELETE /?name=filename const res = await fetch(`${base}/?name=${encodeURIComponent(name)}`, { method: "DELETE", mode: "cors", }); if (res.ok) { setToast(`πŸ—‘ Deleted ${name}`); refresh(); } else { setToast(`Error: Server returned ${res.status}`); } } catch { setToast("Failed to delete β€” check CORS settings"); } setDeleting(null); }; const handleUpload = async (fileList: FileList | null) => { if (!fileList || fileList.length === 0) return; setUploading(true); const base = serverUrl.trim().replace(/\/+$/, ""); let count = 0; for (const file of Array.from(fileList)) { try { // Direct browser β†’ remote POST / with FormData field "file" const fd = new FormData(); fd.append("file", file); const res = await fetch(`${base}/`, { method: "POST", body: fd, mode: "cors" }); if (res.ok) count++; else { setToast(`Error uploading ${file.name}: ${res.status}`); } } catch { setToast(`Failed to upload ${file.name} β€” check CORS`); } } setUploading(false); if (count > 0) { setToast(`⬆ Uploaded ${count} file(s) to remote`); refresh(); } if (uploadRef.current) uploadRef.current.value = ""; }; const selectedFiles = entries.filter((e) => !e.isDir && selected.has(e.name)); const selectedDirs = entries.filter((e) => e.isDir && selected.has(e.name)); const getIcon = (entry: RemoteEntry) => { if (entry.isDir) return "πŸ“"; if (isMediaFile(entry.name)) return "🎬"; if (isArchiveFile(entry.name)) return "πŸ“¦"; return "πŸ“„"; }; return ( <div className="space-y-6"> {toast && <Toast message={toast} onDone={() => setToast(null)} />} <section> <h2 className="mb-3 text-sm font-semibold uppercase tracking-widest text-slate-500">Remote / Mounted Storage</h2> <div className="flex flex-wrap gap-2"> <button type="button" onClick={() => setMode("local")} className={`rounded-lg px-3 py-2 text-sm font-semibold transition-colors ${mode === "local" ? "bg-violet-600 text-white" : "border border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`}> Browse mounted storage </button> <button type="button" onClick={() => setMode("remote")} className={`rounded-lg px-3 py-2 text-sm font-semibold transition-colors ${mode === "remote" ? "bg-violet-600 text-white" : "border border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`}> Remote server browser </button> </div> </section> {mode === "local" ? ( <div className="space-y-6"> <div className="rounded-lg border border-slate-200 bg-slate-50 px-4 py-4 text-sm text-slate-700"> <p className="font-semibold text-slate-800">πŸ“¦ Mounted storage bucket</p> <p className="mt-1">This view shows the local storage bucket mounted to the HuggingFace Space. You can browse files in the Downloads and Encoded folders, manage them, and play videos.</p> </div> <FilesTab key="remote-local-files" onSelectForEncode={onSelectForEncode} onJobStarted={onJobStarted} onBatchEncode={onBatchEncode} /> </div> ) : ( <> <input ref={uploadRef} type="file" multiple className="hidden" onChange={(e) => handleUpload(e.target.files)} /> <section> <div className="mb-3 rounded-lg border border-sky-200 bg-sky-50 px-4 py-3 text-xs text-sky-700 space-y-1"> <p className="font-semibold">πŸ’‘ Direct browser connection</p> <p>All requests go directly from your browser to the remote server β€” not through HuggingFace. Your remote server must have <strong>CORS enabled</strong> (respond with <code className="bg-sky-100 px-1 rounded">Access-Control-Allow-Origin: *</code>).</p> <p>Downloads are fetched via our server proxy so files land in your local Files tab.</p> </div> <div className="flex gap-2"> <input type="url" value={serverUrl} onChange={(e) => setServerUrl(e.target.value)} placeholder="http://example.com:8080" onKeyDown={(e) => { if (e.key === "Enter") refresh(); }} className="flex-1 rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> <button onClick={refresh} className="rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 transition-colors"> Connect </button> </div> </section> {downloadJobs.length > 0 && ( <div className="space-y-2"> <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">Downloading to local storage</p> {downloadJobs.map((jid) => ( <DownloadProgress key={jid} jobId={jid} onDone={() => setToast("βœ“ File downloaded to local Files tab")} /> ))} <button onClick={() => setDownloadJobs([])} className="text-xs text-slate-400 hover:text-slate-600 hover:underline"> Clear download history </button> </div> )} {selected.size > 0 && ( <div className="flex flex-wrap items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-4 py-3 shadow-sm"> <span className="flex h-6 w-6 items-center justify-center rounded-full bg-violet-600 text-[11px] font-bold text-white">{selected.size}</span> <span className="text-sm font-semibold text-violet-800">selected</span> <button onClick={() => setSelected(new Set())} className="ml-1 rounded-full p-0.5 text-violet-400 hover:text-violet-700"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> <div className="flex-1" /> {selectedFiles.length > 0 && ( <button onClick={handleBatchDownload} className="flex items-center gap-1.5 rounded-lg bg-sky-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-sky-600 transition-colors"> ⬇ Download ({selectedFiles.length}) </button> )} {selectedDirs.length > 0 && selectedFiles.length === 0 && ( <button onClick={handleBatchDownload} className="flex items-center gap-1.5 rounded-lg bg-amber-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-amber-600 transition-colors"> πŸ“ Download ({selectedDirs.length}) </button> )} <button onClick={handleBatchDelete} className="flex items-center gap-1.5 rounded-lg bg-red-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-600 transition-colors"> πŸ—‘ Delete ({selected.size}) </button> </div> )} <section> <div className="flex items-center justify-between mb-3"> <h2 className="text-sm font-semibold uppercase tracking-widest text-slate-500">Remote Files</h2> <div className="flex items-center gap-2"> <button onClick={() => uploadRef.current?.click()} disabled={uploading} className="flex items-center gap-1.5 rounded-lg border border-violet-300 bg-violet-50 px-3 py-1.5 text-xs font-semibold text-violet-700 hover:bg-violet-100 disabled:opacity-50 transition-colors"> {uploading ? ( <> <svg className="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> Uploading… </> ) : ( <>⬆ Upload to Remote</> )} </button> <button onClick={refresh} className="rounded-lg border border-slate-200 bg-white p-1.5 text-slate-500 hover:bg-slate-50" title="Refresh"> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" /> </svg> </button> </div> </div> {loading ? ( <div className="py-10 text-center text-sm text-slate-400"> <svg className="animate-spin h-6 w-6 mx-auto mb-2 text-violet-500" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> Loading remote files… </div> ) : error ? ( <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-6 text-center"> <p className="text-sm font-medium text-red-600">❌ {error}</p> <p className="text-xs text-red-400 mt-1">Check the server URL and try again</p> </div> ) : entries.length === 0 ? ( <div className="rounded-xl border border-dashed border-slate-200 py-10 text-center text-sm text-slate-400"> No files or folders found. Click Connect to load. </div> ) : ( <div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100"> {entries.map((entry) => ( <div key={entry.name} className={`flex items-center gap-3 px-4 py-3 transition-colors ${ selected.has(entry.name) ? "bg-violet-50" : "hover:bg-slate-50" }`}> <input type="checkbox" className="h-4 w-4 accent-violet-600 rounded flex-shrink-0 cursor-pointer" checked={selected.has(entry.name)} onChange={() => toggleSelect(entry.name)} /> {renamingName === entry.name ? ( <div className="flex-1 flex items-center gap-2"> <span className="text-lg flex-shrink-0">{getIcon(entry)}</span> <input autoFocus value={renameVal} onChange={(e) => setRenameVal(e.target.value)} onBlur={() => handleRename(entry.name)} onKeyDown={(e) => { if (e.key === "Enter") handleRename(entry.name); if (e.key === "Escape") setRenamingName(null); }} className="flex-1 rounded border border-violet-400 px-2 py-0.5 text-sm focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> ) : ( <button onClick={() => toggleSelect(entry.name)} className="flex items-center gap-3 flex-1 min-w-0 text-left"> <span className="text-lg flex-shrink-0">{getIcon(entry)}</span> <div className="flex-1 min-w-0"> <p className={`truncate text-sm font-medium ${entry.isDir ? "text-amber-700" : "text-slate-800"}`}> {entry.name}{entry.isDir ? "/" : ""} </p> {entry.sizeStr && <p className="text-xs text-slate-400 mt-0.5">{entry.sizeStr}</p>} </div> </button> )} <div className="flex items-center gap-0.5 flex-shrink-0"> <IconBtn title="Rename" onClick={() => { setRenamingName(entry.name); setRenameVal(entry.name); }}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125" /> </svg> </IconBtn> {!entry.isDir && isMediaFile(entry.name) && ( <IconBtn title="Play preview" onClick={() => { const base = serverUrl.trim().replace(/\/+$/, ""); setPreviewUrl(`${base}/${encodeURIComponent(entry.name)}`); setPreviewTitle(entry.name); }}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" /> </svg> </IconBtn> )} {!entry.isDir && ( <IconBtn title="Download to local" onClick={() => handleDownload(entry)}> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" /> </svg> </IconBtn> )} <IconBtn title="Delete from remote" onClick={() => handleDelete(entry.name)} danger disabled={deleting === entry.name}> {deleting === entry.name ? ( <svg className="animate-spin h-3.5 w-3.5" fill="none" viewBox="0 0 24 24"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" /> </svg> ) : ( <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /> </svg> )} </IconBtn> </div> </div> ))} </div> )} </section> </> )} {previewUrl && ( <PreviewModal title={previewTitle} url={previewUrl} onClose={() => setPreviewUrl(null)} /> )} </div> ); }
import { useCallback, useEffect, useRef, useState } from "react";
// ─── Types ────────────────────────────────────────────────────────────────────
interface FileEntry {
id: string;
name: string;
relativePath: string;
sizeBytes: number;
source: "downloaded" | "encoded";
createdAt: number;
folder: string;
}
interface Job {
id: string;
createdAt: number;
status: "running" | "done" | "failed" | "stopped";
settings: Record<string, unknown>;
batchIndex: number | null;
batchTotal: number | null;
outputFolder: string;
outputSource: string;
progress: {
percent: number;
fps: number;
etaSeconds: number;
sizeOutBytes: number;
log: string[];
};
}
interface DownloadJob {
id: string;
status: "running" | "done" | "failed" | "stopped";
url: string;
filename: string | null;
bytesDownloaded: number;
totalBytes: number;
error: string | null;
}
interface VideoInfo {
fileSize: string;
fileSizeBytes: number;
duration: string;
durationSeconds: number;
video: {
codec: string;
profile: string | null;
resolution: string;
width: number;
height: number;
frameRate: string;
bitrate: string;
bitrateRaw: number;
pixFmt: string;
streamSize: string;
} | null;
audio: {
codec: string;
sampleRate: string;
channels: number | string;
channelLayout: string;
bitrate: string;
bitrateRaw: number;
streamSize: string;
} | null;
encodeSettings?: {
createdAt?: number;
inputFilename?: string;
outputFilename?: string;
resolution?: string;
settings?: Record<string, unknown>;
} | null;
}
type Tab = "files" | "encode" | "jobs" | "remote";
interface RemoteEntry {
name: string;
isDir: boolean;
size?: number;
sizeStr?: string;
type?: string;
}
interface PixeldrainJob {
id: string;
status: "running" | "done" | "failed";
filename: string;
bytesUploaded: number;
totalBytes: number;
pixeldrainUrl: string | null;
error: string | null;
}
interface QueueItem {
uid: string;
file: FileEntry;
status: "waiting" | "encoding" | "done" | "failed";