import { lazy, Suspense, useEffect, useState } from "react"; import { qk } from "../lib/queryKeys"; import { useTranslation } from "react-i18next"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Ban, ClipboardPaste, Download, Link2, Pause, Play, PlayCircle, Plus, RotateCcw, Scissors, Settings2, Share2, Pencil, Trash2, UploadCloud, } from "lucide-react"; import Tabs from "./ui/Tabs"; import { PageToolbar } from "./ui/PageShell"; import { LoadingState, StateMessage } from "./ui/QueryState"; // Lazy: these dialogs/editors open on demand, so they stay out of the Downloads page chunk until // used (the video editor in particular is heavy — filmstrip + scrubber). const DownloadDialog = lazy(() => import("./DownloadDialog")); const UploadDialog = lazy(() => import("./UploadDialog")); const ProfileEditor = lazy(() => import("./ProfileEditor")); const VideoEditor = lazy(() => import("./VideoEditor")); const ShareDialog = lazy(() => import("./ShareDialog")); const LibraryPlayer = lazy(() => import("./LibraryPlayer")); import { useConfirm } from "./ConfirmProvider"; import { useLiveQuery } from "../lib/useLiveQuery"; import { useMe } from "../lib/useMe"; import { api, type DownloadJob } from "../lib/api"; import { invalidateDownloads, quickShareLink } from "../lib/downloads"; import { libraryRowActions, sharedRowActions } from "../lib/downloadActions"; import { inputCls } from "./ui/form"; import { Button } from "./ui/Button"; import { DownloadRow, IconBtn, UsageBar } from "./downloadRow"; import { MetaEditModal, ErrorModal } from "./downloadModals"; import { AdminSystem } from "./downloadAdmin"; export default function DownloadCenter() { const me = useMe(); const { t } = useTranslation(); const qc = useQueryClient(); const confirm = useConfirm(); // Always land on the queue tab (not a persisted last-tab) — the queue is where new work and // any failures are, so it's the useful default every visit. const [tab, setTab] = useState("queue"); const [addUrl, setAddUrl] = useState(""); const [addSource, setAddSource] = useState(null); const [upload, setUpload] = useState(false); const [manage, setManage] = useState(false); const [metaJob, setMetaJob] = useState(null); const [shareJob, setShareJob] = useState(null); const [playJob, setPlayJob] = useState(null); const [editJob, setEditJob] = useState(null); const [errorJob, setErrorJob] = useState(null); // Poll fast (2s) while work is actually in flight; back off to 15s once the queue is settled // (only done/error/paused rows left, which don't advance on their own) so an idle Download Center // isn't hitting the API — and adding to the shared box's load — every 2s for nothing. const jobsQ = useLiveQuery(qk.downloads(), api.downloads, { intervalMs: (data) => data?.some((j) => j.status === "queued" || j.status === "running") ? 2000 : 15000, }); const sharedQ = useQuery({ queryKey: qk.downloadsShared(), queryFn: api.downloadsShared, enabled: tab === "shared", }); const jobs = jobsQ.data ?? []; const queue = jobs.filter((j) => ["queued", "running", "paused", "error"].includes(j.status)); const library = jobs.filter((j) => j.status === "done"); const invalidate = () => invalidateDownloads(qc); const act = useMutation({ mutationFn: ({ id, op, }: { id: number; op: "pause" | "resume" | "cancel" | "delete" | "redownload"; }) => op === "pause" ? api.pauseDownload(id) : op === "resume" ? api.resumeDownload(id) : op === "cancel" ? api.cancelDownload(id) : op === "redownload" ? api.redownloadDownload(id) : api.deleteDownload(id), onSuccess: invalidate, // No onError: a failed job action returns 400/409/422/500, already surfaced by the global // error modal (api.ts req) with the backend's specific message — a caller toast would double it. }); // Remove a shared-with-me item from your list (only your grant; the owner's file is untouched). const removeShared = useMutation({ mutationFn: (id: number) => api.removeSharedDownload(id), onSuccess: () => qc.invalidateQueries({ queryKey: qk.downloadsShared() }), }); const confirmThen = async (title: string, body: string, fn: () => void) => { if (await confirm({ title, message: body, confirmLabel: title, danger: true })) fn(); }; // One-click share (E7 S3 · D2-A): ensure a downloadable link, copy it, toast with "open in new tab" // (see quickShareLink). Re-clicking reuses the existing link; a per-job in-flight guard also stops a // double-click from racing two POSTs into two links before the cache is primed. Advanced controls // (password, expiry, revoke, share-with-a-user) live in the Share dialog, via the manage-share button. const [sharingId, setSharingId] = useState(null); const quickShare = async (job: DownloadJob) => { if (sharingId !== null) return; setSharingId(job.id); try { await quickShareLink(qc, job, t); } finally { setSharingId(null); } }; // Pull a link off the clipboard into the add-URL box. Clipboard reads need a secure context + // a user gesture/permission (iOS Safari/Brave are strict) — so this is best-effort: the paste // button is an explicit gesture (reliable), and the input's onFocus tries silently (ignored if // the browser refuses without a click). Only accept an http(s) URL, don't clobber existing text. const pasteFromClipboard = async (force = false) => { if (!force && addUrl.trim()) return; try { const text = (await navigator.clipboard?.readText())?.trim(); if (text && /^https?:\/\/\S+$/i.test(text)) setAddUrl(text); } catch { /* permission denied or unsupported — the manual paste button still works on a click */ } }; const tabs = [ { id: "queue", label: t("downloads.tabs.queue"), badge: queue.length }, { id: "done", label: t("downloads.tabs.done"), badge: library.length }, { id: "shared", label: t("downloads.tabs.shared") }, ...(me.role === "admin" ? [{ id: "system", label: t("downloads.tabs.system") }] : []), ]; // Guard against the active tab going away under us (e.g. admin on "system" gets demoted mid-session) // — that would render a blank page with no active tab. Fall back to the default. useEffect(() => { if (!tabs.some((tb) => tb.id === tab)) setTab("queue"); // eslint-disable-next-line react-hooks/exhaustive-deps }, [tab, me.role]); const saveBtn = (job: DownloadJob) => ( ); return ( <> {/* Page title + subtitle + tabs are fixed chrome; the tab content scrolls under them. */}

