telev / src /App.tsx
mozolla's picture
Upload 34 files
9df6ae5 verified
Raw History Blame Contribute Delete
331 kB
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { InputHTMLAttributes } from "react"; import type { FileEntry, Job, DownloadJob, VideoInfo, RemoteEntry, TeleboxEntry, BackblazeEntry, Tab, PixeldrainJob, QueueItem, EncodePreset, RemoteCredentials } from "./types"; import { api } from "./api"; import { CloseIcon, FolderIcon, DownloadIcon, UploadIcon, EditIcon, DeleteIcon, DragHandleIcon, ChevronUpIcon, ChevronDownIcon, SpinnerIcon, ListIcon, SelectAllIcon, ClearIcon } from "./icons"; import { AdvancedTrimCropModal } from "./components/AdvancedTrimCropModal"; import { CredentialsModal } from "./components/Modals"; import { normalizeRemoteUrl } from "./utils/credentials"; // ─── 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 formatAspectRatio(width: number, height: number): string { const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b)); const divisor = gcd(width, height); return `${width / divisor}:${height / divisor}`; } 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 parseLooseTimeToSeconds(input: string): number | null { const value = input.trim(); if (!value) return null; const parts = value.split(":").map((p) => p.trim()); if (parts.some((p) => p === "" || Number.isNaN(Number(p)))) return null; if (parts.length === 2) { const [mm, ss] = parts.map(Number); if (mm < 0 || ss < 0 || ss >= 60) return null; return mm * 60 + ss; } if (parts.length === 3) { const [hh, mm, ss] = parts.map(Number); if (hh < 0 || mm < 0 || ss < 0 || mm >= 60 || ss >= 60) return null; return hh * 3600 + mm * 60 + ss; } return null; } function parsePastedSegments(text: string): { start: string; end: string }[] { const lines = text .split(/\r?\n/) .map((line) => line.trim()) .filter(Boolean); const parsed: { start: string; end: string }[] = []; for (const line of lines) { const match = line.match(/(\d{1,2}:\d{2}(?::\d{2})?)\s*-\s*(\d{1,2}:\d{2}(?::\d{2})?)/); if (!match) continue; const startSec = parseLooseTimeToSeconds(match[1]); const endSec = parseLooseTimeToSeconds(match[2]); if (startSec == null || endSec == null || endSec <= startSec) continue; parsed.push({ start: secondsToHms(startSec), end: secondsToHms(endSec), }); } return parsed; } type CropValues = { cropEnabled: boolean; cropLeft: number; cropRight: number; cropTop: number; cropBottom: number; }; type DirectoryInputProps = InputHTMLAttributes<HTMLInputElement> & { webkitdirectory?: string; mozdirectory?: string; }; 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) }); 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); 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; } 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> ); } // ─── Upload Area ────────────────────────────────────────────────────────────── // Helper to recursively read directory entries from drag-and-drop async function* getFilesFromDataTransferItems(items: DataTransferItemList, prefix = ""): AsyncGenerator<File & { __folderPath?: string }> { for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.kind === "file") { const entry = item.webkitGetAsEntry?.(); if (entry?.isFile) { const file = item.getAsFile(); if (file) { if (prefix) { (file as any).__folderPath = prefix; } yield file as File & { __folderPath?: string }; } } else if (entry?.isDirectory) { // Pass the directory name as the initial prefix yield* readDirectoryRecursive(entry as any, entry.name); } } } } async function* readDirectoryRecursive(dir: any, prefix = ""): AsyncGenerator<File & { __folderPath?: string }> { const reader = dir.createReader(); const entries = await new Promise<any[]>((resolve, reject) => { reader.readEntries(resolve, reject); }); for (const entry of entries) { const newPrefix = prefix ? `${prefix}/${entry.name}` : entry.name; if (entry.isFile) { const file = await new Promise<File>((resolve, reject) => { (entry as any).file(resolve, reject); }); (file as any).__folderPath = prefix; yield file as File & { __folderPath?: string }; } else if (entry.isDirectory) { yield* readDirectoryRecursive(entry, newPrefix); } } } function UploadArea({ onFilesSelected, busy, dragOver, onDragOver, onDragLeave, uploadInputRef, uploadFolderRef, }: { onFilesSelected: (files: FileList | (File & { __folderPath?: string })[]) => void; busy: boolean; dragOver: boolean; onDragOver: (e: React.DragEvent) => void; onDragLeave: (e: React.DragEvent) => void; uploadInputRef: React.RefObject<HTMLInputElement | null>; uploadFolderRef: React.RefObject<HTMLInputElement | null>; }) { const handleDrop = async (e: React.DragEvent) => { e.preventDefault(); onDragLeave(e); if (e.dataTransfer.items?.length) { try { // Try to read directory structure from drag-and-drop const allFiles: (File & { __folderPath?: string })[] = []; for await (const file of getFilesFromDataTransferItems(e.dataTransfer.items)) { allFiles.push(file); } if (allFiles.length > 0) { onFilesSelected(allFiles); } else if (e.dataTransfer.files) { onFilesSelected(e.dataTransfer.files); } } catch (err) { console.error("Error reading drag-and-drop items:", err); if (e.dataTransfer.files) { onFilesSelected(e.dataTransfer.files); } } } else if (e.dataTransfer.files) { onFilesSelected(e.dataTransfer.files); } }; return ( <div onDragOver={onDragOver} onDragLeave={onDragLeave} onDrop={handleDrop} className={`rounded-lg border-2 border-dashed p-4 text-center transition-colors ${ dragOver ? "border-violet-400 bg-violet-50" : "border-slate-300 bg-slate-50 hover:border-slate-400" } ${busy ? "opacity-60 cursor-not-allowed" : "cursor-pointer"}`} > <div className="text-sm font-semibold text-slate-600 mb-2"> {busy ? "Uploading..." : "Drop files or folders here"} </div> <div className="flex gap-2 justify-center flex-wrap"> <button type="button" onClick={() => uploadInputRef.current?.click()} disabled={busy} className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors" > Select Files </button> <button type="button" onClick={() => uploadFolderRef.current?.click()} disabled={busy} className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors" > Select Folder </button> </div> <input ref={uploadInputRef} type="file" multiple onChange={(e) => e.target.files && onFilesSelected(e.target.files)} className="hidden" disabled={busy} /> <input {...({ ref: uploadFolderRef, type: "file", webkitdirectory: "true", mozdirectory: "true", multiple: true, onChange: (e) => e.target.files && onFilesSelected(e.target.files), className: "hidden", disabled: busy, } as DirectoryInputProps)} /> </div> ); } // ─── Pixeldrain Upload Progress ─────────────────────────────────────────────── function PixeldrainProgress({ jobId, onClose }: { jobId: string; onClose: () => void }) { const [job, setJob] = useState<PixeldrainJob | null>(null); const [copied, setCopied] = useState(false); const pollInProgressRef = useRef(false); useEffect(() => { const poll = async () => { // Prevent concurrent requests if (pollInProgressRef.current) return; pollInProgressRef.current = true; 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 */ } finally { pollInProgressRef.current = false; } }; poll(); // Increased polling interval from 800ms to 1500ms to reduce server load const iv = setInterval(poll, 1500); 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(() => { const firstFile = files[0]; if (!firstFile) { setOutName("merged_output.mkv"); return; } const name = firstFile.name; const lastDotIndex = name.lastIndexOf("."); if (lastDotIndex > 0) { const baseName = name.slice(0, lastDotIndex); const ext = name.slice(lastDotIndex); setOutName(`$${baseName}_merged$${ext}`); } else { setOutName(`${name}_merged.mkv`); } }, [files]); 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> ); } // ─── 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={`inline-flex items-center justify-center rounded-md p-1 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.audioStreams && info.audioStreams.length > 0 && ( <div> <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2"> Audio Streams ({info.audioStreams.length}) </h3> <div className="space-y-2"> {info.audioStreams.map((stream, i) => ( <div key={i} className="rounded-xl bg-slate-50 px-4 py-3"> <div className="mb-2 text-[11px] font-semibold text-slate-500"> Audio #{stream.index} </div> <Row label="Codec" value={stream.codec || "unknown"} /> <Row label="Language" value={stream.language || "unknown"} /> <Row label="Title" value={stream.title || "β€”"} /> <Row label="Channels" value={`${stream.channels}${stream.channelLayout && stream.channelLayout !== "unknown" ? ` (${stream.channelLayout})` : ""}`} /> <Row label="Sample Rate" value={stream.sampleRate || "unknown"} /> <Row label="Bitrate" value={stream.bitrate || "unknown"} /> <Row label="Stream Size" value={stream.streamSize || "unknown"} /> </div> ))} </div> </div> )} {info.subtitleStreams && info.subtitleStreams.length > 0 && ( <div> <h3 className="text-xs font-bold uppercase tracking-widest text-violet-600 mb-2"> Subtitle Streams ({info.subtitleStreams.length}) </h3> <div className="space-y-2"> {info.subtitleStreams.map((stream, i) => ( <div key={i} className="rounded-xl bg-slate-50 px-4 py-3"> <div className="mb-2 text-[11px] font-semibold text-slate-500"> Subtitle #{stream.index} </div> <Row label="Codec" value={stream.codec || "unknown"} /> <Row label="Language" value={stream.language || "unknown"} /> <Row label="Title" value={stream.title || "β€”"} /> <Row label="Default" value={stream.default ? "Yes" : "No"} /> <Row label="Forced" value={stream.forced ? "Yes" : "No"} /> </div> ))} </div> </div> )} {!info.video && !info.audio && (!info.audioStreams || info.audioStreams.length === 0) && (!info.subtitleStreams || info.subtitleStreams.length === 0) && ( <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 }) { const videoRef = useRef<HTMLVideoElement>(null); const [seekStep, setSeekStep] = useState(6); const seek = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; useEffect(() => { const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seek(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seek(seekStep); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [seekStep]); 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 ref={videoRef} className="w-full max-h-[70vh] rounded-3xl bg-black" controls playsInline src={url} /> <div className="mt-3 flex flex-wrap items-center justify-between gap-3"> <div className="flex items-center gap-2"> <button onClick={() => seek(-seekStep)} className="rounded-full bg-slate-800 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700 transition-colors" > βˆ’{seekStep}s </button> <button onClick={() => seek(seekStep)} className="rounded-full bg-slate-800 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700 transition-colors" > +{seekStep}s </button> <label className="flex items-center gap-1.5 text-xs text-slate-400"> Step: <input type="number" min={1} max={600} value={seekStep} onChange={(e) => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))} className="w-14 rounded bg-slate-800 border border-slate-700 px-2 py-1 text-white text-xs text-center" /> s </label> </div> <div className="flex items-center 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> </div> ); } // ─── Crop Modal ───────────────────────────────────────────────────────────── function CropModal({ file, onClose, onDone }: { file: FileEntry; onClose: () => void; onDone: (values: CropValues) => void; }) { const videoRef = useRef<HTMLVideoElement>(null); const [cropEnabled, setCropEnabled] = useState(false); const [cropLeft, setCropLeft] = useState(0); const [cropRight, setCropRight] = useState(0); const [cropTop, setCropTop] = useState(0); const [cropBottom, setCropBottom] = useState(0); const [seekStep, setSeekStep] = useState(6); const [isVideoPlaying, setIsVideoPlaying] = useState(false); const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number } | null>(null); const [zoomLevel, setZoomLevel] = useState(100); const [dragAnchor, setDragAnchor] = useState<{ x: number; y: number; left: number; right: number; top: number; bottom: number } | null>(null); const applyPreset = (preset: "lt" | "rt" | "up" | "low") => { const map: Record<typeof preset, CropValues> = { lt: { cropEnabled: true, cropLeft: 20, cropRight: 20, cropTop: 10, cropBottom: 10 }, rt: { cropEnabled: true, cropLeft: 10, cropRight: 20, cropTop: 10, cropBottom: 10 }, up: { cropEnabled: true, cropLeft: 10, cropRight: 10, cropTop: 20, cropBottom: 10 }, low: { cropEnabled: true, cropLeft: 10, cropRight: 10, cropTop: 10, cropBottom: 20 }, }; updateFromValues(map[preset]); }; const updateFromValues = (values: CropValues) => { setCropEnabled(values.cropEnabled); setCropLeft(values.cropLeft); setCropRight(values.cropRight); setCropTop(values.cropTop); setCropBottom(values.cropBottom); }; useEffect(() => { // First check localStorage const saved = localStorage.getItem(`crop-${file.id}`); if (saved) { try { updateFromValues(JSON.parse(saved)); return; // Use localStorage if found } catch {} } // Then check server for savedCropSettings (from .crop.json sidecar) api.getFileInfo(file.id).then((res) => { if (res.ok && res.info?.savedCropSettings) { const s = res.info.savedCropSettings; updateFromValues({ cropEnabled: Boolean(s.cropEnabled), cropLeft: Number(s.cropLeft ?? 0), cropRight: Number(s.cropRight ?? 0), cropTop: Number(s.cropTop ?? 0), cropBottom: Number(s.cropBottom ?? 0), }); } }).catch(() => {}); // Ignore errors }, [file.id]); const handleDone = () => { const values = { cropEnabled, cropLeft, cropRight, cropTop, cropBottom }; try { localStorage.setItem(`crop-${file.id}`, JSON.stringify(values)); } catch {} onDone(values); }; const cropOutputSize = useMemo(() => { if (!videoDimensions) return null; const width = Math.max(1, Math.round(videoDimensions.width * (1 - (cropLeft + cropRight) / 100))); const height = Math.max(1, Math.round(videoDimensions.height * (1 - (cropTop + cropBottom) / 100))); return { width, height }; }, [videoDimensions, cropLeft, cropRight, cropTop, cropBottom]); const seekVideo = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; const togglePlayback = () => { const v = videoRef.current; if (!v) return; if (v.paused) { void v.play(); setIsVideoPlaying(true); } else { v.pause(); setIsVideoPlaying(false); } }; const centerCrop = () => { setCropEnabled(true); setCropLeft(10); setCropRight(10); setCropTop(10); setCropBottom(10); }; const adjustZoom = (delta: number) => { setZoomLevel((prev) => Math.max(50, Math.min(200, prev + delta))); }; const handleCropPointerDown = (event: React.PointerEvent<HTMLDivElement>) => { if (!cropEnabled) return; event.preventDefault(); event.currentTarget.setPointerCapture(event.pointerId); setDragAnchor({ x: event.clientX, y: event.clientY, left: cropLeft, right: cropRight, top: cropTop, bottom: cropBottom, }); }; const handleCropPointerMove = (event: React.PointerEvent<HTMLDivElement>) => { if (!dragAnchor) return; const rect = event.currentTarget.getBoundingClientRect(); const deltaX = ((event.clientX - dragAnchor.x) / rect.width) * 100; const deltaY = ((event.clientY - dragAnchor.y) / rect.height) * 100; const nextLeft = Math.max(0, Math.min(45, dragAnchor.left + deltaX)); const nextRight = Math.max(0, Math.min(45, dragAnchor.right - deltaX)); const nextTop = Math.max(0, Math.min(45, dragAnchor.top + deltaY)); const nextBottom = Math.max(0, Math.min(45, dragAnchor.bottom - deltaY)); setCropLeft(nextLeft); setCropRight(nextRight); setCropTop(nextTop); setCropBottom(nextBottom); }; const handleCropPointerUp = (event: React.PointerEvent<HTMLDivElement>) => { if (dragAnchor) { event.currentTarget.releasePointerCapture(event.pointerId); setDragAnchor(null); } }; useEffect(() => { const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [seekStep]); return ( <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/45 p-4 backdrop-blur-sm" onClick={onClose}> <div className="w-full max-w-3xl overflow-hidden rounded-3xl bg-white shadow-2xl" onClick={(e) => e.stopPropagation()}> <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4"> <div> <h2 className="text-sm font-bold text-slate-900">Crop preview</h2> <p className="text-xs text-slate-500">Trim the visible area from the left, right, top, and bottom before encoding.</p> </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="grid gap-5 p-5 lg:grid-cols-[1.2fr_0.8fr]"> <div className="space-y-3"> <div className="relative overflow-hidden rounded-2xl border border-slate-200 bg-slate-950"> <div className="overflow-hidden rounded-2xl" style={{ transform: `scale(${zoomLevel / 100})`, transformOrigin: "center center" }}> <video ref={videoRef} src={`/api/files/${encodeURIComponent(file.id)}/stream`} controls playsInline className="w-full rounded-2xl bg-black" onPlay={() => setIsVideoPlaying(true)} onPause={() => setIsVideoPlaying(false)} onEnded={() => setIsVideoPlaying(false)} onLoadedMetadata={() => { const video = videoRef.current; if (video) { setVideoDimensions({ width: video.videoWidth || 0, height: video.videoHeight || 0 }); } }} /> </div> <div className="absolute inset-0"> <div className="absolute inset-0 rounded-2xl bg-black/55" /> <div className={`absolute rounded-xl border-2 border-white/90 shadow-[0_0_0_9999px_rgba(0,0,0,0.55)] transition-[top,bottom,left,right] duration-75 ${cropEnabled ? "cursor-move" : "cursor-default"}`} style={{ top: `${cropTop}%`, bottom: `${cropBottom}%`, left: `${cropLeft}%`, right: `${cropRight}%`, }} onPointerDown={handleCropPointerDown} onPointerMove={handleCropPointerMove} onPointerUp={handleCropPointerUp} onPointerCancel={handleCropPointerUp} /> </div> </div> <div className="flex flex-wrap items-center gap-2"> <button type="button" onClick={togglePlayback} className="rounded-full bg-slate-900 px-3 py-1.5 text-sm font-semibold text-white hover:bg-slate-700" > {isVideoPlaying ? "Pause" : "Play"} </button> <button type="button" onClick={() => adjustZoom(-10)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > βˆ’ Zoom </button> <button type="button" onClick={() => adjustZoom(10)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > + Zoom </button> <button type="button" onClick={() => setZoomLevel(100)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > Reset zoom </button> <span className={`rounded-full px-2.5 py-1 text-xs font-semibold ${zoomLevel === 100 ? "bg-slate-100 text-slate-600" : "bg-violet-100 text-violet-700"}`}> {zoomLevel === 100 ? "100% (default)" : `${zoomLevel}%`} </span> <button type="button" onClick={centerCrop} className="rounded-full bg-violet-600 px-3 py-1.5 text-sm font-semibold text-white hover:bg-violet-700" > Center crop </button> <button type="button" onClick={() => seekVideo(-seekStep)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > βˆ’{seekStep}s </button> <button type="button" onClick={() => seekVideo(seekStep)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > +{seekStep}s </button> <label className="flex items-center gap-1.5 text-xs text-slate-500"> Step: <input type="number" min={1} max={600} value={seekStep} onChange={(e) => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))} className="w-14 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs text-center" /> s </label> </div> <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-xs text-slate-500"> <p className="font-semibold text-slate-700">Preview</p> <p className="mt-1">The visible rectangle updates as you adjust the crop values. Drag the highlighted box directly in the preview or use the sliders and the play/seek controls while you crop.</p> {cropOutputSize && ( <div className="mt-2 flex flex-wrap gap-2"> <span className="rounded-full bg-white px-2.5 py-1 font-semibold text-slate-700">Output: {cropOutputSize.width}Γ—{cropOutputSize.height}</span> <span className="rounded-full bg-white px-2.5 py-1 font-semibold text-slate-700">Aspect: {formatAspectRatio(cropOutputSize.width, cropOutputSize.height)}</span> </div> )} </div> </div> <div className="space-y-4"> <label className="flex items-center justify-between rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700"> <span>Enable crop</span> <input type="checkbox" checked={cropEnabled} onChange={(e) => setCropEnabled(e.target.checked)} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> </label> <div className="space-y-3 rounded-2xl border border-slate-200 bg-white p-3"> <div className="flex flex-wrap gap-2"> {([ ["lt", "LT"], ["rt", "RT"], ["up", "UP"], ["low", "LOW"], ] as const).map(([key, label]) => ( <button key={key} type="button" onClick={() => applyPreset(key)} disabled={!cropEnabled} className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-50" > {label} </button> ))} </div> {[ { key: "cropLeft", label: "Left", value: cropLeft, setter: setCropLeft }, { key: "cropRight", label: "Right", value: cropRight, setter: setCropRight }, { key: "cropTop", label: "Top", value: cropTop, setter: setCropTop }, { key: "cropBottom", label: "Bottom", value: cropBottom, setter: setCropBottom }, ].map((field) => ( <div key={field.key} className="space-y-1.5"> <div className="flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-slate-500"> <span>{field.label}</span> <span>{field.value}%</span> </div> <input type="range" min={0} max={45} step={1} value={field.value} disabled={!cropEnabled} onChange={(e) => field.setter(Number(e.target.value))} className="w-full accent-violet-600 disabled:cursor-not-allowed disabled:opacity-60" /> </div> ))} </div> <div className="flex flex-wrap gap-2"> <button type="button" onClick={() => { setCropEnabled(false); setCropLeft(0); setCropRight(0); setCropTop(0); setCropBottom(0); }} className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">Reset</button> <button type="button" onClick={handleDone} className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700">Done</button> </div> </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[]>([]); const [activeSegmentId, setActiveSegmentId] = useState(""); const [outName, setOutName] = useState(""); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const [pasteText, setPasteText] = useState(""); const videoRef = useRef<HTMLVideoElement>(null); const [previewCurrentTime, setPreviewCurrentTime] = useState(0); const [pendingClipStart, setPendingClipStart] = useState<number | null>(null); const [seekStep, setSeekStep] = useState(6); const seekVideo = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; useEffect(() => { const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [seekStep]); useEffect(() => { api.getFileInfo(file.id).then((res) => { if (res.ok && res.info.durationSeconds) { const d = res.info.durationSeconds; setDuration(d); } }).finally(() => setLoading(false)); const ext = file.name.match(/(\.[^.]+)$/)?.[1] || ""; const base = file.name.replace(/(\.[^.]+)$/, ""); setOutName(`${base}_trim${ext}`); }, [file]); useEffect(() => { if (segments.length && !segments.some((segment) => segment.id === activeSegmentId)) { setActiveSegmentId(segments[0].id); } if (!segments.length && activeSegmentId) { setActiveSegmentId(""); } }, [segments, activeSegmentId]); const activeSegment = segments.find((segment) => segment.id === activeSegmentId) || segments[0] || null; const startSec = activeSegment ? hmsToSeconds(activeSegment.start) : 0; const endSec = activeSegment ? hmsToSeconds(activeSegment.end) : 0; 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)) : lastEnd; const newSegment = { id, start: secondsToHms(nextStart), end: secondsToHms(nextStart) }; 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 handlePasteImport = () => { const parsed = parsePastedSegments(pasteText); if (!parsed.length) { setError("No valid clip ranges found in pasted text"); return; } if (duration) { for (const seg of parsed) { if (hmsToSeconds(seg.end) > duration) { setError("One or more pasted segments exceed the file duration"); return; } } } const nextSegments = parsed.map((seg) => ({ id: `seg_${Math.random().toString(16).slice(2)}`, start: seg.start, end: seg.end, })); setSegments(nextSegments); setActiveSegmentId(nextSegments[0].id); setError(null); }; const captureClipStart = () => { const t = Math.floor(videoRef.current?.currentTime ?? 0); setPreviewCurrentTime(t); setPendingClipStart(t); setError(null); }; const captureClipEnd = () => { const t = Math.floor(videoRef.current?.currentTime ?? 0); setPreviewCurrentTime(t); if (pendingClipStart == null) { setError("Set clip start first."); return; } if (t <= pendingClipStart) { setError("Clip end must be after clip start."); return; } const seg = { id: `seg_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`, start: secondsToHms(pendingClipStart), end: secondsToHms(t), }; setSegments((prev) => [...prev, seg]); setActiveSegmentId(seg.id); setPendingClipStart(null); setError(null); }; const undoLastCapturedClip = () => { setSegments((prev) => { if (!prev.length) return prev; const next = prev.slice(0, -1); setActiveSegmentId(next.length ? next[next.length - 1].id : ""); return next; }); setError(null); }; const clearCapturedClips = () => { setSegments([]); setActiveSegmentId(""); setPendingClipStart(null); setError(null); }; 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"> <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col"> <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> {/* ── Always-visible OSD bar ── */} {!loading && ( <div className="flex-shrink-0 flex flex-wrap items-center gap-x-5 gap-y-1 px-5 py-2 border-b border-slate-100 bg-slate-50 text-xs text-slate-600"> <span> <span className="font-semibold">Duration:</span>{" "} {duration != null ? secondsToHms(Math.floor(duration)) : "β€”"} </span> <span> <span className="font-semibold">Current:</span>{" "} {secondsToHms(Math.floor(previewCurrentTime))} </span> <span> <span className="font-semibold">Pending start:</span>{" "} {pendingClipStart == null ? "β€”" : secondsToHms(Math.floor(pendingClipStart))} </span> </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> ) : ( <> {/* ── Video player + seek + set start/end ── */} <div className="space-y-3"> <video ref={videoRef} src={`/api/files/${encodeURIComponent(file.id)}/stream`} controls className="w-full rounded-2xl border border-slate-200 bg-black" onTimeUpdate={() => setPreviewCurrentTime(Math.floor(videoRef.current?.currentTime ?? 0))} onLoadedMetadata={() => setPreviewCurrentTime(Math.floor(videoRef.current?.currentTime ?? 0))} /> <div className="flex items-center gap-2"> <button type="button" onClick={() => seekVideo(-seekStep)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > βˆ’{seekStep}s </button> <button type="button" onClick={() => seekVideo(seekStep)} className="rounded-full bg-slate-100 px-3 py-1.5 text-sm font-semibold text-slate-700 hover:bg-slate-200" > +{seekStep}s </button> <label className="flex items-center gap-1.5 text-xs text-slate-500"> Step: <input type="number" min={1} max={600} value={seekStep} onChange={(e) => setSeekStep(Math.max(1, parseInt(e.target.value) || 6))} className="w-14 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs text-center" /> s </label> </div> <div className="rounded-xl border border-slate-200 bg-slate-50 p-3"> <div className="flex flex-wrap gap-2"> <button type="button" onClick={captureClipStart} className="rounded-full bg-violet-600 px-3 py-2 text-sm font-semibold text-white hover:bg-violet-700" > Set Start </button> <button type="button" onClick={captureClipEnd} className="rounded-full bg-emerald-600 px-3 py-2 text-sm font-semibold text-white hover:bg-emerald-700" > Set End </button> <button type="button" onClick={undoLastCapturedClip} className="rounded-full bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200" > Undo Last Clip </button> <button type="button" onClick={clearCapturedClips} className="rounded-full bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200" > Clear Clips </button> </div> <p className="mt-3 text-xs text-slate-500"> While previewing: click Set Start, then Set End. Each start/end pair is added automatically as a new clip. </p> </div> </div> {/* ── Paste clip list ── */} <div className="space-y-2 rounded-xl border border-slate-200 bg-slate-50 p-3"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Paste clip list </label> <textarea value={pasteText} onChange={(e) => setPasteText(e.target.value)} placeholder={`Clip 1: 08:56 - 12:22 Clip 2: 17:05 - 22:49 Clip 3: 28:19 - 33:02 Clip 4: 39:49 - 42:57`} className="min-h-[120px] 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" /> <div className="flex items-center justify-between gap-2"> <span className="text-xs text-slate-500"> Supports mm:ss or hh:mm:ss per line. </span> <button type="button" onClick={handlePasteImport} className="rounded-lg bg-violet-600 px-3 py-2 text-sm font-semibold text-white hover:bg-violet-700" > Import clips </button> </div> </div> {/* ── Segments list ── */} {segments.length > 0 && ( <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} onClick={() => setActiveSegmentId(segment.id)} className={`rounded-2xl border px-4 py-3 cursor-pointer ${ isActive ? "border-violet-300 bg-violet-50" : "border-slate-200 bg-white" }`} > <div className="flex items-center justify-between gap-2"> <div className="flex-1 min-w-0"> <div className="flex items-center gap-2"> <span className="text-xs font-semibold text-slate-700"> {segment.start} β†’ {segment.end} </span> <span className="text-xs text-slate-400"> ({secondsToHms(Math.floor(segmentLen))}) </span> </div> </div> <div className="flex items-center gap-1"> <button type="button" onClick={(e) => { e.stopPropagation(); moveSegment(idx, -1); }} disabled={idx === 0} className="rounded p-1 text-slate-400 hover:text-slate-600 disabled:opacity-30" title="Move up" > ↑ </button> <button type="button" onClick={(e) => { e.stopPropagation(); moveSegment(idx, 1); }} disabled={idx === segments.length - 1} className="rounded p-1 text-slate-400 hover:text-slate-600 disabled:opacity-30" title="Move down" > ↓ </button> <button type="button" onClick={(e) => { e.stopPropagation(); removeSegment(segment.id); }} className="rounded p-1 text-slate-400 hover:text-red-600" title="Remove segment" > βœ• </button> </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() || !segments.length} 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(() => { let iv: number | undefined; const poll = async () => { try { const data = await api.getDownloadJob(jobId); setJob(data.job); if (data.job.status !== "running") { if (iv) window.clearInterval(iv); // Only auto-dismiss on success; failures stay visible until user dismisses if (data.job.status === "done" && !doneRef.current) { doneRef.current = true; onDone?.(); } } } catch { if (iv) window.clearInterval(iv); } }; poll(); iv = window.setInterval(poll, 1000); return () => { if (iv) window.clearInterval(iv); }; }, [jobId, onDone]); if (!job) return null; const pct = job.totalBytes > 0 ? Math.min(100, (job.bytesDownloaded / job.totalBytes) * 100) : null; const finished = job.status !== "running"; return ( <div className={`rounded-2xl border bg-white/90 p-4 shadow-sm backdrop-blur ${job.status === "failed" ? "border-red-200" : "border-slate-200"}`}> <div className="mb-2 flex items-center justify-between gap-3"> <div className="min-w-0"> <p className="truncate text-sm font-semibold text-slate-800">{job.filename || "Downloading…"}</p> <p className="truncate text-xs text-slate-500">{job.url}</p> </div> <Badge color={ job.status === "done" ? "bg-emerald-100 text-emerald-700" : job.status === "failed" ? "bg-red-100 text-red-700" : job.status === "stopped" ? "bg-slate-200 text-slate-700" : "bg-violet-100 text-violet-700" }> {job.status} </Badge> </div> <div className="mb-2 h-2 overflow-hidden rounded-full bg-slate-100"> {pct == null ? ( <div className="h-full w-1/3 animate-pulse rounded-full bg-violet-500" /> ) : ( <div className={`h-full rounded-full transition-all ${job.status === "failed" ? "bg-red-400" : "bg-violet-500"}`} style={{ width: `${pct}%` }} /> )} </div> <div className="flex items-center justify-between text-xs text-slate-500"> <span> {fmt(job.bytesDownloaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""} {job.status === "running" && job.speedBytesPerSec && job.speedBytesPerSec > 0 ? <span className="ml-2 text-violet-500 font-medium">{fmt(job.speedBytesPerSec)}/s</span> : null} </span> <span className="flex items-center gap-1.5"> {job.useAria2 && job.status === "running" && ( <span className="rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-700">⚑ aria2c</span> )} {pct == null ? "…" : `${pct.toFixed(1)}%`} </span> </div> {job.error && <p className="mt-2 text-xs text-red-500">{job.error}</p>} {finished && ( <div className="mt-3 flex justify-end gap-2"> {job.status === "running" && ( <button onClick={() => api.stopDownloadJob(job.id)} className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50" > Stop </button> )} <button onClick={() => onDone?.()} className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50" > Dismiss </button> </div> )} {!finished && ( <div className="mt-3 flex justify-end"> <button onClick={() => api.stopDownloadJob(job.id)} className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50" > Stop </button> </div> )} </div> ); } // ─── Remote Download Progress Bar ───────────────────────────────────────────── function RemoteDownloadProgress({ jobId, onDone }: { jobId: string; onDone?: () => void }) { const [job, setJob] = useState<DownloadJob | null>(null); const doneRef = useRef(false); useEffect(() => { let iv: number | undefined; const poll = async () => { try { const data = await api.getRemoteDownloadJob(jobId); setJob(data.job); if (data.job.status !== "running") { if (iv) window.clearInterval(iv); if (!doneRef.current) { doneRef.current = true; onDone?.(); } } } catch { if (iv) window.clearInterval(iv); } }; poll(); iv = window.setInterval(poll, 1000); return () => { if (iv) window.clearInterval(iv); }; }, [jobId, onDone]); if (!job) return null; const pct = job.totalBytes > 0 ? Math.min(100, (job.bytesDownloaded / job.totalBytes) * 100) : null; return ( <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm backdrop-blur"> <div className="mb-2 flex items-center justify-between gap-3"> <div className="min-w-0"> <p className="truncate text-sm font-semibold text-slate-800">{job.filename || "Downloading…"}</p> <p className="truncate text-xs text-slate-500">{job.url}</p> </div> <Badge color={ job.status === "done" ? "bg-emerald-100 text-emerald-700" : job.status === "failed" ? "bg-red-100 text-red-700" : job.status === "stopped" ? "bg-slate-200 text-slate-700" : "bg-violet-100 text-violet-700" }> {job.status} </Badge> </div> <div className="mb-2 h-2 overflow-hidden rounded-full bg-slate-100"> {pct == null ? ( <div className="h-full w-1/3 animate-pulse rounded-full bg-violet-500" /> ) : ( <div className="h-full rounded-full bg-violet-500 transition-all" style={{ width: `${pct}%` }} /> )} </div> <div className="flex items-center justify-between text-xs text-slate-500"> <span>{fmt(job.bytesDownloaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""}</span> <span>{pct == null ? "…" : `${pct.toFixed(1)}%`}</span> </div> {job.error && <p className="mt-2 text-xs text-red-500">{job.error}</p>} {job.status === "running" && ( <div className="mt-3 flex justify-end"> <button onClick={() => api.stopRemoteDownloadJob(job.id)} className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50" > Stop </button> </div> )} </div> ); } // ─── Upload Progress ────────────────────────────────────────────────────────── function UploadProgress({ progress, onClose }: { progress: { bytesUploaded: number; totalBytes: number; fileCount: number; startTime: number } | null; onClose: () => void }) { const [stats, setStats] = useState<{ speed: number; eta: number }>({ speed: 0, eta: 0 }); useEffect(() => { if (!progress) return; const elapsed = (Date.now() - progress.startTime) / 1000; if (elapsed > 0) { const speed = progress.bytesUploaded / elapsed; const remaining = progress.totalBytes - progress.bytesUploaded; const eta = speed > 0 ? remaining / speed : 0; setStats({ speed, eta }); } }, [progress]); if (!progress) return null; const pct = progress.totalBytes > 0 ? Math.min(100, (progress.bytesUploaded / progress.totalBytes) * 100) : 0; return ( <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm backdrop-blur"> <div className="mb-2 flex items-center justify-between gap-3"> <div className="min-w-0"> <p className="text-sm font-semibold text-slate-800">Uploading {progress.fileCount} file(s)</p> <p className="text-xs text-slate-500"> {fmt(stats.speed)}/s Β· ETA {stats.eta > 0 ? fmtEta(stats.eta) : "calculating..."} </p> </div> <Badge color="bg-violet-100 text-violet-700"> uploading </Badge> </div> <div className="mb-2 h-2 overflow-hidden rounded-full bg-slate-100"> <div className="h-full rounded-full bg-violet-500 transition-all" style={{ width: `${pct}%` }} /> </div> <div className="flex items-center justify-between text-xs text-slate-500"> <span>{fmt(progress.bytesUploaded)} / {fmt(progress.totalBytes)}</span> <span>{pct.toFixed(1)}%</span> </div> </div> ); } // ─── Main App ───────────────────────────────────────────────────────────────── function HighlightedText({ text, highlight }: { text: string; highlight: string }) { if (!highlight.trim()) return <>{text}</>; const escaped = highlight.replace(/[.*+?^\${}()|[\]\\]/g, '\\$&'); const parts = text.split(new RegExp(`(${escaped})`, 'gi')); return ( <> {parts.map((part, i) => part.toLowerCase() === highlight.toLowerCase() ? ( <mark key={i} className="rounded bg-yellow-200 px-1">{part}</mark> ) : ( part ) )} </> ); } export default function App() { const [tab, setTab] = useState<Tab>("files"); const [searchTerm, setSearchTerm] = useState(""); const [extensionFilter, setExtensionFilter] = useState(""); const [debouncedSearch, setDebouncedSearch] = useState(""); // Debounce search input useEffect(() => { const t = setTimeout(() => setDebouncedSearch(searchTerm), 300); return () => clearTimeout(t); }, [searchTerm]); const [files, setFiles] = useState<FileEntry[]>([]); const [folders, setFolders] = useState<string[]>([]); const [selectedFolder, setSelectedFolder] = useState<string>("/"); const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]); const [loadingFiles, setLoadingFiles] = useState(true); const [fileSearch, setFileSearch] = useState(""); const [remoteSearch, setRemoteSearch] = useState(""); const [selectedForEncode, setSelectedForEncode] = useState<string>(""); const [jobs, setJobs] = useState<Job[]>([]); const [downloadJobId, setDownloadJobId] = useState<string | null>(null); const [remoteDownloadJobId, setRemoteDownloadJobId] = useState<string | null>(null); const [pixeldrainJobIds, setPixeldrainJobIds] = useState<string[]>([]); const [toast, setToast] = useState<string | null>(null); const [showInfoFile, setShowInfoFile] = useState<FileEntry | null>(null); const [showPreviewFile, setShowPreviewFile] = useState<FileEntry | null>(null); const [showTrimFile, setShowTrimFile] = useState<FileEntry | null>(null); const [showCropFile, setShowCropFile] = useState<FileEntry | null>(null); const [showAdvancedTrimCropFile, setShowAdvancedTrimCropFile] = useState<FileEntry | null>(null); const [showMoveFiles, setShowMoveFiles] = useState<FileEntry[] | null>(null); const [showMergeFiles, setShowMergeFiles] = useState<FileEntry[] | null>(null); const [showCreateFolder, setShowCreateFolder] = useState(false); const [showCredentialsModal, setShowCredentialsModal] = useState(false); // Per-remote URL credentials storage const [remoteCredentials, setRemoteCredentials] = useState<Record<string, RemoteCredentials>>(() => { try { const saved = localStorage.getItem("remoteCredentials"); return saved ? JSON.parse(saved) : {}; } catch { return {}; } }); const [remoteUrl, setRemoteUrl] = useState(""); const [remoteEntries, setRemoteEntries] = useState<RemoteEntry[]>([]); const [remoteLoading, setRemoteLoading] = useState(false); const [remoteError, setRemoteError] = useState<string | null>(null); const [remoteSelected, setRemoteSelected] = useState<string[]>([]); const remoteUploadRef = useRef<HTMLInputElement>(null); const [remoteUrlHistory, setRemoteUrlHistory] = useState<string[]>(() => { try { return JSON.parse(localStorage.getItem("remoteUrlHistory") || "[]"); } catch { return []; } }); const [remoteShowHistory, setRemoteShowHistory] = useState(false); const remoteInputRef = useRef<HTMLInputElement>(null); // Get credentials for current remote URL const getCurrentRemoteCredentials = (url: string = remoteUrl): RemoteCredentials => { const normalizedUrl = normalizeRemoteUrl(url); return remoteCredentials[normalizedUrl] || { hfToken: '', hfS3AccessKeyId: '', hfS3SecretAccessKey: '' }; }; // Current URL's credentials const currentRemoteCreds = getCurrentRemoteCredentials(remoteUrl); const [remoteHfToken, setRemoteHfToken] = useState(currentRemoteCreds.hfToken); const [remoteHfS3AccessKeyId, setRemoteHfS3AccessKeyId] = useState(currentRemoteCreds.hfS3AccessKeyId); const [remoteHfS3SecretAccessKey, setRemoteHfS3SecretAccessKey] = useState(currentRemoteCreds.hfS3SecretAccessKey); // Update credentials for current remote URL const updateCurrentRemoteCredentials = (url: string, creds: Partial<RemoteCredentials>) => { const normalizedUrl = normalizeRemoteUrl(url); if (!normalizedUrl) return; setRemoteCredentials((prev) => { const newCreds = { ...prev }; if (!newCreds[normalizedUrl]) { newCreds[normalizedUrl] = { hfToken: '', hfS3AccessKeyId: '', hfS3SecretAccessKey: '' }; } if (creds.hfToken !== undefined) newCreds[normalizedUrl].hfToken = creds.hfToken; if (creds.hfS3AccessKeyId !== undefined) newCreds[normalizedUrl].hfS3AccessKeyId = creds.hfS3AccessKeyId; if (creds.hfS3SecretAccessKey !== undefined) newCreds[normalizedUrl].hfS3SecretAccessKey = creds.hfS3SecretAccessKey; try { localStorage.setItem("remoteCredentials", JSON.stringify(newCreds)); } catch {} return newCreds; }); }; // Load credentials when remoteUrl changes useEffect(() => { if (remoteUrl.trim()) { const creds = getCurrentRemoteCredentials(remoteUrl); setRemoteHfToken(creds.hfToken); setRemoteHfS3AccessKeyId(creds.hfS3AccessKeyId); setRemoteHfS3SecretAccessKey(creds.hfS3SecretAccessKey); } }, [remoteUrl]); // Save credentials to localStorage and remoteCredentials whenever they change useEffect(() => { if (!remoteUrl.trim()) return; updateCurrentRemoteCredentials(remoteUrl, { hfToken: remoteHfToken, hfS3AccessKeyId: remoteHfS3AccessKeyId, hfS3SecretAccessKey: remoteHfS3SecretAccessKey, }); }, [remoteHfToken, remoteHfS3AccessKeyId, remoteHfS3SecretAccessKey, remoteUrl]); const saveRemoteUrlToHistory = (url: string) => { const base = url.trim(); if (!base) return; setRemoteUrlHistory((prev) => { const next = [base, ...prev.filter((u) => u !== base)].slice(0, 20); try { localStorage.setItem("remoteUrlHistory", JSON.stringify(next)); } catch {} return next; }); }; const removeRemoteUrlFromHistory = (url: string) => { setRemoteUrlHistory((prev) => { const next = prev.filter((u) => u !== url); try { localStorage.setItem("remoteUrlHistory", JSON.stringify(next)); } catch {} return next; }); }; const [teleboxToken, setTeleboxToken] = useState(""); const [teleboxWebToken, setTeleboxWebToken] = useState(""); const [teleboxEntries, setTeleboxEntries] = useState<TeleboxEntry[]>([]); const [teleboxLoading, setTeleboxLoading] = useState(false); const [teleboxError, setTeleboxError] = useState<string | null>(null); const [teleboxSelected, setTeleboxSelected] = useState<string[]>([]); const [teleboxPid, setTeleboxPid] = useState(0); const [teleboxPath, setTeleboxPath] = useState<{ id: number; name: string }[]>([]); const teleboxUploadRef = useRef<HTMLInputElement>(null); // ── Generic S3-compatible storage state (Qencode media storage, Backblaze, etc) ── const [b2KeyId, setB2KeyId] = useState(""); const [b2AppKey, setB2AppKey] = useState(""); const [b2BucketName, setB2BucketName] = useState(() => { try { return localStorage.getItem("s3BucketName") || ""; } catch { return ""; } }); // Path-style S3 management API host, e.g. "us-west.s3.qencode.com" (Qencode) or // "s3.us-east-005.backblazeb2.com" (Backblaze B2). Different providers use // different hosts, so this must be entered explicitly rather than assumed. const [b2Host, setB2Host] = useState(() => { try { return localStorage.getItem("s3Host") || "s3.us-east-005.backblazeb2.com"; } catch { return "s3.us-east-005.backblazeb2.com"; } }); // Virtual-hosted CDN/playback host (e.g. https://<bucket>.media-storage.<region>.qencode.com). // Used ONLY for signed-URL playback links (Qencode-specific feature) β€” NOT for // list/upload/download/delete, which use the path-style host above instead. const [b2EndpointUrl, setB2EndpointUrl] = useState(() => { try { return localStorage.getItem("s3EndpointUrl") || ""; } catch { return ""; } }); const [b2Region, setB2Region] = useState(() => { try { return localStorage.getItem("s3Region") || "us-east-005"; } catch { return "us-east-005"; } }); const [b2Entries, setB2Entries] = useState<BackblazeEntry[]>([]); const [b2Loading, setB2Loading] = useState(false); const [b2Error, setB2Error] = useState<string | null>(null); const [b2Selected, setB2Selected] = useState<string[]>([]); const [b2Prefix, setB2Prefix] = useState(""); const b2UploadRef = useRef<HTMLInputElement>(null); const [b2CfProxyUrl, setB2CfProxyUrl] = useState(""); const [b2UploadingFileIds, setB2UploadingFileIds] = useState<Set<string>>(new Set()); const [b2DownloadJobId, setB2DownloadJobId] = useState<string | null>(null); const setB2BucketNamePersist = (v: string) => { setB2BucketName(v); try { localStorage.setItem("s3BucketName", v); } catch {} }; const setB2HostPersist = (v: string) => { setB2Host(v); try { localStorage.setItem("s3Host", v); } catch {} }; const setB2EndpointUrlPersist = (v: string) => { setB2EndpointUrl(v); try { localStorage.setItem("s3EndpointUrl", v); } catch {} }; const setB2RegionPersist = (v: string) => { setB2Region(v); try { localStorage.setItem("s3Region", v); } catch {} }; // ── Saved storage connections (named presets) so switching providers/buckets // doesn't require re-typing bucket/host/region/keys every time. ────────────── type SavedS3Connection = { name: string; bucketName: string; region: string; host: string; endpointUrl: string; keyId: string; appKey: string; }; const [b2SavedConnections, setB2SavedConnections] = useState<SavedS3Connection[]>(() => { try { return JSON.parse(localStorage.getItem("s3SavedConnections") || "[]"); } catch { return []; } }); const [b2SelectedConnectionName, setB2SelectedConnectionName] = useState(""); const persistSavedConnections = (list: SavedS3Connection[]) => { setB2SavedConnections(list); try { localStorage.setItem("s3SavedConnections", JSON.stringify(list)); } catch {} }; const loadSavedConnection = (name: string) => { setB2SelectedConnectionName(name); const conn = b2SavedConnections.find((c) => c.name === name); if (!conn) return; setB2BucketNamePersist(conn.bucketName); setB2RegionPersist(conn.region); setB2HostPersist(conn.host); setB2EndpointUrlPersist(conn.endpointUrl); setB2KeyId(conn.keyId); setB2AppKey(conn.appKey); }; const saveCurrentConnection = () => { const defaultName = b2BucketName.trim() || "Untitled connection"; const name = (window.prompt("Save this connection as:", b2SelectedConnectionName || defaultName) || "").trim(); if (!name) return; const conn: SavedS3Connection = { name, bucketName: b2BucketName.trim(), region: b2Region.trim(), host: b2Host.trim(), endpointUrl: b2EndpointUrl.trim(), keyId: b2KeyId.trim(), appKey: b2AppKey.trim(), }; const next = [...b2SavedConnections.filter((c) => c.name !== name), conn]; persistSavedConnections(next); setB2SelectedConnectionName(name); setToast(`Saved connection "${name}"`); }; const deleteSavedConnection = (name: string) => { if (!confirm(`Delete saved connection "${name}"?`)) return; persistSavedConnections(b2SavedConnections.filter((c) => c.name !== name)); if (b2SelectedConnectionName === name) setB2SelectedConnectionName(""); }; const browseS3 = async (prefix = b2Prefix) => { if (!b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()) return; setB2Loading(true); setB2Error(null); setB2Selected([]); const res = await api.s3List(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), prefix); setB2Loading(false); if (res.ok) { setB2Entries(res.entries); setB2Prefix(prefix); } else { setB2Error(res.error || "Failed to browse bucket"); } }; const uploadFilesToS3 = async (fileList: FileList | null) => { if (!fileList?.length || !b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()) return; for (const file of Array.from(fileList)) { const res = await api.s3Upload(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), file, b2Prefix); if (!res.ok && res.error) alert(`${file.name}: ${res.error}`); } setToast("Storage upload finished"); browseS3(); }; const downloadFromS3 = async (key: string) => { const res = await api.s3Download(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-east-005", b2Host.trim(), key, selectedFolder || undefined, b2CfProxyUrl.trim() || undefined); if (res.jobId) { setB2DownloadJobId(res.jobId); } else { setToast(`Download failed: ${res.error || "unknown error"}`); } }; const deleteFromS3 = async (key: string) => { if (!confirm(`Delete "${key}" from storage? This cannot be undone.`)) return; const res = await api.s3Delete(b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), key); if (res.ok) { setToast("Deleted from storage"); browseS3(); } else { setToast(`Delete failed: ${res.error || "unknown error"}`); } }; const toggleB2Selected = (key: string) => { setB2Selected((prev) => prev.includes(key) ? prev.filter((v) => v !== key) : [...prev, key]); }; const getS3SignedLink = async (key: string) => { // Prefer the CF proxy URL β€” use ?b2File=&b2Bucket=&kid=&key= (native B2 // download-by-name mode) so the link works for ANY filename including those // with spaces, parentheses, or other special characters. if (b2CfProxyUrl.trim() && b2BucketName.trim()) { const base = b2CfProxyUrl.trim().replace(/\/+$/, ""); const b2File = btoa(key); const b2Bucket = btoa(b2BucketName.trim()); const kid = btoa(b2KeyId.trim()); const keyB64 = btoa(b2AppKey.trim()); const url = `${base}?b2File=${encodeURIComponent(b2File)}&b2Bucket=${encodeURIComponent(b2Bucket)}&kid=${encodeURIComponent(kid)}&key=${encodeURIComponent(keyB64)}`; try { await navigator.clipboard.writeText(url); setToast("Direct link copied β€” free via Cloudflare proxy"); } catch { setToast(url); } return; } // Fallback: S3 presigned URL (no CF proxy configured). Works anywhere but // egress goes through B2 directly and counts against bandwidth. if (b2KeyId.trim() && b2AppKey.trim() && b2BucketName.trim() && b2Host.trim()) { const res = await api.s3Presign( b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-east-005", b2Host.trim(), key, 3600 ); if (res.ok && res.url) { try { await navigator.clipboard.writeText(res.url); setToast("Presigned link copied (valid 1 hour) β€” note: counts against B2 bandwidth"); } catch { setToast(res.url); } } else { setToast(`Failed to create presigned link: ${res.error || "unknown error"}`); } return; } setToast("Enter a CF proxy URL or storage credentials to generate a link"); }; const isHfBucketUrlClient = (u: string) => /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\/([^\/]+)\/([^\/]+)(?:\/tree(?:\/(.*))?)?$/.test(u.trim()); const remoteBucketMatch = remoteUrl.trim().match(/^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\/([^\/]+)\/([^\/]+)(?:\/tree(?:\/(.*))?)?$/); const remoteBucketPath = remoteBucketMatch ? (remoteBucketMatch[3] || "") : ""; const remoteBreadcrumbParts = remoteBucketPath ? remoteBucketPath.split("/").filter(Boolean) : []; const [queue, setQueue] = useState<QueueItem[]>([]); const [presets, setPresets] = useState<EncodePreset[]>([]); const [presetLabel, setPresetLabel] = useState(""); const [fileSortBy, setFileSortBy] = useState<"date" | "size" | "name">("date"); const [fileSortDir, setFileSortDir] = useState<"asc" | "desc">("desc"); const [downloadUrlInput, setDownloadUrlInput] = useState(""); const [downloadUserInput, setDownloadUserInput] = useState("admin"); const [downloadPassInput, setDownloadPassInput] = useState("1234"); const [downloadBusy, setDownloadBusy] = useState(false); const [showDownloadAuth, setShowDownloadAuth] = useState(true); const [useFastDownload, setUseFastDownload] = useState(false); // ── Auto-upload to S3 after encode ─────────────────────────────────────────── const [encodeAutoS3, setEncodeAutoS3] = useState(() => { try { return localStorage.getItem("encodeAutoS3") === "1"; } catch { return false; } }); const setEncodeAutoS3Persist = (v: boolean) => { setEncodeAutoS3(v); try { localStorage.setItem("encodeAutoS3", v ? "1" : "0"); } catch {} }; const autoS3JobIdsRef = useRef<Set<string>>(new Set()); const prevJobStatusesRef = useRef<Map<string, string>>(new Map()); const [uploadDragOver, setUploadDragOver] = useState(false); const [uploadBusy, setUploadBusy] = useState(false); const [uploadProgress, setUploadProgress] = useState<{ bytesUploaded: number; totalBytes: number; fileCount: number; startTime: number } | null>(null); const uploadInputRef = useRef<HTMLInputElement | null>(null); const uploadFolderRef = useRef<HTMLInputElement | null>(null); const [forceStartMode, setForceStartMode] = useState(false); const [uploadDirectToRemote, setUploadDirectToRemoteState] = useState(() => { try { return localStorage.getItem("uploadDirectToRemote") === "1"; } catch { return false; } }); const setUploadDirectToRemote = (v: boolean) => { setUploadDirectToRemoteState(v); try { localStorage.setItem("uploadDirectToRemote", v ? "1" : "0"); } catch {} }; const [settings, setSettings] = useState<Record<string, unknown>>({ codec: "av1", mode: "crf-1pass", crf: 45, videoBitrateKbps: 1200, audioBitrateKbps: 64, resolution: "original", frameRate: "original", preset: 8, h26xPreset: "medium", aqMode: 1, tiles: "2x2", outputContainer: "mkv", outputFilename: "", outputFormat: "video", stripSubtitles: false, stripMetadata: false, subtitleFile: "", subtitleLang: "eng", subtitleBurn: false, startTime: "", endTime: "", deinterlace: false, denoise: false, rotate: "none", speed: 1, brightness: 0, contrast: 1, saturation: 1, audioChannels: "same", sameAsOriginalAudio: false, sameAsOriginalVideo: false, cropEnabled: false, cropLeft: 0, cropRight: 0, cropTop: 0, cropBottom: 0, scaleWidth: "", scaleHeight: "", forceStereo: false, sceneChange: true, }); const isAudioOnly = String(settings.outputFormat) === "audio"; const copiesVideo = Boolean(settings.sameAsOriginalVideo); const copiesAudio = Boolean(settings.sameAsOriginalAudio); const selectedFile = files.find((f) => f.id === selectedForEncode) || null; const normalizedSearch = (fileSearch.trim() || debouncedSearch.trim()).toLowerCase(); const isSearching = !!normalizedSearch; const visibleFiles = files.filter((f) => { const folder = f.folder || "/"; if (selectedFolder !== "/" && folder !== selectedFolder) return false; if (selectedFolder === "/" && folder !== "/") return false; return true; }); // When a search term is active, search across ALL files (all folders); otherwise use folder-scoped list const filteredVisibleFiles = (isSearching ? files : visibleFiles).filter((f) => { if (!normalizedSearch) return true; const haystack = `${f.name} ${f.folder || "/"}`.toLowerCase(); return haystack.includes(normalizedSearch); }); const sortedVisibleFiles = [...filteredVisibleFiles].sort((a, b) => { let result = 0; if (fileSortBy === "date") result = a.createdAt - b.createdAt; else if (fileSortBy === "size") result = a.sizeBytes - b.sizeBytes; else result = a.name.localeCompare(b.name); return fileSortDir === "asc" ? result : -result; }); const selectedFiles = files.filter((f) => selectedFileIds.includes(f.id)); const selectedMediaFiles = selectedFiles.filter((f) => isMediaFile(f.name)); const selectedArchiveFiles = selectedFiles.filter((f) => isArchiveFile(f.name)); const selectedSubtitleFiles = files.filter((f) => isSubtitleFile(f.name)); const refreshFiles = useCallback(async () => { setLoadingFiles(true); try { const data = await api.getFiles(); const all = [...(data.downloaded || []), ...(data.encoded || [])].sort((a, b) => b.createdAt - a.createdAt); setFiles(all); setFolders(data.folders || []); setSelectedFolder((prev) => { const allFolders = new Set(["/", ...(data.folders || [])]); return allFolders.has(prev) ? prev : "/"; }); setSelectedFileIds((prev) => prev.filter((id) => all.some((f) => f.id === id))); setSelectedForEncode((prev) => { if (prev && all.some((f) => f.id === prev)) return prev; const firstMedia = all.find((f) => isMediaFile(f.name)); return firstMedia?.id || ""; }); } finally { setLoadingFiles(false); } }, []); const refreshJobs = useCallback(async () => { try { const next = await api.getJobs(); setJobs(next.sort((a, b) => b.createdAt - a.createdAt)); } catch { // ignore } }, []); useEffect(() => { refreshFiles(); refreshJobs(); }, [refreshFiles, refreshJobs]); // ── Server-side settings: load on mount ────────────────────────────────────── const settingsLoadedRef = useRef(false); useEffect(() => { (async () => { try { const s = await api.getSettings() as Record<string, unknown>; // Hydrate all credential state from server (server is source of truth) if (typeof s.b2KeyId === "string") setB2KeyId(s.b2KeyId); if (typeof s.b2AppKey === "string") setB2AppKey(s.b2AppKey); if (typeof s.b2BucketName === "string") { setB2BucketName(s.b2BucketName); try { localStorage.setItem("s3BucketName", s.b2BucketName); } catch {} } if (typeof s.b2Host === "string") { setB2Host(s.b2Host); try { localStorage.setItem("s3Host", s.b2Host); } catch {} } if (typeof s.b2EndpointUrl === "string") { setB2EndpointUrl(s.b2EndpointUrl); try { localStorage.setItem("s3EndpointUrl", s.b2EndpointUrl); } catch {} } if (typeof s.b2Region === "string") { setB2Region(s.b2Region); try { localStorage.setItem("s3Region", s.b2Region); } catch {} } if (typeof s.b2CfProxyUrl === "string") setB2CfProxyUrl(s.b2CfProxyUrl); if (Array.isArray(s.b2SavedConnections)) { setB2SavedConnections(s.b2SavedConnections as SavedS3Connection[]); try { localStorage.setItem("s3SavedConnections", JSON.stringify(s.b2SavedConnections)); } catch {} } if (typeof s.remoteUrl === "string") setRemoteUrl(s.remoteUrl); if (Array.isArray(s.remoteUrlHistory)) { setRemoteUrlHistory(s.remoteUrlHistory as string[]); try { localStorage.setItem("remoteUrlHistory", JSON.stringify(s.remoteUrlHistory)); } catch {} } // Load per-remote credentials if (s.remoteCredentials && typeof s.remoteCredentials === 'object') { setRemoteCredentials(s.remoteCredentials as Record<string, RemoteCredentials>); try { localStorage.setItem("remoteCredentials", JSON.stringify(s.remoteCredentials)); } catch {} } // Legacy credentials - will be used as fallback if (typeof s.remoteHfToken === "string") setRemoteHfToken(s.remoteHfToken); if (typeof s.remoteHfS3AccessKeyId === "string") setRemoteHfS3AccessKeyId(s.remoteHfS3AccessKeyId); if (typeof s.remoteHfS3SecretAccessKey === "string") setRemoteHfS3SecretAccessKey(s.remoteHfS3SecretAccessKey); if (typeof s.teleboxToken === "string") setTeleboxToken(s.teleboxToken); if (typeof s.teleboxWebToken === "string") setTeleboxWebToken(s.teleboxWebToken); if (typeof s.encodeAutoS3 === "boolean") { setEncodeAutoS3(s.encodeAutoS3); try { localStorage.setItem("encodeAutoS3", s.encodeAutoS3 ? "1" : "0"); } catch {} } if (typeof s.uploadDirectToRemote === "boolean") { setUploadDirectToRemoteState(s.uploadDirectToRemote); try { localStorage.setItem("uploadDirectToRemote", s.uploadDirectToRemote ? "1" : "0"); } catch {} } if (Array.isArray(s.encodePresets)) setPresets(s.encodePresets as EncodePreset[]); else { // fallback: load encode presets from localStorage if not on server yet const saved = localStorage.getItem("encode_presets_v1"); if (saved) { try { setPresets(JSON.parse(saved)); } catch {} } } } catch { /* server unreachable, fall back to localStorage */ } settingsLoadedRef.current = true; })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // ── Server-side settings: debounced save on any credential change ───────────── useEffect(() => { if (!settingsLoadedRef.current) return; const timer = setTimeout(() => { api.saveSettings({ b2KeyId, b2AppKey, b2BucketName, b2Host, b2EndpointUrl, b2Region, b2CfProxyUrl, b2SavedConnections, remoteUrl, remoteCredentials, remoteUrlHistory, teleboxToken, teleboxWebToken, encodeAutoS3, uploadDirectToRemote, encodePresets: presets, }); }, 600); return () => clearTimeout(timer); }, [ b2KeyId, b2AppKey, b2BucketName, b2Host, b2EndpointUrl, b2Region, b2CfProxyUrl, b2SavedConnections, remoteUrl, remoteCredentials, remoteUrlHistory, teleboxToken, teleboxWebToken, encodeAutoS3, uploadDirectToRemote, presets, ]); useEffect(() => { if (!selectedFile) return; const ext = String(settings.outputContainer || "mkv"); const base = selectedFile.name.replace(/\.[^.]+$/, ""); setSettings((prev) => ({ ...prev, outputFilename: `${base}_encoded.${ext}`, })); }, [selectedFile?.id, settings.outputContainer]); const toggleSelected = (id: string) => { setSelectedFileIds((prev) => prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]); }; const clearSelected = () => setSelectedFileIds([]); const selectAllVisible = () => { setSelectedFileIds(filteredVisibleFiles.map((f) => f.id)); }; const deleteOne = async (file: FileEntry) => { if (!confirm(`Delete "${file.name}"?`)) return; await api.deleteFile(file.id); setToast("File deleted"); refreshFiles(); }; const deleteSelected = async () => { if (!selectedFileIds.length) return; if (!confirm(`Delete ${selectedFileIds.length} selected file(s)?`)) return; await api.batchDelete(selectedFileIds); setToast(`${selectedFileIds.length} file(s) deleted`); clearSelected(); refreshFiles(); }; const uploadSelectedToPixeldrain = async () => { if (!selectedFileIds.length) return; const res = await api.batchPixeldrain(selectedFileIds); setPixeldrainJobIds((prev) => [...res.jobIds, ...prev]); setToast(`Started ${res.jobIds.length} Pixeldrain upload(s)`); }; const unzipSelected = async () => { if (!selectedArchiveFiles.length) return; for (const file of selectedArchiveFiles) { const res = await api.unzipFile(file.id); if (res.ok) { setToast(`Extracted ${file.name}`); } } refreshFiles(); }; const zipSelected = async () => { if (!selectedFileIds.length) return; const res = await api.batchZip(selectedFileIds); if (res.ok) { setToast(`Created ZIP: ${res.filename}`); refreshFiles(); } }; const renameFile = async (file: FileEntry) => { const next = prompt("New file name:", file.name); if (!next || next.trim() === file.name) return; const res = await api.renameFile(file.id, next.trim()); if (res?.name) { setToast("File renamed"); refreshFiles(); } }; const renameFolder = async (folderPath: string) => { if (folderPath === "/") return; const currentName = folderPath.split("/").filter(Boolean).pop() || ""; const next = prompt("New folder name:", currentName); if (!next || next.trim() === currentName) return; const res = await api.renameFolder(folderPath, next.trim()); if (res.ok) { setToast("Folder renamed"); setSelectedFolder((prev) => prev === folderPath ? folderPath.replace(/[^/]+$/, next.trim()) : prev); refreshFiles(); } else if (res.error) { alert(res.error); } }; const deleteFolder = async (folderPath: string) => { if (folderPath === "/") return; if (!confirm(`Delete folder "${folderPath}" and all files inside it?`)) return; const res = await api.deleteFolder(folderPath); if (res.ok) { setToast("Folder deleted"); setSelectedFolder("/"); refreshFiles(); } else if (res.error) { alert(res.error); } }; const startUrlDownload = async () => { const url = downloadUrlInput.trim(); if (!url) { setToast("Enter a URL first"); return; } const username = downloadUserInput.trim() || undefined; const password = downloadPassInput.trim() || undefined; setDownloadBusy(true); try { const data = await api.startDownloadUrl(url, username, password, useFastDownload); setDownloadJobId(data.jobId); setToast("Download started"); setTab("files"); } catch (err) { console.error("Download failed:", err); setToast("Download failed"); } finally { setDownloadBusy(false); } }; const startEncode = async () => { if (!selectedFile) { setToast("Select a media file first"); return; } // Check if there are running jobs and not in force-start mode if (!forceStartMode && runningJobs.length > 0) { addToQueue(); setToast("Added to queue - waiting for current job to finish"); return; } const outputContainer = String(settings.outputContainer || "mkv"); const base = selectedFile.name.replace(/\.[^.]+$/, ""); const outputFilename = String(settings.outputFilename || `${base}_encoded.${outputContainer}`); const normalizedSettings: Record<string, unknown> = { ...settings, fileId: selectedFile.id, inputFilename: selectedFile.relativePath || selectedFile.name, outputFilename, frameRate: settings.frameRate === "same" ? "original" : settings.frameRate, cropEnabled: Boolean(settings.cropEnabled), cropLeft: Number(settings.cropLeft ?? 0), cropRight: Number(settings.cropRight ?? 0), cropTop: Number(settings.cropTop ?? 0), cropBottom: Number(settings.cropBottom ?? 0), audioChannels: settings.audioChannels === "2" ? "stereo" : settings.audioChannels === "1" ? "mono" : settings.audioChannels, rotate: settings.rotate === "clockwise" ? "90cw" : settings.rotate === "counterclockwise" ? "90ccw" : settings.rotate, copyVideo: Boolean(settings.sameAsOriginalVideo), copyAudio: Boolean(settings.sameAsOriginalAudio), }; try { const job = await api.startEncode(normalizedSettings); if (encodeAutoS3) autoS3JobIdsRef.current.add(job.id); setQueue((prev) => prev.map((q) => q.file.id === selectedFile.id && q.status === "waiting" ? { ...q, status: "encoding", jobId: job.id, settings: normalizedSettings } : q)); setForceStartMode(false); setToast("Encode started"); setTab("jobs"); refreshJobs(); } catch (err) { console.error("Encode failed:", err); setToast(err instanceof Error ? err.message : "Failed to start encode"); } }; const addToQueue = () => { if (!selectedFile) return; const uid = `queue_$${Math.random().toString(16).slice(2)}_$${Date.now().toString(16)}`; const preset = presets.find((p) => p.label === presetLabel); const item: QueueItem = { uid, file: selectedFile, status: "waiting", jobId: null, settings: { ...settings, fileId: selectedFile.id, inputFilename: selectedFile.relativePath || selectedFile.name, outputFilename: String(settings.outputFilename || `${selectedFile.name.replace(/\.[^.]+$/, "")}_encoded.${String(settings.outputContainer || "mkv")}`), frameRate: settings.frameRate === "same" ? "original" : settings.frameRate, cropEnabled: Boolean(settings.cropEnabled), cropLeft: Number(settings.cropLeft ?? 0), cropRight: Number(settings.cropRight ?? 0), cropTop: Number(settings.cropTop ?? 0), cropBottom: Number(settings.cropBottom ?? 0), audioChannels: settings.audioChannels === "2" ? "stereo" : settings.audioChannels === "1" ? "mono" : settings.audioChannels, rotate: settings.rotate === "clockwise" ? "90cw" : settings.rotate === "counterclockwise" ? "90ccw" : settings.rotate, }, presetLabel: preset?.label || "", }; setQueue((prev) => [...prev, item]); setToast("Added to queue"); }; const removeQueueItem = (uid: string) => { setQueue((prev) => prev.filter((q) => q.uid !== uid)); }; const startQueue = async () => { for (const item of queue) { if (item.status !== "waiting") continue; setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "encoding" } : q)); try { const job = await api.startEncode(item.settings); setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, jobId: job.id } : q)); let done = false; while (!done) { await new Promise((r) => setTimeout(r, 1500)); const latest = await api.getJob(job.id); if (latest.status === "done") { setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "done", jobId: job.id } : q)); done = true; } else if (latest.status === "failed" || latest.status === "stopped") { setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "failed", jobId: job.id } : q)); done = true; } } } catch { setQueue((prev) => prev.map((q) => q.uid === item.uid ? { ...q, status: "failed" } : q)); } } setToast("Queue finished"); refreshJobs(); refreshFiles(); }; const savePreset = () => { const label = prompt("Preset name:", presetLabel || "My preset"); if (!label?.trim()) return; const preset: EncodePreset = { id: Date.now(), label: label.trim(), settings: { ...settings }, }; setPresets((prev) => [preset, ...prev]); setPresetLabel(preset.label); setToast("Preset saved"); }; const loadPreset = (label: string) => { const preset = presets.find((p) => p.label === label); if (!preset) return; setPresetLabel(preset.label); setSettings((prev) => ({ ...prev, ...preset.settings, outputFilename: prev.outputFilename, })); setToast("Preset loaded"); }; const deletePreset = (id: number) => { setPresets((prev) => prev.filter((p) => p.id !== id)); setToast("Preset deleted"); }; const browseRemote = async (urlOverride?: string) => { const url = (urlOverride ?? remoteUrl).trim(); if (!url) return; setRemoteShowHistory(false); setRemoteLoading(true); setRemoteError(null); try { // Get credentials for this specific URL const creds = getCurrentRemoteCredentials(url); const res = await api.remoteList(url, creds.hfToken.trim() || undefined); if (res.ok) { setRemoteEntries(res.entries || []); saveRemoteUrlToHistory(url); } else { setRemoteError(res.error || "Failed to fetch"); } } finally { setRemoteLoading(false); } }; const browseTelebox = async (nextPid = teleboxPid, nextPath = teleboxPath) => { if (!teleboxToken.trim()) { setTeleboxError("TeleBox token is required"); return; } setTeleboxLoading(true); setTeleboxError(null); try { const res = await api.teleboxList(teleboxToken.trim(), nextPid); if (!res.ok) { setTeleboxError(res.error || "Failed to load TeleBox"); setTeleboxEntries([]); } else { setTeleboxEntries(res.entries || []); setTeleboxPid(nextPid); setTeleboxPath(nextPath); } } finally { setTeleboxLoading(false); } }; const openTeleboxFolder = async (entry: TeleboxEntry) => { const nextPath = [...teleboxPath, { id: Number(entry.id), name: entry.name }]; await browseTelebox(Number(entry.id), nextPath); }; const goTeleboxRoot = async () => { await browseTelebox(0, []); }; const goTeleboxCrumb = async (idx: number) => { const nextPath = teleboxPath.slice(0, idx + 1); const nextPid = nextPath[idx]?.id ?? 0; await browseTelebox(nextPid, nextPath); }; const createTeleboxFolder = async () => { if (!teleboxToken.trim()) { setTeleboxError("TeleBox token is required"); return; } const name = prompt("New TeleBox folder name:"); if (!name || !name.trim()) return; const res = await api.teleboxCreateFolder(teleboxToken.trim(), teleboxPid, name.trim()); if (!res.ok) { setTeleboxError(res.error || "Failed to create folder"); return; } setToast(`Created TeleBox folder: ${name.trim()}`); browseTelebox(); }; const toggleTeleboxSelected = (id: string) => { setTeleboxSelected((prev) => prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]); }; const teleboxDownloadSelected = async () => { if (!teleboxWebToken.trim()) { setTeleboxError("TeleBox web session token is required for download"); return; } const selectedItems = teleboxEntries.filter((e) => teleboxSelected.includes(e.id) && !e.isDir && e.itemId); let started = 0; for (const entry of selectedItems) { const res = await api.teleboxDownload(teleboxWebToken.trim(), String(entry.itemId), entry.name, selectedFolder); if (res.jobId) { setRemoteDownloadJobId(res.jobId); started++; } else if (!res.ok) { setTeleboxError(res.error || "TeleBox download failed"); } } if (started > 0) setToast(`Started ${started} TeleBox download(s)`); }; const uploadTeleboxFiles = async (files: FileList | null) => { if (!files?.length) return; if (!teleboxToken.trim()) { setTeleboxError("TeleBox token is required"); return; } const res = await api.teleboxUpload(teleboxToken.trim(), teleboxPid, files); if (!res.ok) { setTeleboxError(res.error || "TeleBox upload failed"); return; } setToast(`Uploaded ${files.length} file(s) to TeleBox`); browseTelebox(); }; const remoteDownloadSelected = async () => { if (!remoteSelected.length || !remoteUrl.trim()) return; let started = 0; for (const name of remoteSelected) { try { const entry = remoteEntries.find((e) => e.name === name); const creds = getCurrentRemoteCredentials(remoteUrl); const res = await api.remoteDownload( remoteUrl.trim(), name, selectedFolder, entry?.downloadUrl, { hfPath: entry?.hfPath, hfOrg: entry?.hfOrg, hfBucket: entry?.hfBucket, }, creds.hfToken.trim() ); if (res.error) { setToast(`Download failed: ${res.error}`); continue; } if (res.jobId) { console.log("Remote download job started:", res.jobId); setRemoteDownloadJobId(res.jobId); started++; } } catch (err) { setToast(`Download error: ${err instanceof Error ? err.message : "Unknown"}`); } } if (started > 0) { setToast(`Started ${started} remote download(s)`); } }; const remoteRenameEntry = async (name: string) => { const next = prompt("New remote name:", name); if (!next || next.trim() === name || !remoteUrl.trim()) return; const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(remoteUrl.trim()); const creds = getCurrentRemoteCredentials(remoteUrl); if (isHfBucket && (!creds.hfS3AccessKeyId.trim() || !creds.hfS3SecretAccessKey.trim())) { setToast("S3 credentials required for HF bucket operations"); return; } const hfCreds = isHfBucket ? { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim(), hfToken: creds.hfToken.trim() } : undefined; const res = await api.remoteRename(remoteUrl.trim(), name, next.trim(), hfCreds); if (res.ok) { setToast("Remote item renamed"); browseRemote(); } else if (res.error) { alert(res.error); } }; const remoteDeleteEntry = async (name: string) => { if (!remoteUrl.trim()) return; if (!confirm(`Delete remote item "${name}"?`)) return; const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(remoteUrl.trim()); const creds = getCurrentRemoteCredentials(remoteUrl); if (isHfBucket && (!creds.hfS3AccessKeyId.trim() || !creds.hfS3SecretAccessKey.trim())) { setToast("S3 credentials required for HF bucket operations"); return; } const hfCreds = isHfBucket ? { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim() } : undefined; const res = await api.remoteDelete(remoteUrl.trim(), name, hfCreds); if (res.ok) { setToast("Remote item deleted"); setRemoteSelected((prev) => prev.filter((v) => v !== name)); browseRemote(); } else if (res.error) { alert(res.error); } }; const remoteMoveEntry = async (name: string) => { if (!remoteUrl.trim()) return; const targetFolder = prompt(`Move "${name}" to folder (e.g. "SubFolder" or "/" for root):`, "/"); if (!targetFolder || !targetFolder.trim()) return; const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(remoteUrl.trim()); const creds = getCurrentRemoteCredentials(remoteUrl); if (isHfBucket && (!creds.hfS3AccessKeyId.trim() || !creds.hfS3SecretAccessKey.trim())) { setToast("S3 credentials required for HF bucket operations"); return; } const hfCreds = isHfBucket ? { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim(), hfToken: creds.hfToken.trim() } : undefined; const res = await api.remoteMove(remoteUrl.trim(), name, targetFolder.trim(), hfCreds); if (res.ok) { setToast(`Moved "${name}" to ${targetFolder.trim()}`); browseRemote(); } else if (res.error) { alert(res.error); } }; const remoteUploadFiles = async (fileList: FileList | null) => { if (!fileList?.length || !remoteUrl.trim()) return; const creds = getCurrentRemoteCredentials(remoteUrl); const hfCreds = { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim() }; for (const file of Array.from(fileList)) { const res = await api.remoteUpload(remoteUrl.trim(), file, hfCreds); if (!res.ok && res.error) { alert(`${file.name}: ${res.error}`); } } setToast("Remote upload finished"); browseRemote(); }; const toggleRemoteSelected = (name: string) => { setRemoteSelected((prev) => prev.includes(name) ? prev.filter((v) => v !== name) : [...prev, name]); }; const uploadFileToRemote = async (file: FileEntry) => { const target = remoteUrl.trim() || prompt("Remote server URL to upload to:", "") || ""; if (!target.trim()) return; if (target.trim() !== remoteUrl.trim()) setRemoteUrl(target.trim()); setToast(`Uploading ${file.name} to remote…`); // Check if this is an HF bucket and if we have S3 credentials const isHfBucket = /^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\//.test(target.trim()); if (isHfBucket && (!remoteHfS3AccessKeyId.trim() || !remoteHfS3SecretAccessKey.trim())) { setToast("For HF buckets, you need S3 credentials. Get them at huggingface.co/settings/tokens β†’ token menu β†’ 'Generate S3 credentials'"); return; } const hfCreds = { accessKeyId: remoteHfS3AccessKeyId.trim(), secretAccessKey: remoteHfS3SecretAccessKey.trim() }; const res = await api.uploadFileToRemote(file.id, target.trim(), hfCreds); if (res.ok) { saveRemoteUrlToHistory(target.trim()); setToast(`Uploaded ${file.name} to remote`); } else { setToast(`Remote upload failed: ${res.error || "unknown error"}`); } }; const uploadFileToB2 = async (file: FileEntry) => { const connOk = b2BucketName.trim() && b2KeyId.trim() && b2AppKey.trim() && b2Host.trim(); if (!connOk) { setToast("Configure Backblaze B2 credentials in the Storage tab first"); return; } setB2UploadingFileIds((prev) => new Set(prev).add(file.id)); setToast(`Uploading ${file.name} to Backblaze…`); try { const res = await api.s3UploadLocal( null, file.id, b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), b2Prefix || undefined ); if (res.ok) { setToast(`Uploaded to Backblaze: ${res.filename ?? file.name}`); } else { setToast(`Backblaze upload failed: ${res.error || "unknown error"}`); } } finally { setB2UploadingFileIds((prev) => { const next = new Set(prev); next.delete(file.id); return next; }); } }; const stopJob = async (id: string) => { await api.stopJob(id); setToast("Job stop requested"); refreshJobs(); }; const handleFileUpload = async (fileListOrArray: FileList | (File & { __folderPath?: string })[]) => { if (!fileListOrArray || (Array.isArray(fileListOrArray) ? fileListOrArray.length === 0 : fileListOrArray.length === 0)) return; if (uploadDirectToRemote) { const target = remoteUrl.trim(); if (!target) { setToast("Enter a remote server URL first"); return; } const files = Array.from(fileListOrArray); setUploadBusy(true); const totalBytes = files.reduce((sum, f) => sum + (f as File).size, 0); setUploadProgress({ bytesUploaded: 0, totalBytes, fileCount: files.length, startTime: Date.now() }); let uploaded = 0; let bytesDone = 0; let failed = 0; const creds = getCurrentRemoteCredentials(target); const hfCreds = { accessKeyId: creds.hfS3AccessKeyId.trim(), secretAccessKey: creds.hfS3SecretAccessKey.trim() }; try { for (const file of files) { try { const res = await api.remoteUpload(target, file as File, hfCreds); if (res.ok) { uploaded++; } else { failed++; console.error("Remote upload failed:", res.error); } } catch (err) { failed++; console.error("Remote upload error:", err); } bytesDone += (file as File).size; setUploadProgress(prev => prev ? { ...prev, bytesUploaded: bytesDone } : null); } saveRemoteUrlToHistory(target); setToast( failed ? `Uploaded ${uploaded}/${files.length} file(s) to remote (${failed} failed)` : `Uploaded ${uploaded} file(s) directly to remote` ); } finally { setUploadBusy(false); setTimeout(() => setUploadProgress(null), 2000); if (uploadInputRef.current) uploadInputRef.current.value = ""; if (uploadFolderRef.current) uploadFolderRef.current.value = ""; } return; } setUploadBusy(true); setUploadProgress({ bytesUploaded: 0, totalBytes: 0, fileCount: 0, startTime: Date.now() }); try { const files = Array.from(fileListOrArray); const formData = new FormData(); let totalBytes = 0; // Add files and their relative paths, calculate total size for (let i = 0; i < files.length; i++) { const file = files[i] as any; formData.append("files", file); totalBytes += file.size; // Include folder structure if available (from webkitRelativePath or custom path) if (file.webkitRelativePath) { const pathParts = file.webkitRelativePath.split("/"); if (pathParts.length > 1) { const folderPath = pathParts.slice(0, -1).join("/"); formData.append(`folderPath_${i}`, folderPath); } } else if (file.__folderPath) { formData.append(`folderPath_${i}`, file.__folderPath); } } if (selectedFolder && selectedFolder !== "/") { formData.append("folderPath", selectedFolder); } // Update progress with file count and total size setUploadProgress(prev => prev ? { ...prev, totalBytes, fileCount: files.length } : null); // Use XMLHttpRequest for upload progress tracking await new Promise<void>((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", (e) => { if (e.lengthComputable) { setUploadProgress(prev => prev ? { ...prev, bytesUploaded: e.loaded } : null); } }); xhr.addEventListener("load", () => { if (xhr.status === 200) { try { const data = JSON.parse(xhr.responseText); if (data.ok) { setToast(`Uploaded ${files.length} file(s)`); refreshFiles(); resolve(); } else { reject(new Error(data.error || "Upload failed")); } } catch (err) { reject(err); } } else { reject(new Error(`Upload failed with status ${xhr.status}`)); } }); xhr.addEventListener("error", () => { reject(new Error("Upload failed")); }); xhr.open("POST", "/api/files/upload"); xhr.send(formData); }); } catch (err) { console.error("Upload error:", err); setToast(`Upload error: ${err instanceof Error ? err.message : "Unknown error"}`); } finally { setUploadBusy(false); setTimeout(() => setUploadProgress(null), 2000); if (uploadInputRef.current) uploadInputRef.current.value = ""; if (uploadFolderRef.current) uploadFolderRef.current.value = ""; } }; const runningJobs = jobs.filter((j) => j.status === "running"); const finishedJobs = jobs.filter((j) => j.status !== "running"); // ─── Real-time job polling ──────────────────────────────────────────────── // Poll jobs every 1.5s while there are running jobs for live progress updates useEffect(() => { if (runningJobs.length === 0) return; const iv = setInterval(() => { refreshJobs(); }, 1500); return () => clearInterval(iv); }, [runningJobs.length, refreshJobs]); // ─── Auto-upload to S3 when encode job completes ────────────────────────── useEffect(() => { for (const job of jobs) { const prev = prevJobStatusesRef.current.get(job.id); if (prev === "running" && job.status === "done" && autoS3JobIdsRef.current.has(job.id)) { autoS3JobIdsRef.current.delete(job.id); const connOk = b2BucketName.trim() && b2KeyId.trim() && b2AppKey.trim() && b2Host.trim(); if (connOk) { (async () => { setToast("Uploading encoded file to S3…"); const res = await api.s3UploadLocal( job.id, null, b2BucketName.trim(), b2KeyId.trim(), b2AppKey.trim(), b2Region.trim() || "us-west", b2Host.trim(), b2Prefix || undefined ); if (res.ok) { setToast(`Uploaded to S3: ${res.filename}`); browseS3(); } else { setToast(`S3 upload failed: ${res.error || "unknown error"}`); } })(); } } prevJobStatusesRef.current.set(job.id, job.status); } }, [jobs]); // Auto-start next queue item when a job finishes useEffect(() => { const queueWaiting = queue.filter((q) => q.status === "waiting"); const hasRunningJobs = runningJobs.length > 0; if (queueWaiting.length > 0 && !hasRunningJobs) { const timer = setTimeout(() => { const nextItem = queueWaiting[0]; if (nextItem) { setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: "encoding" } : q)); (async () => { try { const job = await api.startEncode(nextItem.settings); setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, jobId: job.id } : q)); } catch (err) { console.error("Failed to start queue item:", err); setQueue((prev) => prev.map((q) => q.uid === nextItem.uid ? { ...q, status: "failed" } : q)); } })(); } }, 1500); return () => clearTimeout(timer); } }, [queue, jobs]); const isFileSelected = (id: string) => selectedFileIds.includes(id); const handleSortFiles = (key: "date" | "size" | "name") => { if (fileSortBy === key) { setFileSortDir((prev) => (prev === "asc" ? "desc" : "asc")); } else { setFileSortBy(key); setFileSortDir(key === "name" ? "asc" : "desc"); } }; const sortIndicator = (key: "date" | "size" | "name") => fileSortBy === key ? (fileSortDir === "asc" ? " β–²" : " β–Ό") : ""; // ─── Compact bulk action button style ─────────────────────────────────────── const bulkBtn = "rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-[11px] font-semibold text-slate-600 hover:bg-slate-50 hover:border-slate-300 disabled:opacity-40 disabled:cursor-not-allowed transition-colors whitespace-nowrap"; const bulkBtnDanger = "rounded-lg border border-red-200 bg-white px-2.5 py-1.5 text-[11px] font-semibold text-red-600 hover:bg-red-50 hover:border-red-300 disabled:opacity-40 disabled:cursor-not-allowed transition-colors whitespace-nowrap"; return ( <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-violet-50 text-slate-900"> <div className="mx-auto max-w-7xl px-3 sm:px-6 lg:px-8"> {/* Sticky header with app title, tabs, and refresh buttons - all pinned when scrolling */} <header className="sticky top-0 z-50 mb-4 flex flex-col gap-2 rounded-2xl border border-slate-200 bg-white/90 px-4 py-3 shadow-lg backdrop-blur-sm"> <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between"> <div className="flex items-center gap-3"> <div className="inline-flex items-center gap-2 rounded-full bg-violet-100 px-3 py-1 text-xs font-semibold text-violet-700"> OgA-Encoder </div> <h1 className="hidden text-xl font-black tracking-tight text-slate-900 sm:block">Encode, Trim, Merge, Move</h1> </div> {/* Tab navigation - on same line as title in header */} <div className="flex w-full items-center gap-1 overflow-x-auto sm:w-auto sm:flex-wrap"> {([ ["files", "Files", files.length, `${new Set(["/", ...folders]).size} folders`], ["encode", "Encode", queue.length, "queue"], ["jobs", "Jobs", runningJobs.length, "running"], ["remote", "Remote", remoteEntries.length, "entries"], ["telebox", "TeleBox", teleboxEntries.length, "cloud"], ["backblaze", "Storage", b2Entries.length, "S3 bucket"], ] as [Tab, string, number, string][]).map(([value, label, count, meta]) => ( <button key={value} onClick={() => setTab(value)} className={`min-w-[110px] flex-shrink-0 rounded-lg border px-3 py-2 text-left transition ${ tab === value ? "border-violet-500 bg-violet-600 text-white shadow-sm" : "border-slate-200 bg-white text-slate-700 hover:bg-slate-50" }`} > <div className="flex items-center justify-between gap-2"> <div className="min-w-0"> <div className="text-xs font-semibold">{label}</div> <div className={`text-[10px] ${tab === value ? "text-violet-100" : "text-slate-400"}`}> {meta} </div> </div> <span className={`rounded-full px-1.5 py-0.5 text-[10px] font-bold ${ tab === value ? "bg-white/20 text-white" : "bg-slate-100 text-slate-600" }`}> {count} </span> </div> </button> ))} </div> </div> {/* Refresh buttons - under tabs but still in header area */} <div className="flex w-full items-center gap-2 rounded-xl border border-slate-200 bg-white/50 px-4 py-2 sm:flex-wrap"> <button onClick={refreshFiles} className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition hover:border-violet-200 hover:text-violet-700" > Refresh Files </button> <button onClick={refreshJobs} className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition hover:border-violet-200 hover:text-violet-700" > Refresh Jobs </button> </div> </header> {/* ══════════════════════════════════════════════════════════════════════ FIX 3: Compact download bar β€” single row, much smaller footprint ══════════════════════════════════════════════════════════════════════ */} <div className="mb-3 rounded-xl border border-slate-200 bg-white/90 px-3 py-2 shadow-sm backdrop-blur"> <div className="flex items-center gap-2 flex-wrap"> <svg className="h-4 w-4 flex-shrink-0 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" /> </svg> <input type="text" value={downloadUrlInput} onChange={(e) => setDownloadUrlInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); startUrlDownload(); } }} placeholder="Paste download URL…" className="min-w-0 flex-1 rounded-lg border border-slate-200 px-2.5 py-1.5 text-xs focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-100" /> {showDownloadAuth && ( <> <input type="text" value={downloadUserInput} onChange={(e) => setDownloadUserInput(e.target.value)} placeholder="User" className="w-24 rounded-lg border border-slate-200 px-2.5 py-1.5 text-xs focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-100" /> <input type="password" value={downloadPassInput} onChange={(e) => setDownloadPassInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); startUrlDownload(); } }} placeholder="Pass" className="w-24 rounded-lg border border-slate-200 px-2.5 py-1.5 text-xs focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-100" /> </> )} <button type="button" onClick={() => setShowDownloadAuth((v) => !v)} className="rounded-lg border border-slate-200 px-2 py-1.5 text-[10px] font-semibold text-slate-500 hover:bg-slate-50 hover:text-slate-700 transition-colors" title="Toggle auth fields" > {showDownloadAuth ? "Hide auth" : "πŸ”‘ Auth"} </button> <button type="button" onClick={() => setUseFastDownload((v) => !v)} title="Fast mode uses yt-dlp + aria2c with 16 parallel connections" className={`rounded-lg border px-2 py-1.5 text-[10px] font-semibold transition-colors ${ useFastDownload ? "border-amber-400 bg-amber-50 text-amber-700 hover:bg-amber-100" : "border-slate-200 text-slate-500 hover:bg-slate-50 hover:text-slate-700" }`} > ⚑ Fast </button> <button onClick={startUrlDownload} disabled={downloadBusy || !downloadUrlInput.trim()} className="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" > {downloadBusy ? "…" : "Download"} </button> </div> </div> {downloadJobId && ( <div className="mb-4"> <DownloadProgress jobId={downloadJobId} onDone={() => { refreshFiles(); refreshJobs(); setDownloadJobId(null); }} /> </div> )} {remoteDownloadJobId && ( <div className="mb-4"> <RemoteDownloadProgress jobId={remoteDownloadJobId} onDone={() => { refreshFiles(); refreshJobs(); setRemoteDownloadJobId(null); }} /> </div> )} {b2DownloadJobId && ( <div className="mb-4"> <DownloadProgress jobId={b2DownloadJobId} onDone={() => { refreshFiles(); setB2DownloadJobId(null); }} /> </div> )} {!!pixeldrainJobIds.length && ( <div className="mb-4 space-y-3"> {pixeldrainJobIds.map((jobId) => ( <PixeldrainProgress key={jobId} jobId={jobId} onClose={() => setPixeldrainJobIds((prev) => prev.filter((id) => id !== jobId))} /> ))} </div> )} {tab === "files" && ( <section className="space-y-4"> <UploadArea onFilesSelected={handleFileUpload} busy={uploadBusy} dragOver={uploadDragOver} onDragOver={(e) => { e.preventDefault(); setUploadDragOver(true); }} onDragLeave={(e) => { e.preventDefault(); setUploadDragOver(false); }} uploadInputRef={uploadInputRef} uploadFolderRef={uploadFolderRef} /> {/* Upload Progress */} {uploadProgress && ( <UploadProgress progress={uploadProgress} onClose={() => setUploadProgress(null)} /> )} {/* ══════════════════════════════════════════════════════════════════ FIX 2: Folder filter β€” always visible actions, long names truncate ══════════════════════════════════════════════════════════════════ */} <div className="rounded-2xl border border-slate-200 bg-white/90 p-3 shadow-sm"> <div className="flex items-center justify-between mb-2"> <h2 className="text-xs font-bold uppercase tracking-wider text-slate-500">Folders</h2> <button onClick={() => setShowCreateFolder(true)} className="rounded-lg bg-violet-600 px-2.5 py-1 text-[10px] font-semibold text-white hover:bg-violet-700" > + New </button> </div> <div className="flex flex-wrap gap-1.5"> {/* Root folder */} <div className="inline-flex items-center"> <button onClick={() => setSelectedFolder("/")} className={`inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition ${ selectedFolder === "/" ? "bg-violet-100 text-violet-700 ring-1 ring-violet-300" : "bg-slate-50 text-slate-600 hover:bg-slate-100" }`} > <span className="text-[10px]">πŸ“‚</span> <span>/ root</span> <span className="rounded-full bg-white/80 px-1.5 text-[10px] text-slate-400">{files.filter((f) => (f.folder || "/") === "/").length}</span> </button> <a href="/api/folders/zip?folder=/" download className="ml-0.5 rounded p-1 text-slate-300 hover:bg-slate-100 hover:text-violet-600 transition-colors" title="Download root as ZIP"> <svg className="h-3 w-3" 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> </div> {Array.from(new Set(folders)) .sort((a, b) => a.localeCompare(b)) .map((folder) => { const count = files.filter((f) => (f.folder || "/") === folder).length; const active = selectedFolder === folder; return ( <div key={folder} className="inline-flex items-center group"> <button onClick={() => setSelectedFolder(folder)} className={`inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition max-w-[200px] ${ active ? "bg-violet-100 text-violet-700 ring-1 ring-violet-300" : "bg-slate-50 text-slate-600 hover:bg-slate-100" }`} title={folder} > <span className="text-[10px] flex-shrink-0">πŸ“</span> <span className="truncate">{folder}</span> <span className="flex-shrink-0 rounded-full bg-white/80 px-1.5 text-[10px] text-slate-400">{count}</span> </button> {/* FIX 2: Always-visible rename/delete β€” no hover-hidden */} <button onClick={() => renameFolder(folder)} className="ml-0.5 rounded p-1 text-slate-300 hover:bg-slate-100 hover:text-slate-600 transition-colors" title="Rename folder" > <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" /> </svg> </button> <button onClick={() => deleteFolder(folder)} className="rounded p-1 text-slate-300 hover:bg-red-50 hover:text-red-500 transition-colors" title="Delete folder" > <svg className="h-3 w-3" 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 15.916 21.75H8.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 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" /> </svg> </button> <a href={`/api/folders/zip?folder=${encodeURIComponent(folder)}`} download className="rounded p-1 text-slate-300 hover:bg-slate-100 hover:text-violet-600 transition-colors" title="Download folder as ZIP" > <svg className="h-3 w-3" 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> </div> ); })} </div> </div> {/* ══════════════════════════════════════════════════════════════════ FIX 1: Bulk actions β€” only appear when files are selected, shown as a compact sticky bar above the file list ══════════════════════════════════════════════════════════════════ */} {selectedFileIds.length > 0 && ( <div className="sticky top-0 z-30 rounded-xl border border-violet-200 bg-violet-50/95 px-3 py-2 shadow-sm backdrop-blur-sm"> <div className="flex items-center gap-2 flex-wrap"> <span className="text-xs font-bold text-violet-700 flex-shrink-0"> {selectedFileIds.length} selected </span> <div className="h-4 w-px bg-violet-200 flex-shrink-0" /> <button onClick={selectAllVisible} disabled={!filteredVisibleFiles.length} className={bulkBtn}>Select all visible</button> <button onClick={clearSelected} className={bulkBtn}>Clear</button> <button onClick={() => setShowMoveFiles(selectedFiles)} className={bulkBtn}>Move</button> <button onClick={zipSelected} className={bulkBtn}>Zip</button> {selectedArchiveFiles.length > 0 && ( <button onClick={unzipSelected} className={bulkBtn}>Unzip</button> )} {selectedMediaFiles.length >= 2 && ( <button onClick={() => setShowMergeFiles(selectedMediaFiles)} className={bulkBtn}>Merge</button> )} <button onClick={uploadSelectedToPixeldrain} className={bulkBtn}>Pixeldrain</button> <button onClick={deleteSelected} className={bulkBtnDanger}>Delete</button> </div> </div> )} {/* File table / cards β€” now full width, no sidebar */} <div className="rounded-2xl border border-slate-200 bg-white/90 shadow-sm"> <div className="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"> <div> {isSearching ? ( <> <h2 className="text-sm font-bold text-slate-900"> Search results <span className="ml-2 text-xs font-normal text-slate-400">across all folders</span> </h2> <p className="text-xs text-slate-500"> {filteredVisibleFiles.length} file{filteredVisibleFiles.length !== 1 ? "s" : ""} matching &ldquo;{normalizedSearch}&rdquo; </p> </> ) : ( <> <h2 className="text-sm font-bold text-slate-900">Files in {selectedFolder === "/" ? "/ (root)" : selectedFolder}</h2> <p className="text-xs text-slate-500"> {loadingFiles ? "Loading files…" : `${visibleFiles.length} file(s) in this folder`} </p> </> )} </div> <div className="flex items-center gap-3 text-xs text-slate-500"> {!isSearching && ( <span className="rounded-full bg-slate-100 px-2.5 py-1 font-semibold text-slate-700"> {filteredVisibleFiles.length} matching </span> )} <span>Sort:</span> <button type="button" onClick={() => handleSortFiles("name")} className={`font-semibold hover:text-slate-700 ${fileSortBy === "name" ? "text-violet-600" : ""}`}> Name{sortIndicator("name")} </button> <button type="button" onClick={() => handleSortFiles("size")} className={`font-semibold hover:text-slate-700 ${fileSortBy === "size" ? "text-violet-600" : ""}`}> Size{sortIndicator("size")} </button> <button type="button" onClick={() => handleSortFiles("date")} className={`font-semibold hover:text-slate-700 ${fileSortBy === "date" ? "text-violet-600" : ""}`}> Date{sortIndicator("date")} </button> </div> </div> <div className="flex flex-col gap-2 px-3 py-2 sm:flex-row"> {/* Search input with clear button */} <div className="relative flex-1"> <svg className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="m21 21-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0Z" /> </svg> <input type="text" value={fileSearch} onChange={(e) => setFileSearch(e.target.value)} placeholder="Search all folders…" className="w-full rounded-xl border border-slate-200 py-2 pl-9 pr-8 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> {fileSearch && ( <button onClick={() => setFileSearch("")} className="absolute right-2.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600" title="Clear search" > <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </button> )} </div> <div className="flex items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600"> <span className="font-semibold">Filter:</span> <select value={extensionFilter} onChange={(e) => setExtensionFilter(e.target.value)} className="rounded border border-slate-200 bg-white px-2 py-1 text-xs" > <option value="">All types</option> <option value="video">Video</option> <option value="archive">Archive</option> <option value="subtitle">Subtitle</option> </select> </div> </div> </div> {/* MOBILE_FILE_CARDS_START */} <div className="md:hidden"> {loadingFiles ? ( <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-8 text-center text-sm text-slate-400"> Loading files… </div> ) : !sortedVisibleFiles.length ? ( <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-8 text-center text-sm text-slate-400"> {isSearching ? `No files match "${normalizedSearch}"` : "No files in this folder."} </div> ) : ( <div className="divide-y divide-slate-100"> {sortedVisibleFiles.map((file) => { const selected = isFileSelected(file.id); const media = isMediaFile(file.name); const archive = isArchiveFile(file.name); const downloadUrl = `/api/files/${encodeURIComponent(file.id)}/download`; const uploadInFlight = b2UploadingFileIds.has(file.id); const queueItem = queue.find((q) => q.file.id === file.id && (q.status === "waiting" || q.status === "encoding")); const activityBadge = uploadInFlight ? ( <Badge color="bg-amber-100 text-amber-700">uploading</Badge> ) : queueItem ? ( <Badge color="bg-orange-100 text-orange-700">{queueItem.status === "waiting" ? "queued" : "processing"}</Badge> ) : null; const smallBtn = "inline-flex h-8 min-w-8 items-center justify-center rounded-lg border border-slate-200 bg-white px-2 text-[11px] font-semibold text-slate-600 hover:bg-slate-50"; return ( <div key={file.id} className={`space-y-3 px-4 py-4 ${selected ? "bg-violet-50/70" : "bg-white"}`}> <div className="flex items-start gap-3"> <input type="checkbox" checked={selected} onChange={() => toggleSelected(file.id)} className="mt-1 h-4 w-4 flex-shrink-0 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> <div className="min-w-0 flex-1"> <div className="break-words text-sm font-bold leading-snug text-slate-900"> {file.name} </div> <div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500"> <Badge color={file.source === "encoded" ? "bg-violet-100 text-violet-700" : "bg-sky-100 text-sky-700"}>{file.source}</Badge> {media && <Badge color="bg-emerald-100 text-emerald-700">media</Badge>} {archive && <Badge color="bg-amber-100 text-amber-700">archive</Badge>} {isSubtitleFile(file.name) && <Badge color="bg-sky-100 text-sky-700">subtitle</Badge>} {activityBadge} <span>{fmt(file.sizeBytes)}</span> </div> {isSearching && ( <div className="mt-1 flex items-center gap-1 text-[10px] text-slate-400"> <svg className="h-3 w-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12.75V12A2.25 2.25 0 0 1 4.5 9.75h15A2.25 2.25 0 0 1 21.75 12v.75m-8.69-6.44-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> <span className="font-mono">{file.folder || "/"}</span> </div> )} <div className="mt-1 text-[11px] text-slate-400"> {new Date(file.createdAt).toLocaleString([], { year: "2-digit", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", })} </div> </div> </div> <div className="flex flex-wrap gap-1.5 pl-7"> <button type="button" title="Info" onClick={() => setShowInfoFile(file)} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M11.25 11.25 12 17.25m0-9.75h.008v.008H12V7.5Zm9 4.5a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /> </svg> Info </button> {media && ( <button type="button" title="Preview" onClick={() => setShowPreviewFile(file)} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.574 0 3.286L8.03 20.99c-1.25.687-2.779-.216-2.779-1.643V5.653Z" /> </svg> Preview </button> )} {media && ( <button type="button" title="Encode" onClick={() => { setSelectedForEncode(file.id); setTab("encode"); }} className={smallBtn} > Encode </button> )} {media && ( <button type="button" title="Trim" onClick={() => setShowTrimFile(file)} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <circle cx="6" cy="6" r="3" /> <circle cx="6" cy="18" r="3" /> <path strokeLinecap="round" strokeLinejoin="round" d="M20 4 8.12 15.88M20 20 8.12 8.12" /> </svg> Trim </button> )} {media && ( <button type="button" title="Crop" onClick={() => setShowCropFile(file)} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <rect x="4" y="4" width="16" height="16" rx="2" /> <path strokeLinecap="round" strokeLinejoin="round" d="M8 8h8v8" /> </svg> Crop </button> )} {media && ( <button type="button" title="Advanced Trim & Crop" onClick={() => setShowAdvancedTrimCropFile(file)} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <rect x="2" y="2" width="20" height="20" rx="2" /> <path strokeLinecap="round" strokeLinejoin="round" d="M4 4l16 16" /> </svg> Adv TC </button> )} <button type="button" title="Copy download link" onClick={async () => { await navigator.clipboard.writeText(window.location.origin + downloadUrl); setToast("Download link copied"); }} className={smallBtn} > <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125H6.375a1.125 1.125 0 0 1-1.125-1.125V9.375c0-.621.504-1.125 1.125-1.125H9.75m6-6h3.375c.621 0 1.125.504 1.125 1.125v8.25c0 .621-.504 1.125-1.125 1.125h-8.25A1.125 1.125 0 0 1 9.75 11.625v-8.25c0-.621.504-1.125 1.125-1.125h4.875Z" /> </svg> Copy </button> <a href={downloadUrl} target="_blank" rel="noreferrer" title="Download file" className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v10.5m0 0 4-4m-4 4-4-4M4.5 20.25h15" /> </svg> Download </a> <button type="button" title="Upload to Pixeldrain" onClick={async () => { const res = await api.uploadToPixeldrain(file.id); setPixeldrainJobIds((prev) => [res.jobId, ...prev]); setToast(`Started Pixeldrain upload: ${file.name}`); }} className={smallBtn} > <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 16V4m0 12-4-4m4 4 4-4M4 20h16" /> </svg> Upload </button> <button type="button" title="Upload to remote server" onClick={() => uploadFileToRemote(file)} className={smallBtn} > <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 18A4.5 4.5 0 1 1 8.746 9.176 5.25 5.25 0 1 1 18 13.5h-1.5" /> <path strokeLinecap="round" strokeLinejoin="round" d="M12 12v9m0 0-3-3m3 3 3-3" /> </svg> To remote </button> <button type="button" title="Upload to Backblaze B2" disabled={b2UploadingFileIds.has(file.id)} onClick={() => uploadFileToB2(file)} className={smallBtn + (b2UploadingFileIds.has(file.id) ? " opacity-50 cursor-not-allowed" : "")} > {b2UploadingFileIds.has(file.id) ? ( <svg className="mr-1 h-3.5 w-3.5 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v3m0 12v3M3 12h3m12 0h3M5.636 5.636l2.122 2.122m8.485 8.485 2.122 2.122M5.636 18.364l2.122-2.122m8.485-8.485 2.122-2.122" /> </svg> ) : ( <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" 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.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" /> </svg> )} To B2 </button> <button type="button" title="Rename" onClick={() => renameFile(file)} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" /> </svg> Rename </button> <button type="button" title="Move" onClick={() => setShowMoveFiles([file])} className={smallBtn}> <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12 8.25 6m-6 6 6 6M21.75 5.25v13.5a1.5 1.5 0 0 1-1.5 1.5H9.75" /> </svg> Move </button> {archive && ( <button type="button" title="Unzip" onClick={async () => { const res = await api.unzipFile(file.id); if (res.ok) { setToast(`Extracted ${file.name}`); refreshFiles(); } }} className={smallBtn} > <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 7.5h16.5M6.75 7.5V6a2.25 2.25 0 0 1 2.25-2.25h6A2.25 2.25 0 0 1 17.25 6v1.5M6 7.5h12l-.9 10.2a2.25 2.25 0 0 1-2.242 2.05H9.142A2.25 2.25 0 0 1 6.9 17.7L6 7.5Zm6 3v5.25m0 0 2.25-2.25M12 15.75l-2.25-2.25" /> </svg> Unzip </button> )} <button type="button" title="Delete" onClick={() => deleteOne(file)} className="inline-flex h-8 min-w-8 items-center justify-center rounded-lg border border-red-200 bg-white px-2 text-[11px] font-semibold text-red-500 hover:bg-red-50" > <svg className="mr-1 h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" 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 15.916 21.75H8.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 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" /> </svg> Delete </button> </div> </div> ); })} </div> )} </div> {/* MOBILE_FILE_CARDS_END */} <div className="hidden md:block overflow-x-auto"> <table className="w-full table-fixed divide-y divide-slate-100"> <thead className="bg-slate-50/80"> <tr className="text-left text-xs uppercase tracking-wider text-slate-500"> <th className="w-10 px-3 py-3">Sel</th> <th className="px-4 py-3">Name</th> <th className="w-24 px-3 py-3">Size</th> <th className="w-64 px-3 py-3 text-right">Actions</th> <th className="w-36 px-3 py-3">Created</th> <th className="w-24 px-3 py-3">Source</th> </tr> </thead> <tbody className="divide-y divide-slate-100"> {loadingFiles ? ( <tr> <td colSpan={6} className="px-4 py-10 text-center text-sm text-slate-400"> Loading files… </td> </tr> ) : !sortedVisibleFiles.length ? ( <tr> <td colSpan={6} className="px-4 py-10 text-center text-sm text-slate-400"> {isSearching ? `No files match "${normalizedSearch}"` : "No files in this folder."} </td> </tr> ) : ( sortedVisibleFiles.map((file) => { const selected = isFileSelected(file.id); const media = isMediaFile(file.name); const archive = isArchiveFile(file.name); const previewUrl = `/api/files/${encodeURIComponent(file.id)}/download`; const uploadInFlight = b2UploadingFileIds.has(file.id); const queueItem = queue.find((q) => q.file.id === file.id && (q.status === "waiting" || q.status === "encoding")); const activityBadge = uploadInFlight ? ( <Badge color="bg-amber-100 text-amber-700">uploading</Badge> ) : queueItem ? ( <Badge color="bg-orange-100 text-orange-700">{queueItem.status === "waiting" ? "queued" : "processing"}</Badge> ) : null; return ( <tr key={file.id} className={selected ? "bg-violet-50/70" : "hover:bg-slate-50/60"}> <td className="px-3 py-2 align-top"> <input type="checkbox" checked={selected} onChange={() => toggleSelected(file.id)} className="mt-1 h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> </td> <td className="px-3 py-2 align-top"> <div className="min-w-0"> <div className="truncate text-sm font-semibold text-slate-800" title={file.name}> {file.name} </div> <div className="mt-1 flex flex-wrap gap-1"> <Badge color={file.source === "encoded" ? "bg-violet-100 text-violet-700" : "bg-sky-100 text-sky-700"}>{file.source}</Badge> {media && <Badge color="bg-emerald-100 text-emerald-700">media</Badge>} {archive && <Badge color="bg-amber-100 text-amber-700">archive</Badge>} {isSubtitleFile(file.name) && <Badge color="bg-sky-100 text-sky-700">subtitle</Badge>} {activityBadge} {isSearching && ( <span className="inline-flex items-center gap-0.5 rounded-full bg-slate-100 px-1.5 py-0.5 text-[10px] font-mono text-slate-500"> <svg className="h-2.5 w-2.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12.75V12A2.25 2.25 0 0 1 4.5 9.75h15A2.25 2.25 0 0 1 21.75 12v.75m-8.69-6.44-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> {file.folder || "/"} </span> )} </div> </div> </td> <td className="px-3 py-2 align-top text-sm text-slate-500">{fmt(file.sizeBytes)}</td> <td className="w-64 px-3 py-2 align-middle"> <div className="flex items-center justify-end gap-1"> <button title="Info" onClick={() => setShowInfoFile(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M11.25 11.25 12 17.25m0-9.75h.008v.008H12V7.5Zm9 4.5a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /> </svg> </button> {media && ( <button title="Preview" onClick={() => setShowPreviewFile(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.574 0 3.286L8.03 20.99c-1.25.687-2.779-.216-2.779-1.643V5.653Z" /> </svg> </button> )} {media && ( <button title="Encode" onClick={() => { setSelectedForEncode(file.id); setTab("encode"); }} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <rect x="4" y="4" width="16" height="16" rx="2" /> <path strokeLinecap="round" strokeLinejoin="round" d="M9 9h6v6H9zM9 2v2m6-2v2M9 20v2m6-2v2M20 9h2m-2 6h2M2 9h2m-2 6h2" /> </svg> </button> )} {media && ( <button title="Trim" onClick={() => setShowTrimFile(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <circle cx="6" cy="6" r="3" /> <circle cx="6" cy="18" r="3" /> <path strokeLinecap="round" strokeLinejoin="round" d="M20 4 8.12 15.88M20 20 8.12 8.12" /> </svg> </button> )} {media && ( <button title="Crop" onClick={() => setShowCropFile(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <rect x="4" y="4" width="16" height="16" rx="2" /> <path strokeLinecap="round" strokeLinejoin="round" d="M8 8h8v8" /> </svg> </button> )} {media && ( <button title="Advanced Trim & Crop" onClick={() => setShowAdvancedTrimCropFile(file)} className="inline-flex h-7 items-center justify-center rounded-md px-1.5 text-xs font-semibold text-violet-600 hover:bg-violet-50 hover:text-violet-700" type="button" > Adv TC </button> )} <button title="Upload to Pixeldrain" onClick={async () => { const res = await api.uploadToPixeldrain(file.id); setPixeldrainJobIds((prev) => [res.jobId, ...prev]); setToast(`Started Pixeldrain upload: ${file.name}`); }} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 18A4.5 4.5 0 1 1 8.746 9.176 5.25 5.25 0 1 1 18 13.5h-1.5" /> <path strokeLinecap="round" strokeLinejoin="round" d="M12 12v9m0 0-3-3m3 3 3-3" /> </svg> </button> <button title="Upload to remote server" onClick={() => uploadFileToRemote(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" 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> </button> <button title="Upload to Backblaze B2" disabled={b2UploadingFileIds.has(file.id)} onClick={() => uploadFileToB2(file)} className={`inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-sky-50 hover:text-sky-600${b2UploadingFileIds.has(file.id) ? " cursor-not-allowed text-sky-300" : " text-slate-500"}`} type="button" > {b2UploadingFileIds.has(file.id) ? ( <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v3m0 12v3M3 12h3m12 0h3M5.636 5.636l2.122 2.122m8.485 8.485 2.122 2.122M5.636 18.364l2.122-2.122m8.485-8.485 2.122-2.122" /> </svg> ) : ( <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" 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.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" /> </svg> )} </button> <button title="Rename" onClick={() => renameFile(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" /> </svg> </button> <button title="Move" onClick={() => setShowMoveFiles([file])} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0-4.5-4.5M19.5 12l-4.5 4.5" /> </svg> </button> {archive && ( <button title="Unzip" onClick={async () => { const res = await api.unzipFile(file.id); if (res.ok) { setToast(`Extracted ${file.name}`); refreshFiles(); } }} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M3 7.5A1.5 1.5 0 0 1 4.5 6h4.379a1.5 1.5 0 0 1 1.06.44l1.182 1.181a1.5 1.5 0 0 0 1.06.44H19.5A1.5 1.5 0 0 1 21 9.56v8.94A1.5 1.5 0 0 1 19.5 20h-15A1.5 1.5 0 0 1 3 18.5v-11Z" /> </svg> </button> )} <a href={previewUrl} target="_blank" rel="noreferrer" title="Download file" className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H19.5m0 0V12m0-6-7.5 7.5-3-3L4.5 15" /> </svg> </a> <button title="Copy download link" onClick={async () => { const fullUrl = window.location.origin + `/api/files/${encodeURIComponent(file.id)}/download`; await navigator.clipboard.writeText(fullUrl); setToast("Download link copied"); }} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 17.25h3a3 3 0 0 0 0-6h-3m-7.5 0h-3a3 3 0 0 0 0 6h3" /> <path strokeLinecap="round" strokeLinejoin="round" d="M8.25 12h7.5" /> </svg> </button> <button title="Delete" onClick={() => deleteOne(file)} className="inline-flex h-7 w-7 items-center justify-center rounded-md text-red-400 hover:bg-red-50 hover:text-red-600" type="button" > <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" 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 15.916 21.75H8.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 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" /> </svg> </button> </div> </td> <td className="px-3 py-2 align-top text-sm text-slate-500"> {new Date(file.createdAt).toLocaleString([], { year: "2-digit", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", })} </td> <td className="px-3 py-2 align-top text-sm text-slate-500">{file.source}</td> </tr> ); }) )} </tbody> </table> </div> </section> )} {tab === "encode" && ( <section className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]"> <div className="space-y-6"> <div className="rounded-2xl border border-slate-200 bg-white/90 p-5 shadow-sm"> <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between"> <div> <h2 className="text-sm font-bold text-slate-900">Encoder</h2> <p className="text-xs text-slate-500">Pick a local media file and configure FFmpeg settings.</p> </div> {remoteBucketMatch && ( <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600"> <div className="flex flex-wrap items-center gap-2"> <span className="text-xs font-semibold uppercase tracking-wider text-slate-400">Path</span> <button type="button" onClick={() => { const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}`; setRemoteUrl(_u); browseRemote(_u); }} className="rounded-lg bg-white px-2.5 py-1 font-semibold text-violet-700 shadow-sm hover:bg-violet-50" > {remoteBucketMatch[1]}/{remoteBucketMatch[2]} </button> {remoteBreadcrumbParts.map((part, idx) => ( <div key={`${part}_${idx}`} className="flex items-center gap-2"> <span className="text-slate-300">/</span> <button type="button" onClick={() => { const nextPath = remoteBreadcrumbParts.slice(0, idx + 1).join("/"); const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}/tree/${nextPath}`; setRemoteUrl(_u); browseRemote(_u); }} className="rounded-lg bg-white px-2.5 py-1 font-medium text-slate-700 shadow-sm hover:bg-violet-50 hover:text-violet-700" > {part} </button> </div> ))} </div> </div> )} <div className="flex flex-wrap items-center gap-2"> <select value={selectedForEncode} onChange={(e) => setSelectedForEncode(e.target.value)} className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" > <option value="">Select media file…</option> {files.filter((f) => isMediaFile(f.name)).map((file) => ( <option key={file.id} value={file.id}> {file.name} </option> ))} </select> {selectedFile && ( <> <button onClick={() => setShowInfoFile(selectedFile)} className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50" > File info </button> <button onClick={() => setShowCropFile(selectedFile)} className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50" > Crop preview </button> </> )} </div> </div> {!selectedFile ? ( <div className="mt-6 rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-10 text-center text-sm text-slate-500"> Select a media file to begin encoding. </div> ) : ( <div className="mt-6 space-y-6"> <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3"> {/* Output format */} <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Output format </label> <select value={String(settings.outputFormat)} onChange={(e) => setSettings((prev) => ({ ...prev, outputFormat: e.target.value }))} className="w-full rounded-xl 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" > <option value="video">Video</option> <option value="audio">Audio only</option> </select> </div> {/* Codec β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Codec <HelpTip text="Choose the video codec. AV1 gives best compression but is slower. H.264 is fastest and most compatible." /> </label> <select value={String(settings.codec)} onChange={(e) => setSettings((prev) => ({ ...prev, codec: e.target.value }))} className="w-full rounded-xl 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" > <option value="av1">AV1</option> <option value="h264">H.264</option> <option value="h265">H.265 / HEVC</option> <option value="vp9">VP9</option> </select> </div> )} {/* Mode β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Mode <HelpTip text="CRF keeps visual quality more constant. VBR targets a bitrate." /> </label> <select value={String(settings.mode)} onChange={(e) => setSettings((prev) => ({ ...prev, mode: e.target.value }))} className="w-full rounded-xl 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" > <option value="crf-1pass">CRF (1-pass)</option> <option value="vbr">VBR bitrate</option> </select> </div> )} <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Output container </label> <select value={String(settings.outputContainer)} onChange={(e) => setSettings((prev) => ({ ...prev, outputContainer: e.target.value }))} className="w-full rounded-xl 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" > {isAudioOnly ? ( <> <option value="opus">Opus (.opus)</option> <option value="mp3">MP3 (.mp3)</option> <option value="aac">AAC (.aac)</option> <option value="flac">FLAC (.flac)</option> <option value="wav">WAV (.wav)</option> <option value="m4a">M4A (.m4a)</option> </> ) : ( <> <option value="mkv">MKV</option> <option value="mp4">MP4</option> <option value="webm">WEBM</option> </> )} </select> </div> {/* CRF / Video bitrate β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && ( String(settings.mode) === "crf-1pass" ? ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> CRF <HelpTip text="Lower CRF = better quality and bigger size. Higher CRF = smaller files." /> </label> <input type="number" min={0} max={63} value={Number(settings.crf)} onChange={(e) => setSettings((prev) => ({ ...prev, crf: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> ) : ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Video bitrate (kbps) </label> <input type="number" min={100} step={50} value={Number(settings.videoBitrateKbps)} onChange={(e) => setSettings((prev) => ({ ...prev, videoBitrateKbps: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> ) )} {/* Audio bitrate β€” hidden when copying audio */} {!copiesAudio && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Opus audio (kbps) </label> <select value={String(settings.audioBitrateKbps)} onChange={(e) => setSettings((prev) => ({ ...prev, audioBitrateKbps: Number(e.target.value) }))} className="w-full rounded-xl 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" > {[32, 48, 64, 80, 96, 128, 160, 192, 256, 320].map((v) => ( <option key={v} value={v}>{v} kbps</option> ))} </select> </div> )} {/* Resolution β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Resolution </label> <select value={String(settings.resolution)} onChange={(e) => setSettings((prev) => ({ ...prev, resolution: e.target.value }))} className="w-full rounded-xl 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" > <option value="same">Same as source</option> <option value="2160p">2160p</option> <option value="1440p">1440p</option> <option value="1080p">1080p</option> <option value="720p">720p</option> <option value="480p">480p</option> <option value="360p">360p</option> <option value="custom">Custom</option> </select> </div> )} {!isAudioOnly && !copiesVideo && String(settings.resolution) === "custom" && ( <> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Custom width </label> <input type="number" min={2} step={2} value={String(settings.scaleWidth || "")} onChange={(e) => setSettings((prev) => ({ ...prev, scaleWidth: e.target.value }))} placeholder="1280" className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Custom height </label> <input type="number" min={2} step={2} value={String(settings.scaleHeight || "")} onChange={(e) => setSettings((prev) => ({ ...prev, scaleHeight: e.target.value }))} placeholder="720" className="min-w-0 w-full rounded-xl 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> </> )} {/* Frame rate β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Frame rate </label> <select value={String(settings.frameRate)} onChange={(e) => setSettings((prev) => ({ ...prev, frameRate: e.target.value }))} className="w-full rounded-xl 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" > <option value="same">Same as source</option> <option value="24">24</option> <option value="25">25</option> <option value="30">30</option> <option value="50">50</option> <option value="60">60</option> </select> </div> )} {/* Audio channels β€” hidden when copying audio */} {!copiesAudio && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Audio channels </label> <select value={String(settings.audioChannels)} onChange={(e) => setSettings((prev) => ({ ...prev, audioChannels: e.target.value }))} className="w-full rounded-xl 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" > <option value="same">Same as source</option> <option value="1">Mono</option> <option value="2">Stereo</option> </select> </div> )} {/* H26x preset β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && (String(settings.codec) === "h264" || String(settings.codec) === "h265") && ( <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> H26x preset </label> <select value={String(settings.h26xPreset)} onChange={(e) => setSettings((prev) => ({ ...prev, h26xPreset: e.target.value }))} className="w-full rounded-xl 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" > <option value="ultrafast">ultrafast</option> <option value="superfast">superfast</option> <option value="veryfast">veryfast</option> <option value="faster">faster</option> <option value="fast">fast</option> <option value="medium">medium</option> <option value="slow">slow</option> <option value="slower">slower</option> <option value="veryslow">veryslow</option> </select> </div> )} {/* AV1 params β€” hidden for audio-only or copy-video */} {!isAudioOnly && !copiesVideo && String(settings.codec) === "av1" && ( <> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> AV1 preset </label> <input type="number" min={0} max={13} value={Number(settings.preset)} onChange={(e) => setSettings((prev) => ({ ...prev, preset: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> AQ mode </label> <select value={String(settings.aqMode)} onChange={(e) => setSettings((prev) => ({ ...prev, aqMode: Number(e.target.value) }))} className="w-full rounded-xl 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" > <option value="0">0 - Off</option> <option value="1">1 - Variance</option> <option value="2">2 - Complexity</option> </select> </div> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Tiles </label> <select value={String(settings.tiles)} onChange={(e) => setSettings((prev) => ({ ...prev, tiles: e.target.value }))} className="w-full rounded-xl 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" > <option value="0">Off</option> <option value="2">2x2</option> <option value="4">4x4</option> </select> </div> </> )} </div> <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3"> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Start time </label> <TimePartsInput value={String(settings.startTime || "")} allowEmpty onChange={(value) => setSettings((prev) => ({ ...prev, startTime: value }))} /> </div> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> End time </label> <TimePartsInput value={String(settings.endTime || "")} allowEmpty onChange={(value) => setSettings((prev) => ({ ...prev, endTime: value }))} /> </div> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Speed </label> <input type="number" min={0.25} max={4} step={0.05} value={Number(settings.speed)} onChange={(e) => setSettings((prev) => ({ ...prev, speed: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Brightness </label> <input type="number" step={0.05} value={Number(settings.brightness)} onChange={(e) => setSettings((prev) => ({ ...prev, brightness: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Contrast </label> <input type="number" min={0} step={0.05} value={Number(settings.contrast)} onChange={(e) => setSettings((prev) => ({ ...prev, contrast: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Saturation </label> <input type="number" min={0} step={0.05} value={Number(settings.saturation)} onChange={(e) => setSettings((prev) => ({ ...prev, saturation: Number(e.target.value) }))} className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Rotate </label> <select value={String(settings.rotate)} onChange={(e) => setSettings((prev) => ({ ...prev, rotate: e.target.value }))} className="w-full rounded-xl 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" > <option value="none">None</option> <option value="clockwise">90Β° clockwise</option> <option value="counterclockwise">90Β° counter-clockwise</option> <option value="180">180Β°</option> </select> </div> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Subtitle file </label> <select value={String(settings.subtitleFile)} onChange={(e) => setSettings((prev) => ({ ...prev, subtitleFile: e.target.value }))} className="w-full rounded-xl 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" > <option value="">None</option> {selectedSubtitleFiles.map((file) => ( <option key={file.id} value={file.name}> {file.name} </option> ))} </select> </div> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Subtitle language </label> <input type="text" value={String(settings.subtitleLang)} onChange={(e) => setSettings((prev) => ({ ...prev, subtitleLang: e.target.value }))} className="min-w-0 w-full rounded-xl 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> <div className="space-y-1.5"> <label className="text-xs font-semibold uppercase tracking-wider text-slate-500"> Output filename </label> <input type="text" value={String(settings.outputFilename)} onChange={(e) => setSettings((prev) => ({ ...prev, outputFilename: e.target.value }))} className="min-w-0 w-full rounded-xl 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> </div> <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3"> {([ ["stripSubtitles", "Strip embedded subtitles", false], ["stripMetadata", "Strip metadata", false], ["sameAsOriginalAudio", "Same as original audio", false], ["sameAsOriginalVideo", "Same as original video", true], ["subtitleBurn", "Burn subtitle into video", true], ["deinterlace", "Deinterlace", true], ["denoise", "Denoise", true], ["forceStereo", "Force stereo output", false], ["sceneChange", "Scene change detection", true], ] as [string, string, boolean][]) .filter(([, , videoOnly]) => !isAudioOnly || !videoOnly) .map(([key, label]) => ( <label key={key} className="flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700"> <input type="checkbox" checked={Boolean(settings[key])} onChange={(e) => setSettings((prev) => ({ ...prev, [key]: e.target.checked }))} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> <span>{label}</span> </label> ))} </div> <div className="flex flex-wrap items-center gap-3"> <button onClick={startEncode} disabled={!selectedForEncode} className={`rounded-xl px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50 ${ forceStartMode ? "bg-orange-600 hover:bg-orange-700" : "bg-violet-600 hover:bg-violet-700" }`} title={forceStartMode ? "Force Start Mode: Will ignore running jobs" : "Start encoding"} > {forceStartMode ? "Start (Force)" : "Start encode"} </button> <button onClick={addToQueue} disabled={!selectedForEncode} className="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Add to queue </button> <button onClick={savePreset} className="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50" > Save preset </button> {(b2BucketName.trim() && b2KeyId.trim() && b2AppKey.trim() && b2Host.trim()) ? ( <label title="When checked, the encoded output is automatically uploaded to the currently configured S3/Backblaze connection after the job completes." className={`flex cursor-pointer items-center gap-2 rounded-xl border px-3 py-2 text-sm ${ encodeAutoS3 ? "border-violet-400 bg-violet-50 text-violet-700" : "border-slate-200 bg-slate-50 text-slate-600" }`} > <input type="checkbox" checked={encodeAutoS3} onChange={(e) => setEncodeAutoS3Persist(e.target.checked)} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> Save to S3 after encode </label> ) : ( <span className="text-xs text-slate-400" title="Configure S3/Backblaze credentials in the Storage tab to enable auto-upload after encode."> ☁ S3 not configured </span> )} </div> <div className="mt-5 rounded-2xl border border-slate-200 bg-slate-50/70 p-4"> <div className="flex items-center justify-between gap-2"> <div> <h3 className="text-sm font-semibold text-slate-900">Saved presets</h3> <p className="text-xs text-slate-500">These are stored in the app settings and available on this device.</p> </div> </div> {presets.length ? ( <div className="mt-3 space-y-2"> {presets.map((preset) => ( <div key={preset.id} className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2"> <div className="min-w-0"> <div className="truncate text-sm font-semibold text-slate-800">{preset.label}</div> <div className="text-xs text-slate-500"> {String(preset.settings.outputFormat || "video")} β€’ {String(preset.settings.codec || "av1")} β€’ {String(preset.settings.outputContainer || "mkv")} </div> </div> <div className="flex flex-wrap items-center gap-2"> <button type="button" onClick={() => loadPreset(preset.label)} className="rounded-lg border border-slate-200 px-2.5 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50" > Load </button> <button type="button" onClick={() => deletePreset(preset.id)} className="rounded-lg border border-red-200 px-2.5 py-1 text-xs font-semibold text-red-600 hover:bg-red-50" > Delete </button> </div> </div> ))} </div> ) : ( <p className="mt-3 text-sm text-slate-500">No presets saved yet. Use β€œSave preset” to keep the current encoder settings.</p> )} </div> </div> )} </div> </div> </section> )} {tab === "jobs" && ( <section className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_256px]"> <div className="space-y-6"> <div className="rounded-2xl border border-slate-200 bg-white/90 shadow-sm"> <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4"> <div> <h2 className="text-sm font-bold text-slate-900">Running jobs</h2> <p className="text-xs text-slate-500">Live FFmpeg tasks and progress polling</p> </div> <button onClick={refreshJobs} className="rounded-xl border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50" > Refresh </button> </div> <div className="p-5 space-y-4"> {!runningJobs.length ? ( <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-10 text-center text-sm text-slate-500"> No running jobs right now. </div> ) : ( runningJobs.map((job) => { const settings = job.settings || {}; const isTrim = settings.type === "trim"; const isMerge = settings.type === "merge"; const pct = Math.max(0, Math.min(100, Number(job.progress?.percent || 0))); return ( <div key={job.id} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"> {/* Header row: name + badge + stop button */} <div className="flex min-w-0 items-start justify-between gap-3"> <div className="min-w-0 flex-1"> <div className="flex min-w-0 flex-wrap items-center gap-2"> <p className="min-w-0 truncate text-sm font-bold text-slate-900"> {String(settings.outputFilename || settings.inputFilename || "Job")} </p> <Badge color="bg-violet-100 text-violet-700">running</Badge> {job.batchIndex != null && job.batchTotal != null && ( <span className="text-[11px] text-slate-400">Batch {job.batchIndex + 1}/{job.batchTotal}</span> )} </div> <p className="mt-0.5 text-xs text-slate-500"> {isMerge ? `Merge ${Array.isArray(settings.fileIds) ? settings.fileIds.length : 0} files Β· stream copy` : isTrim ? Array.isArray(settings.segments) ? `Trim & merge ${(settings.segments as { startTime: number; endTime: number }[]).length} segments Β· stream copy` : `Trim ${secondsToHms(Number(settings.startTime ?? 0))} β†’ ${secondsToHms(Number(settings.endTime ?? 0))} Β· stream copy` : `${String(settings.codec || "").toUpperCase()} Β· ${String(settings.resolution || "same")} Β· ${String(settings.mode || "")} ${String(settings.mode || "").includes("crf") ? `CRF ${settings.crf}` : ""}`} </p> <p className="mt-1 truncate text-[11px] text-slate-400"> {job.outputFolder || "/"} </p> </div> <button onClick={() => stopJob(job.id)} className="flex-shrink-0 rounded-xl border border-red-200 px-3 py-1.5 text-xs font-semibold text-red-600 hover:bg-red-50" > Stop </button> </div> {/* Progress bar */} <div className="mt-3"> <div className="mb-1.5 flex items-center justify-between text-xs"> <span className="font-semibold text-slate-800">{pct.toFixed(1)}%</span> <span className="text-slate-500"> {job.progress?.bitrateKbps ? `${job.progress.bitrateKbps.toFixed(0)} kbps` : ""} </span> </div> <div className="h-2 overflow-hidden rounded-full bg-slate-100"> <div className="h-full rounded-full bg-violet-600 transition-all" style={{ width: `${pct}%` }} /> </div> </div> {/* Stats row β€” 2 cols on xs, 4 cols on sm+ */} <div className="mt-3 grid grid-cols-2 gap-x-4 gap-y-1 sm:grid-cols-4 text-xs text-slate-500"> <div className="flex justify-between gap-1"> <span>ETA</span> <span className="font-medium text-slate-700">{fmtEta(Number(job.progress?.etaSeconds || 0))}</span> </div> <div className="flex justify-between gap-1"> <span>Speed</span> <span className="font-medium text-slate-700"> {job.progress?.speed && job.progress.speed > 0 ? `${job.progress.speed.toFixed(2)}Γ—` : "…"} </span> </div> <div className="flex justify-between gap-1"> <span>FPS</span> <span className="font-medium text-slate-700"> {job.progress?.fps ? job.progress.fps.toFixed(1) : "…"} </span> </div> <div className="flex justify-between gap-1"> <span>Size</span> <span className="font-medium text-slate-700">{fmt(Number(job.progress?.sizeOutBytes || 0))}</span> </div> </div> {!!job.progress?.log?.length && ( <details className="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3"> <summary className="cursor-pointer text-xs font-semibold text-slate-700">Recent log</summary> <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-[11px] leading-relaxed text-slate-600"> {job.progress.log.slice(-20).join("\n")} </pre> </details> )} </div> ); }) )} </div> </div> <div className="rounded-2xl border border-slate-200 bg-white/90 shadow-sm"> <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4"> <div> <h2 className="text-sm font-bold text-slate-900">Finished jobs</h2> <p className="text-xs text-slate-500">Completed, failed, and stopped tasks</p> </div> {finishedJobs.length > 0 && ( <button onClick={async () => { await api.clearFinishedJobs(); await refreshJobs(); }} className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-xs font-semibold text-red-600 hover:bg-red-100 transition-colors" > Clear finished </button> )} </div> <div className="p-5 space-y-4"> {!finishedJobs.length ? ( <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-10 text-center text-sm text-slate-500"> No finished jobs yet. </div> ) : ( finishedJobs.map((job) => { const settings = job.settings || {}; const isTrim = settings.type === "trim"; const isMerge = settings.type === "merge"; const isEncode = !isTrim && !isMerge; const badgeColor = job.status === "done" ? "bg-emerald-100 text-emerald-700" : job.status === "failed" ? "bg-red-100 text-red-700" : "bg-slate-200 text-slate-700"; return ( <div key={job.id} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"> {/* Header: name + badge + size/pct */} <div className="flex min-w-0 items-start justify-between gap-3"> <div className="min-w-0 flex-1"> <div className="flex min-w-0 flex-wrap items-center gap-2"> <p className="min-w-0 truncate text-sm font-bold text-slate-900"> {String(settings.outputFilename || settings.inputFilename || "Job")} </p> <Badge color={badgeColor}>{job.status}</Badge> </div> <p className="mt-0.5 text-xs text-slate-500"> {isMerge ? `Merge ${Array.isArray(settings.fileIds) ? settings.fileIds.length : 0} files Β· stream copy` : isTrim ? Array.isArray(settings.segments) ? `Trim & merge ${(settings.segments as { startTime: number; endTime: number }[]).length} segments Β· stream copy` : `Trim ${secondsToHms(Number(settings.startTime ?? 0))} β†’ ${secondsToHms(Number(settings.endTime ?? 0))} Β· stream copy` : `${String(settings.codec || "").toUpperCase()} Β· ${String(settings.resolution || "same")} Β· ${String(settings.mode || "")} ${String(settings.mode || "").includes("crf") ? `CRF ${settings.crf}` : ""}`} </p> </div> <div className="flex-shrink-0 text-right text-[11px] text-slate-500"> <div className="font-medium text-slate-700"> {job.progress?.percent ? `${job.progress.percent.toFixed(1)}%` : job.status === "done" ? "100%" : "β€”"} </div> <div>{fmt(Number(job.progress?.sizeOutBytes || 0))}</div> </div> </div> {/* Meta row */} <div className="mt-2 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-slate-400"> <span className="truncate max-w-[16ch] sm:max-w-none">{job.id}</span> <span>{new Date(job.createdAt).toLocaleString()}</span> {job.outputFolder && <span className="truncate">{job.outputFolder}</span>} </div> {/* Encode tag pills */} {isEncode && ( <div className="mt-2 flex flex-wrap gap-1.5 text-[11px]"> {settings.audioBitrateKbps != null && ( <span className="rounded-full bg-slate-100 px-2 py-0.5 text-slate-600"> Audio {String(settings.audioBitrateKbps)} kbps </span> )} {settings.outputContainer != null && ( <span className="rounded-full bg-slate-100 px-2 py-0.5 text-slate-600"> {String(settings.outputContainer).toUpperCase()} </span> )} {settings.frameRate != null && String(settings.frameRate) !== "same" && ( <span className="rounded-full bg-slate-100 px-2 py-0.5 text-slate-600"> {String(settings.frameRate)} fps </span> )} </div> )} {!!job.progress?.log?.length && ( <details className="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3"> <summary className="cursor-pointer text-xs font-semibold text-slate-700">View log</summary> <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-[11px] leading-relaxed text-slate-600"> {job.progress.log.join("\n")} </pre> </details> )} </div> ); }) )} </div> </div> </div> <aside className="space-y-4"> <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm"> <h3 className="mb-3 text-sm font-bold text-slate-900">Job summary</h3> <div className="grid grid-cols-2 gap-2"> <div className="rounded-xl bg-slate-50 px-3 py-2.5"> <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Running</p> <p className="mt-0.5 text-xl font-black text-slate-900">{runningJobs.length}</p> </div> <div className="rounded-xl bg-slate-50 px-3 py-2.5"> <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Finished</p> <p className="mt-0.5 text-xl font-black text-slate-900">{finishedJobs.length}</p> </div> <div className="rounded-xl bg-slate-50 px-3 py-2.5"> <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Succeeded</p> <p className="mt-0.5 text-xl font-black text-emerald-600">{jobs.filter((j) => j.status === "done").length}</p> </div> <div className="rounded-xl bg-slate-50 px-3 py-2.5"> <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Failed/Stopped</p> <p className="mt-0.5 text-xl font-black text-red-500"> {jobs.filter((j) => j.status === "failed" || j.status === "stopped").length} </p> </div> </div> </div> <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm"> <h3 className="mb-2 text-sm font-bold text-slate-900">Notes</h3> <div className="space-y-1.5 text-xs text-slate-500"> <p>β€’ Trim jobs with pasted clips appear as "Trim & merge X segments".</p> <p>β€’ Merge and trim use stream copy for fast lossless output.</p> <p>β€’ Refresh if a job looks stale or polling was interrupted.</p> </div> </div> </aside> </section> )} {tab === "remote" && ( <section className="space-y-6"> <div className="rounded-2xl border border-slate-200 bg-white/95 shadow-sm"> <div className="border-b border-slate-100 px-6 py-5"> <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between"> <div> <h2 className="text-base font-bold text-slate-900">Remote browser</h2> <p className="text-sm text-slate-500">Browse remote app servers or Hugging Face storage buckets, then download items into your selected local folder.</p> </div> <button onClick={() => setShowCredentialsModal(true)} className="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-colors" > <span>πŸ”‘</span> <span>Manage Credentials</span> </button> </div> </div> <div className="p-6 space-y-5"> <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]"> <div className="relative min-w-0 w-full"> <input ref={remoteInputRef} type="text" value={remoteUrl} onChange={(e) => setRemoteUrl(e.target.value)} onFocus={() => setRemoteShowHistory(true)} onBlur={() => setTimeout(() => setRemoteShowHistory(false), 150)} onKeyDown={(e) => { if (e.key === "Enter") { setRemoteShowHistory(false); browseRemote(); } else if (e.key === "Escape") { setRemoteShowHistory(false); } }} placeholder="https://example.com or https://huggingface.co/buckets/org/bucket/tree/path" className="min-w-0 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> {remoteShowHistory && remoteUrlHistory.length > 0 && ( <div className="absolute z-20 mt-1 w-full overflow-hidden rounded-xl border border-slate-200 bg-white shadow-lg"> <div className="max-h-60 overflow-y-auto py-1"> {remoteUrlHistory .filter((u) => !remoteUrl.trim() || u.toLowerCase().includes(remoteUrl.trim().toLowerCase())) .map((u) => ( <div key={u} className="group flex items-center gap-2 px-3 py-2 hover:bg-violet-50" > <button type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => { setRemoteUrl(u); setRemoteShowHistory(false); // Load credentials for this URL const creds = getCurrentRemoteCredentials(u); setRemoteHfToken(creds.hfToken); setRemoteHfS3AccessKeyId(creds.hfS3AccessKeyId); setRemoteHfS3SecretAccessKey(creds.hfS3SecretAccessKey); browseRemote(u); }} className="min-w-0 flex-1 truncate text-left text-sm text-slate-700" title={u} > {u} </button> <button type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => removeRemoteUrlFromHistory(u)} className="shrink-0 rounded-md p-1 text-slate-400 opacity-0 hover:bg-slate-100 hover:text-red-500 group-hover:opacity-100" title="Remove from history" > <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> )} </div> <button onClick={() => browseRemote()} disabled={remoteLoading || !remoteUrl.trim()} className="w-full rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 sm:w-auto" > {remoteLoading ? "Browsing…" : "Browse"} </button> </div> <input type="password" value={remoteHfToken} onChange={(e) => { setRemoteHfToken(e.target.value); updateCurrentRemoteCredentials(remoteUrl, { hfToken: e.target.value }); }} placeholder="HF token (optional, only needed for private buckets)" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> {remoteBucketMatch && ( <div className="rounded-xl border border-amber-200 bg-amber-50/70 p-3 space-y-2"> <p className="text-xs text-amber-800"> Uploading to a Hugging Face bucket needs S3 credentials, not the HF token above. Generate them from an access token with <strong>Write</strong> permission at{" "} <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="underline"> huggingface.co/settings/tokens </a>{" "} β†’ token menu β†’ "Generate S3 credentials". </p> <div className="grid gap-2 sm:grid-cols-2"> <input type="text" value={remoteHfS3AccessKeyId} onChange={(e) => { setRemoteHfS3AccessKeyId(e.target.value); updateCurrentRemoteCredentials(remoteUrl, { hfS3AccessKeyId: e.target.value }); }} placeholder="HF S3 Access Key ID (HFAK…)" className="min-w-0 w-full rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="password" value={remoteHfS3SecretAccessKey} onChange={(e) => setRemoteHfS3SecretAccessKey(e.target.value)} placeholder="HF S3 Secret Access Key" className="min-w-0 w-full rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> </div> )} {remoteError && ( <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"> {remoteError} </div> )} {remoteBucketMatch && ( <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600"> <div className="flex flex-wrap items-center gap-2"> <span className="text-xs font-semibold uppercase tracking-wider text-slate-400">Path</span> <button type="button" onClick={() => { const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}`; setRemoteUrl(_u); browseRemote(_u); }} className="rounded-lg bg-white px-2.5 py-1 font-semibold text-violet-700 shadow-sm hover:bg-violet-50" > {remoteBucketMatch[1]}/{remoteBucketMatch[2]} </button> {remoteBreadcrumbParts.map((part, idx) => ( <div key={`${part}_${idx}`} className="flex items-center gap-2"> <span className="text-slate-300">/</span> <button type="button" onClick={() => { const nextPath = remoteBreadcrumbParts.slice(0, idx + 1).join("/"); const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}/tree/${nextPath}`; setRemoteUrl(_u); browseRemote(_u); }} className="rounded-lg bg-white px-2.5 py-1 font-medium text-slate-700 shadow-sm hover:bg-violet-50 hover:text-violet-700" > {part} </button> </div> ))} </div> </div> )} <div className="flex flex-wrap items-center gap-2"> <button onClick={remoteDownloadSelected} disabled={!remoteSelected.length || !remoteUrl.trim()} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" /> </svg> Download selected </button> <button onClick={() => remoteUploadRef.current?.click()} disabled={!remoteUrl.trim()} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 16V4m0 12-4-4m4 4 4-4M4 20h16" /> </svg> Upload </button> <input ref={remoteUploadRef} type="file" multiple className="hidden" onChange={(e) => { remoteUploadFiles(e.target.files); e.currentTarget.value = ""; }} /> <button onClick={() => setRemoteSelected(remoteEntries.map((e) => e.name))} disabled={!remoteEntries.length} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > <svg className="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 6.75h15m-15 5.25h15m-15 5.25h15" /> </svg> Select all </button> <button onClick={() => setRemoteSelected([])} disabled={!remoteSelected.length} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > <svg className="mr-1.5 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> Clear </button> </div> <input type="text" value={remoteSearch} onChange={(e) => setRemoteSearch(e.target.value)} placeholder="Search remote entries by name…" className="w-full rounded-xl 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="overflow-hidden rounded-2xl border border-slate-200 bg-white"> <div className="overflow-x-auto"> <table className="min-w-full table-fixed divide-y divide-slate-100"> <thead className="bg-slate-50/80"> <tr className="text-left text-xs uppercase tracking-wider text-slate-500"> <th className="w-14 px-4 py-3">Sel</th> <th className="w-full px-4 py-3">Name</th> <th className="w-28 px-4 py-3">Type</th> <th className="w-32 px-4 py-3">Size</th> <th className="w-44 px-4 py-3 text-right">Actions</th> </tr> </thead> <tbody className="divide-y divide-slate-100"> {!remoteEntries.length ? ( <tr> <td colSpan={5} className="px-4 py-14 text-center text-sm text-slate-400"> {remoteLoading ? "Loading remote entries…" : "No remote entries loaded yet."} </td> </tr> ) : ( remoteEntries .filter((entry) => !remoteSearch.trim() || entry.name.toLowerCase().includes(remoteSearch.trim().toLowerCase()) ) .map((entry) => { const selected = remoteSelected.includes(entry.name); return ( <tr key={entry.name} className={selected ? "bg-violet-50/80" : "hover:bg-slate-50/70"}> <td className="px-4 py-3"> <input type="checkbox" checked={selected} onChange={() => toggleRemoteSelected(entry.name)} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> </td> <td className="max-w-0 w-full px-4 py-3"> <div className="flex min-w-0 items-center gap-2"> <span className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-slate-100 text-base"> {entry.isDir ? "πŸ“" : "πŸ“„"} </span> {entry.isDir ? ( <button type="button" onClick={() => { if (remoteBucketMatch) { const nextPath = remoteBucketPath ? `${remoteBucketPath}/${entry.name}` : entry.name; const _u = `https://huggingface.co/buckets/${remoteBucketMatch[1]}/${remoteBucketMatch[2]}/tree/${nextPath}`; setRemoteUrl(_u); browseRemote(_u); } }} className="block min-w-0 truncate text-left text-sm font-medium text-violet-700 hover:underline" title={entry.name} > {entry.name} </button> ) : ( <span className="block min-w-0 truncate text-sm font-medium text-slate-800" title={entry.name}>{entry.name}</span> )} </div> </td> <td className="px-4 py-3 text-sm text-slate-500"> <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-semibold ${ entry.isDir ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600" }`}> {entry.isDir ? "folder" : (entry.type || "file")} </span> </td> <td className="px-4 py-3 text-sm tabular-nums text-slate-500">{entry.sizeStr || (entry.size != null ? fmt(entry.size) : "β€”")}</td> <td className="px-4 py-3"> <div className="flex justify-end gap-1 whitespace-nowrap"> <IconBtn title={entry.isDir ? "Download folder" : "Download"} onClick={async () => { if (entry.isDir) { const res = await api.remoteDownloadFolder( remoteUrl.trim(), entry.name, selectedFolder, remoteHfToken.trim() ); if (res.error) { setToast(`Folder download failed: ${res.error}`); } else { setToast(`Started ${res.count || 0} downloads from folder: ${entry.name}`); } } else { const res = await api.remoteDownload( remoteUrl.trim(), entry.name, selectedFolder, (entry as { downloadUrl?: string }).downloadUrl, { hfPath: (entry as { hfPath?: string }).hfPath, hfOrg: (entry as { hfOrg?: string }).hfOrg, hfBucket: (entry as { hfBucket?: string }).hfBucket, }, remoteHfToken.trim() ); if (res.jobId) { setRemoteDownloadJobId(res.jobId); setToast(`Started download: ${entry.name}`); } else if (res.error) { setToast(`Download failed: ${res.error}`); } } }} > <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" /> </svg> </IconBtn> <IconBtn title="Rename" onClick={() => remoteRenameEntry(entry.name)}> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487a2.25 2.25 0 1 1 3.182 3.182L7.5 20.25 3 21l.75-4.5 13.112-12.013Z" /> </svg> </IconBtn> <IconBtn title="Move" onClick={() => remoteMoveEntry(entry.name)}> <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 12h15m0 0-4.5-4.5M19.5 12l-4.5 4.5" /> </svg> </IconBtn> <IconBtn title="Delete" onClick={() => remoteDeleteEntry(entry.name)} danger> <svg className="h-4 w-4" 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 15.916 21.75H8.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 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" /> </svg> </IconBtn> </div> </td> <td className="px-4 py-3 text-sm text-slate-500"> <span className={`inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold ${ entry.isDir ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600" }`}> {entry.isDir ? "folder" : (entry.type || "file")} </span> </td> </tr> ); }) )} </tbody> </table> </div> </div> </div> </div> </section> )} {tab === "telebox" && ( <section className="space-y-6"> <div className="rounded-2xl border border-slate-200 bg-white/95 shadow-sm"> <div className="border-b border-slate-100 px-6 py-5"> <h2 className="text-base font-bold text-slate-900">TeleBox</h2> <p className="text-sm text-slate-500">Browse your TeleBox storage, upload files, and download items into your selected local folder.</p> </div> <div className="space-y-5 p-6"> <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]"> <div className="space-y-2"> <input type="password" value={teleboxToken} onChange={(e) => setTeleboxToken(e.target.value)} placeholder="TeleBox API token (list/upload)" className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="password" value={teleboxWebToken} onChange={(e) => setTeleboxWebToken(e.target.value)} placeholder="TeleBox web session token (download)" className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> </div> <button onClick={() => browseTelebox(teleboxPid, teleboxPath)} disabled={teleboxLoading || !teleboxToken.trim()} className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50" > {teleboxLoading ? "Loading…" : "Load"} </button> </div> {teleboxError && ( <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"> {teleboxError} </div> )} <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600"> <div className="flex flex-wrap items-center gap-2"> <span className="text-xs font-semibold uppercase tracking-wider text-slate-400">Path</span> <button type="button" onClick={goTeleboxRoot} className="rounded-lg bg-white px-2.5 py-1 font-semibold text-violet-700 shadow-sm hover:bg-violet-50" > Root </button> {teleboxPath.map((part, idx) => ( <div key={`${part.id}_${idx}`} className="flex items-center gap-2"> <span className="text-slate-300">/</span> <button type="button" onClick={() => goTeleboxCrumb(idx)} className="rounded-lg bg-white px-2.5 py-1 font-medium text-slate-700 shadow-sm hover:bg-violet-50 hover:text-violet-700" > {part.name} </button> </div> ))} </div> </div> <div className="flex flex-wrap items-center gap-2"> <button onClick={teleboxDownloadSelected} disabled={!teleboxSelected.length || !teleboxToken.trim()} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Download selected to {selectedFolder === "/" ? "/ (root)" : selectedFolder} </button> <button onClick={() => teleboxUploadRef.current?.click()} disabled={!teleboxToken.trim()} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Upload file(s) </button> <input ref={teleboxUploadRef} type="file" multiple className="hidden" onChange={(e) => { uploadTeleboxFiles(e.target.files); e.currentTarget.value = ""; }} /> <button onClick={createTeleboxFolder} disabled={!teleboxToken.trim()} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > New folder </button> <button onClick={() => setTeleboxSelected(teleboxEntries.map((e) => e.id))} disabled={!teleboxEntries.length} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Select all </button> <button onClick={() => setTeleboxSelected([])} disabled={!teleboxSelected.length} className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Clear </button> </div> <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white"> <div className="overflow-x-auto"> <table className="min-w-full table-fixed divide-y divide-slate-100"> <colgroup> <col className="w-14" /> <col /> <col className="w-28" /> <col className="w-28" /> </colgroup> <thead className="bg-slate-50/80"> <tr className="text-left text-xs uppercase tracking-wider text-slate-500"> <th className="px-4 py-3">Sel</th> <th className="w-full px-4 py-3">Name</th> <th className="px-4 py-3">Size</th> <th className="px-4 py-3">Type</th> </tr> </thead> <tbody className="divide-y divide-slate-100"> {!teleboxEntries.length ? ( <tr> <td colSpan={4} className="px-4 py-14 text-center text-sm text-slate-400"> {teleboxLoading ? "Loading TeleBox entries…" : "No TeleBox entries loaded yet."} </td> </tr> ) : ( teleboxEntries.map((entry) => { const selected = teleboxSelected.includes(entry.id); return ( <tr key={entry.id} className={selected ? "bg-violet-50/80" : "hover:bg-slate-50/70"}> <td className="px-4 py-3"> <input type="checkbox" checked={selected} onChange={() => toggleTeleboxSelected(entry.id)} className="h-4 w-4 rounded border-slate-300 text-violet-600 focus:ring-violet-500" /> </td> <td className="min-w-0 px-4 py-3"> <div className="flex min-w-0 items-center gap-2"> <span className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md bg-slate-100 text-xs"> {entry.isDir ? "πŸ“" : "πŸ“„"} </span> {entry.isDir ? ( <button type="button" onClick={() => openTeleboxFolder(entry)} className="block max-w-full min-w-0 flex-1 truncate text-left text-sm font-medium text-violet-700 hover:underline" title={entry.name} > {entry.name} </button> ) : ( <span className="block max-w-full min-w-0 flex-1 truncate text-sm font-medium text-slate-800" title={entry.name}> {entry.name} </span> )} </div> </td> <td className="px-4 py-3 text-sm tabular-nums text-slate-500"> {entry.sizeStr || (entry.size != null ? fmt(entry.size) : "β€”")} </td> <td className="px-4 py-3 text-sm text-slate-500"> <span className={`inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold ${ entry.isDir ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600" }`}> {entry.isDir ? "folder" : (entry.subType || entry.type || "file")} </span> </td> </tr> ); }) )} </tbody> </table> </div> </div> </div> </div> </section> )} {tab === "backblaze" && ( <section className="space-y-4"> <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm space-y-3"> <div> <div className="text-xs font-bold uppercase tracking-wider text-slate-500">S3-compatible storage</div> <p className="mt-0.5 text-xs text-slate-400"> Works with Qencode media storage, Backblaze B2, or any other S3-compatible bucket. Enter the bucket name and the provider's path-style S3 API host β€” for Qencode that's <code>&lt;region&gt;.s3.qencode.com</code>, for Backblaze B2 it's <code>s3.&lt;region&gt;.backblazeb2.com</code>. </p> </div> {b2SavedConnections.length > 0 && ( <div className="flex flex-wrap items-center gap-2"> <select value={b2SelectedConnectionName} onChange={(e) => loadSavedConnection(e.target.value)} className="min-w-0 flex-1 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" > <option value="">Choose a saved connection…</option> {b2SavedConnections.map((c) => ( <option key={c.name} value={c.name}>{c.name}</option> ))} </select> {b2SelectedConnectionName && ( <button onClick={() => deleteSavedConnection(b2SelectedConnectionName)} className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-red-600 hover:bg-red-50" > Delete </button> )} </div> )} <div className="grid gap-2 sm:grid-cols-2"> <input type="text" value={b2BucketName} onChange={(e) => setB2BucketNamePersist(e.target.value)} placeholder="Bucket name (e.g. ogamaa)" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="text" value={b2Region} onChange={(e) => setB2RegionPersist(e.target.value)} placeholder="Region (e.g. us-east-005)" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="text" value={b2Host} onChange={(e) => setB2HostPersist(e.target.value)} placeholder="S3 API host (e.g. s3.us-east-005.backblazeb2.com)" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100 sm:col-span-2" /> <input type="text" value={b2KeyId} onChange={(e) => setB2KeyId(e.target.value)} placeholder="Access Key ID" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="password" value={b2AppKey} onChange={(e) => setB2AppKey(e.target.value)} placeholder="Secret Access Key" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100" /> <input type="text" value={b2EndpointUrl} onChange={(e) => setB2EndpointUrlPersist(e.target.value)} placeholder="Playback/CDN URL, for shareable links only (e.g. https://ogamaa.media-storage.us-west.qencode.com)" className="min-w-0 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm focus:border-violet-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-violet-100 sm:col-span-2" /> <div className="sm:col-span-2 space-y-1"> <input type="text" value={b2CfProxyUrl} onChange={(e) => setB2CfProxyUrl(e.target.value)} placeholder="Cloudflare proxy URL for free downloads (e.g. https://files.medpass.sryze.cc)" className="min-w-0 w-full rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-100" /> <p className="text-xs text-slate-400 px-1"> When set, downloads route through Cloudflare (free, bypasses B2 bandwidth cap). Leave blank to use direct S3. </p> </div> <div className="flex gap-2 sm:col-span-2"> <button onClick={() => browseS3("")} disabled={b2Loading || !b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()} className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50" > {b2Loading ? "Browsing…" : "Browse"} </button> <button onClick={saveCurrentConnection} disabled={!b2BucketName.trim() || !b2Host.trim()} className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Save connection </button> </div> </div> {b2Error && ( <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"> {b2Error} </div> )} <div className="flex items-center justify-between gap-2"> <div className="flex min-w-0 items-center gap-1 overflow-x-auto text-xs text-slate-500"> <button onClick={() => browseS3("")} className="rounded px-1.5 py-0.5 hover:bg-slate-100 font-semibold text-violet-600">root</button> {b2Prefix.split("/").filter(Boolean).map((part, idx, arr) => ( <span key={idx} className="flex items-center gap-1"> <span>/</span> <button onClick={() => browseS3(arr.slice(0, idx + 1).join("/") + "/")} className="rounded px-1.5 py-0.5 hover:bg-slate-100" > {part} </button> </span> ))} </div> <div className="flex items-center gap-2"> <input ref={b2UploadRef} type="file" multiple className="hidden" onChange={(e) => uploadFilesToS3(e.target.files)} /> <button onClick={() => b2UploadRef.current?.click()} disabled={!b2BucketName.trim() || !b2KeyId.trim() || !b2AppKey.trim() || !b2Host.trim()} className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50" > Upload here </button> </div> </div> <div className="overflow-x-auto rounded-xl border border-slate-200"> <table className="w-full text-left text-sm"> <thead className="bg-slate-50 text-xs uppercase tracking-wide text-slate-500"> <tr> <th className="px-4 py-2">Name</th> <th className="px-4 py-2">Size</th> <th className="px-4 py-2">Modified</th> <th className="px-4 py-2 text-right">Actions</th> </tr> </thead> <tbody className="divide-y divide-slate-100"> {b2Entries.length === 0 && ( <tr><td colSpan={4} className="px-4 py-6 text-center text-sm text-slate-400"> {b2Loading ? "Loading…" : "No entries yet β€” enter credentials and click Browse."} </td></tr> )} {b2Entries.map((entry) => ( <tr key={entry.key} className="hover:bg-slate-50/70"> <td className="px-4 py-2"> {entry.isDir ? ( <button onClick={() => browseS3(entry.key)} className="font-medium text-violet-600 hover:underline"> πŸ“ {entry.name} </button> ) : ( <span>{entry.name}</span> )} </td> <td className="px-4 py-2 text-slate-500">{entry.sizeStr || (entry.isDir ? "β€”" : "")}</td> <td className="px-4 py-2 text-slate-500">{entry.lastModified || "β€”"}</td> <td className="px-4 py-2 text-right"> {!entry.isDir && ( <div className="inline-flex items-center gap-1.5"> <IconBtn title="Get shareable link (1 hour)" onClick={() => getS3SignedLink(entry.key)}> <svg className="h-4 w-4" 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="Download" onClick={() => downloadFromS3(entry.key)}> <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8.25h16.5" /> </svg> </IconBtn> <IconBtn title="Delete" onClick={() => deleteFromS3(entry.key)} danger> <svg className="h-4 w-4" 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 15.916 21.75H8.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 0V4.875A2.625 2.625 0 0 0 13.125 2.25h-2.25A2.625 2.625 0 0 0 8.25 4.875V5.25m7.5 0H8.25" /> </svg> </IconBtn> </div> )} </td> </tr> ))} </tbody> </table> </div> </div> </section> )} {showInfoFile && ( <InfoModal file={showInfoFile} onClose={() => setShowInfoFile(null)} /> )} {showPreviewFile && ( <PreviewModal title={showPreviewFile.name} url={`/api/files/${encodeURIComponent(showPreviewFile.id)}/stream`} onClose={() => setShowPreviewFile(null)} /> )} {showCropFile && ( <CropModal file={showCropFile} onClose={() => setShowCropFile(null)} onDone={(values) => { setSettings((prev) => ({ ...prev, cropEnabled: values.cropEnabled, cropLeft: values.cropLeft, cropRight: values.cropRight, cropTop: values.cropTop, cropBottom: values.cropBottom })); setSelectedForEncode(showCropFile.id); setTab("encode"); setShowCropFile(null); setToast(values.cropEnabled ? "Crop settings applied" : "Crop settings cleared"); }} /> )} {showTrimFile && ( <TrimModal file={showTrimFile} onClose={() => setShowTrimFile(null)} onTrimStarted={() => { setToast("Trim job started"); refreshJobs(); }} /> )} {showAdvancedTrimCropFile && ( <AdvancedTrimCropModal file={showAdvancedTrimCropFile} onClose={() => setShowAdvancedTrimCropFile(null)} onProcessingStarted={() => { setToast("Advanced trim & crop job started"); refreshJobs(); }} /> )} {showMoveFiles && ( <MoveModal files={showMoveFiles} folders={folders} onClose={() => setShowMoveFiles(null)} onMoved={() => { setToast("Move completed"); clearSelected(); refreshFiles(); }} /> )} {showMergeFiles && ( <MergeModal files={showMergeFiles} onClose={() => setShowMergeFiles(null)} onMergeStarted={() => { setToast("Merge job started"); refreshJobs(); }} /> )} {showCreateFolder && ( <CreateFolderModal onClose={() => setShowCreateFolder(false)} onCreated={(folder) => { setToast(`Folder created: ${folder}`); refreshFiles(); }} /> )} {showCredentialsModal && ( <CredentialsModal settings={{ b2KeyId, b2AppKey, b2BucketName, b2Host, b2EndpointUrl, b2Region, b2CfProxyUrl, b2SavedConnections, remoteUrl, remoteCredentials, remoteUrlHistory, teleboxToken, teleboxWebToken, encodeAutoS3, uploadDirectToRemote, encodePresets: presets, }} onClose={() => setShowCredentialsModal(false)} onSettingsUpdated={(newSettings) => { // Update all the settings from the merged credentials if (typeof newSettings.b2KeyId === "string") setB2KeyId(newSettings.b2KeyId); if (typeof newSettings.b2AppKey === "string") setB2AppKey(newSettings.b2AppKey); if (typeof newSettings.b2BucketName === "string") { setB2BucketName(newSettings.b2BucketName); try { localStorage.setItem("s3BucketName", newSettings.b2BucketName); } catch {} } if (typeof newSettings.b2Host === "string") { setB2Host(newSettings.b2Host); try { localStorage.setItem("s3Host", newSettings.b2Host); } catch {} } if (typeof newSettings.b2EndpointUrl === "string") { setB2EndpointUrl(newSettings.b2EndpointUrl); try { localStorage.setItem("s3EndpointUrl", newSettings.b2EndpointUrl); } catch {} } if (typeof newSettings.b2Region === "string") { setB2Region(newSettings.b2Region); try { localStorage.setItem("s3Region", newSettings.b2Region); } catch {} } if (typeof newSettings.b2CfProxyUrl === "string") setB2CfProxyUrl(newSettings.b2CfProxyUrl); if (Array.isArray(newSettings.b2SavedConnections)) { setB2SavedConnections(newSettings.b2SavedConnections as SavedS3Connection[]); try { localStorage.setItem("s3SavedConnections", JSON.stringify(newSettings.b2SavedConnections)); } catch {} } if (typeof newSettings.remoteUrl === "string") setRemoteUrl(newSettings.remoteUrl); if (newSettings.remoteCredentials && typeof newSettings.remoteCredentials === 'object') { setRemoteCredentials(newSettings.remoteCredentials as Record<string, RemoteCredentials>); try { localStorage.setItem("remoteCredentials", JSON.stringify(newSettings.remoteCredentials)); } catch {} } if (Array.isArray(newSettings.remoteUrlHistory)) { setRemoteUrlHistory(newSettings.remoteUrlHistory as string[]); try { localStorage.setItem("remoteUrlHistory", JSON.stringify(newSettings.remoteUrlHistory)); } catch {} } if (typeof newSettings.remoteHfToken === "string") setRemoteHfToken(newSettings.remoteHfToken); if (typeof newSettings.remoteHfS3AccessKeyId === "string") setRemoteHfS3AccessKeyId(newSettings.remoteHfS3AccessKeyId); if (typeof newSettings.remoteHfS3SecretAccessKey === "string") setRemoteHfS3SecretAccessKey(newSettings.remoteHfS3SecretAccessKey); if (typeof newSettings.teleboxToken === "string") setTeleboxToken(newSettings.teleboxToken); if (typeof newSettings.teleboxWebToken === "string") setTeleboxWebToken(newSettings.teleboxWebToken); if (typeof newSettings.encodeAutoS3 === "boolean") { setEncodeAutoS3(newSettings.encodeAutoS3); try { localStorage.setItem("encodeAutoS3", newSettings.encodeAutoS3 ? "1" : "0"); } catch {} } if (typeof newSettings.uploadDirectToRemote === "boolean") { setUploadDirectToRemoteState(newSettings.uploadDirectToRemote); try { localStorage.setItem("uploadDirectToRemote", newSettings.uploadDirectToRemote ? "1" : "0"); } catch {} } if (Array.isArray(newSettings.encodePresets)) setPresets(newSettings.encodePresets as EncodePreset[]); }} /> )} {toast && <Toast message={toast} onDone={() => setToast(null)} />} </div> </div> ); }
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { InputHTMLAttributes } from "react";
import type { FileEntry, Job, DownloadJob, VideoInfo, RemoteEntry, TeleboxEntry, BackblazeEntry, Tab, PixeldrainJob, QueueItem, EncodePreset, RemoteCredentials } from "./types";
import { api } from "./api";
import { CloseIcon, FolderIcon, DownloadIcon, UploadIcon, EditIcon, DeleteIcon, DragHandleIcon, ChevronUpIcon, ChevronDownIcon, SpinnerIcon, ListIcon, SelectAllIcon, ClearIcon } from "./icons";
import { AdvancedTrimCropModal } from "./components/AdvancedTrimCropModal";
import { CredentialsModal } from "./components/Modals";
import { normalizeRemoteUrl } from "./utils/credentials";
// ─── 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 formatAspectRatio(width: number, height: number): string {
const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
const divisor = gcd(width, height);
return `${width / divisor}:${height / divisor}`;
}
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 parseLooseTimeToSeconds(input: string): number | null {
const value = input.trim();
if (!value) return null;
const parts = value.split(":").map((p) => p.trim());
if (parts.some((p) => p === "" || Number.isNaN(Number(p)))) return null;
if (parts.length === 2) {
const [mm, ss] = parts.map(Number);
if (mm < 0 || ss < 0 || ss >= 60) return null;
return mm * 60 + ss;
}
if (parts.length === 3) {
const [hh, mm, ss] = parts.map(Number);
if (hh < 0 || mm < 0 || ss < 0 || mm >= 60 || ss >= 60) return null;
return hh * 3600 + mm * 60 + ss;
}
return null;
}
function parsePastedSegments(text: string): { start: string; end: string }[] {