{t("downloads.page.title")}

{t("downloads.page.subtitle")}

{tab === "queue" && ( <>
setAddUrl(e.target.value)} onFocus={() => pasteFromClipboard()} onKeyDown={(e) => e.key === "Enter" && addUrl.trim() && setAddSource(addUrl.trim())} placeholder={t("downloads.page.addUrl")} className={inputCls} /> {/* Local upload is a peer to "add a URL": a general file → the same library (E7 S5c). */}
{queue.map((job) => ( {(job.status === "queued" || job.status === "running") && ( act.mutate({ id: job.id, op: "pause" })} title={t("downloads.actions.pause")} > )} {(job.status === "paused" || job.status === "error") && ( act.mutate({ id: job.id, op: "resume" })} title={t( job.status === "error" ? "downloads.actions.retry" : "downloads.actions.resume", )} > )} confirmThen( t("downloads.confirm.cancelTitle"), t("downloads.confirm.cancelBody"), () => act.mutate({ id: job.id, op: "cancel" }), ) } title={t("downloads.actions.cancel")} danger > ))} {queue.length === 0 && (jobsQ.isError && !jobsQ.data ? ( jobsQ.refetch()}> {t("common.loadError")} ) : jobsQ.isLoading ? ( ) : (
{t("downloads.empty.queue")}
))}
)} {tab === "done" && ( <>
{library.map((job) => { // Row actions gated on the stored media_kind + job_kind (see downloadActions). const a = libraryRowActions(job); return ( {a.play && ( setPlayJob(job)} title={t("downloads.actions.play")}> )} {saveBtn(job)} {a.edit && ( setEditJob(job)} title={t("downloads.actions.edit")}> )} {a.editDetails && ( setMetaJob(job)} title={t("downloads.actions.editDetails")} > )} quickShare(job)} title={t("downloads.actions.share")}> setShareJob(job)} title={t("downloads.actions.shareManage")} > {a.redownload && ( confirmThen( t("downloads.confirm.redownloadTitle"), t("downloads.confirm.redownloadBody"), () => act.mutate({ id: job.id, op: "redownload" }), ) } title={t("downloads.actions.redownload")} > )} confirmThen( t("downloads.confirm.deleteTitle"), t("downloads.confirm.deleteBody"), () => act.mutate({ id: job.id, op: "delete" }), ) } title={t("downloads.actions.delete")} danger > ); })} {library.length === 0 && (jobsQ.isError && !jobsQ.data ? ( jobsQ.refetch()}> {t("common.loadError")} ) : jobsQ.isLoading ? ( ) : (
{t("downloads.empty.done")}
))}
)} {tab === "shared" && (
{(sharedQ.data ?? []).map((job) => { // Same media_kind + can_download gate as the library, via the shared helper (S5b). const a = sharedRowActions(job); return ( {a.play && ( setPlayJob(job)} title={t("downloads.actions.play")}> )} {a.save && saveBtn(job)} {a.edit && ( setEditJob(job)} title={t("downloads.actions.edit")}> )} confirmThen( t("downloads.confirm.removeSharedTitle"), t("downloads.confirm.removeSharedBody"), () => removeShared.mutate(job.id), ) } title={t("downloads.actions.removeShared")} danger > ); })} {(sharedQ.data ?? []).length === 0 && (sharedQ.isError && !sharedQ.data ? ( sharedQ.refetch()}> {t("common.loadError")} ) : sharedQ.isLoading ? ( ) : (
{t("downloads.empty.shared")}
))}
)} {tab === "system" && me.role === "admin" && } {addSource && ( { setAddSource(null); setAddUrl(""); }} /> )} {upload && setUpload(false)} />} {manage && setManage(false)} />} {metaJob && setMetaJob(null)} />} {shareJob && setShareJob(null)} />} {playJob && setPlayJob(null)} />} {editJob && setEditJob(null)} />} {errorJob && ( act.mutate({ id: errorJob.id, op: "resume" })} onClose={() => setErrorJob(null)} /> )}
); }