jobs: download-job UI — panel decision screen + live progress + /jobs renderer
Front half of the download-job feature. Panel (VideoDownloadPanel): after Fetch expands a playlist and the count is known, a decision screen — "Found N items" → pick Audio/Video + subfolder → "Download all as a job" (POST /jobs/download), or "fetch inline to pick individually" (the existing card grid). A single video still goes straight to the inline card. The job phase shows live two-phase progress (polled from the job) + a "View in Jobs" link; it notes the job runs server-side so closing the panel is fine, and it refreshes the browser as each file lands. /jobs (DownloadJobDetail + JobsPage dispatch): a `download` job renders a compact two-phase readout — Metadata and Download bars (processed/total, found/skipped and saved/failed) + the current item — polled from the job's progress, with a Stop. Executor tweak: phase-1 meta.done now counts kept (not processed) so both phases read the same `(done+failed)/total`. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,31 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router';
|
||||
import { usePanelChannel } from 'hooks/usePanelChannel';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Download, Loader2, ChevronLeft, AlertCircle, Check, Music, Film, Folder } from 'lucide-react';
|
||||
import {
|
||||
Download,
|
||||
Loader2,
|
||||
ChevronLeft,
|
||||
AlertCircle,
|
||||
Check,
|
||||
Music,
|
||||
Film,
|
||||
Folder,
|
||||
ExternalLink,
|
||||
CheckCircle2,
|
||||
} from 'lucide-react';
|
||||
import { useFilesAPI, type VideoInfo } from '../../hooks/useFilesAPI';
|
||||
|
||||
// Compact progress shape mirrored from the download-job executor (done = successes, failed = skipped).
|
||||
type JobCounts = { done: number; failed: number; total: number };
|
||||
type JobProgress = {
|
||||
phase: 'expanding' | 'metadata' | 'download' | 'done';
|
||||
meta: JobCounts;
|
||||
dl: JobCounts;
|
||||
current?: string;
|
||||
};
|
||||
|
||||
// Ephemeral side-panel video downloader. Opens on the `download` search param (target folder) with
|
||||
// `downloadRoot` the file-browser root. Self-contained: prefetches metadata (ReClip via the platform
|
||||
// proxy), then downloads per entry in a chosen FORMAT (video or audio) as background jobs, bumping the
|
||||
@@ -137,18 +158,27 @@ export const VideoDownloadPanel = () => {
|
||||
const basePath = searchParams.get('download') ?? '/';
|
||||
const root = searchParams.get('downloadRoot') ?? 'home';
|
||||
const files = useFilesAPI(root);
|
||||
const client = useClient();
|
||||
const navigate = useNavigate();
|
||||
const [, setRefreshSignal] = usePanelChannel<number>('files:refresh-signal', 0);
|
||||
|
||||
const [phase, setPhase] = useState<'input' | 'preview'>('input');
|
||||
const [phase, setPhase] = useState<'input' | 'decide' | 'preview' | 'job'>('input');
|
||||
const [url, setUrl] = useState('');
|
||||
const [expandedUrls, setExpandedUrls] = useState<string[]>([]); // playlist items (count + inline)
|
||||
const [subfolder, setSubfolder] = useState('');
|
||||
const [fetching, setFetching] = useState(false);
|
||||
const [inputError, setInputError] = useState('');
|
||||
const [entries, setEntries] = useState<Entry[]>([]);
|
||||
const [mode, setMode] = useState<'normal' | 'select'>('normal');
|
||||
const [sel, setSel] = useState<Record<number, { video?: boolean; audio?: boolean }>>({});
|
||||
const [bulk, setBulk] = useState<{ done: number; total: number } | null>(null);
|
||||
const [jobFormat, setJobFormat] = useState<Fmt>('audio');
|
||||
const [jobId, setJobId] = useState<string | null>(null);
|
||||
const [jobProg, setJobProg] = useState<JobProgress | null>(null);
|
||||
const [jobStatus, setJobStatus] = useState<string>('running');
|
||||
const entriesRef = useRef(entries);
|
||||
entriesRef.current = entries;
|
||||
const lastDlDone = useRef(0);
|
||||
|
||||
const isPlaylist = entries.length > 1;
|
||||
const anyReadyVideo = entries.some((e) => e.status === 'ready' && e.hasVideo);
|
||||
@@ -160,36 +190,36 @@ export const VideoDownloadPanel = () => {
|
||||
const patchFmt = (i: number, fmt: Fmt, p: Partial<FmtState>) =>
|
||||
setEntries((prev) => prev.map((e, idx) => (idx === i ? { ...e, [fmt]: { ...e[fmt], ...p } } : e)));
|
||||
|
||||
const fetchMeta = async () => {
|
||||
// Fetch = expand. A playlist goes to the decision screen (inline vs job) now that we know the count; a
|
||||
// single video goes straight to the inline card.
|
||||
const onFetch = async () => {
|
||||
const u = url.trim();
|
||||
if (!u) return;
|
||||
setFetching(true);
|
||||
setInputError('');
|
||||
setEntries([]);
|
||||
setMode('normal');
|
||||
setBulk(null);
|
||||
setSel({});
|
||||
|
||||
let urls = [u];
|
||||
if (u.includes('list=')) {
|
||||
setFetching(true);
|
||||
const pl = await files.videoPlaylist(u).catch(() => null);
|
||||
if (pl?.error) {
|
||||
setEntries([
|
||||
{
|
||||
url: u,
|
||||
status: 'error',
|
||||
error: pl.error,
|
||||
hasVideo: false,
|
||||
video: { phase: 'idle' },
|
||||
audio: { phase: 'idle' },
|
||||
},
|
||||
]);
|
||||
setPhase('preview');
|
||||
setFetching(false);
|
||||
return;
|
||||
}
|
||||
if (pl?.urls?.length) urls = pl.urls;
|
||||
setFetching(false);
|
||||
if (pl?.error || !pl?.urls?.length) return setInputError(pl?.error || 'No videos found in that playlist');
|
||||
setExpandedUrls(pl.urls);
|
||||
setPhase('decide');
|
||||
} else {
|
||||
setExpandedUrls([u]);
|
||||
setPhase('preview');
|
||||
void fetchInline([u]);
|
||||
}
|
||||
};
|
||||
|
||||
// Interactive path: fetch each item's metadata sequentially, populating the cards.
|
||||
const fetchInline = async (urls: string[]) => {
|
||||
setFetching(true);
|
||||
setMode('normal');
|
||||
setBulk(null);
|
||||
setSel({});
|
||||
setEntries(
|
||||
urls.map((v) => ({
|
||||
url: v,
|
||||
@@ -199,9 +229,6 @@ export const VideoDownloadPanel = () => {
|
||||
audio: { phase: 'idle' },
|
||||
})),
|
||||
);
|
||||
setPhase('preview');
|
||||
|
||||
// Sequentially (ReClip runs yt-dlp per video); cards fill in as they resolve.
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
const info = await files.videoInfo(urls[i]!).catch((): VideoInfo => ({ error: 'Could not fetch info' }));
|
||||
if (info.error) patch(i, { status: 'error', error: info.error, hasVideo: false });
|
||||
@@ -218,6 +245,51 @@ export const VideoDownloadPanel = () => {
|
||||
setFetching(false);
|
||||
};
|
||||
|
||||
// Job path: hand the whole playlist to a server-side two-phase download job (own lane, survives the
|
||||
// panel closing). The server re-expands + fetches metadata (phase 1) then downloads survivors (phase 2).
|
||||
const startJob = async () => {
|
||||
try {
|
||||
const res = await client.post<{ jobId: string; status: string }>('/jobs/download', {
|
||||
url: url.trim(),
|
||||
format: jobFormat,
|
||||
dir: targetDir(),
|
||||
root,
|
||||
label: `${jobFormat === 'audio' ? 'Audio' : 'Video'} · ${expandedUrls.length} items`,
|
||||
});
|
||||
lastDlDone.current = 0;
|
||||
setJobId(res.jobId);
|
||||
setJobStatus(res.status === 'pending' ? 'pending' : 'running');
|
||||
setJobProg(null);
|
||||
setPhase('job');
|
||||
} catch {
|
||||
setInputError('Could not start the job');
|
||||
}
|
||||
};
|
||||
|
||||
// Poll the running job's progress; refresh the browser as each file lands.
|
||||
useEffect(() => {
|
||||
if (phase !== 'job' || !jobId) return;
|
||||
let cancelled = false;
|
||||
const poll = async () => {
|
||||
const j = await client.get<{ status: string; progress: JobProgress | null }>(`/jobs/${jobId}`).catch(() => null);
|
||||
if (cancelled || !j) return;
|
||||
setJobStatus(j.status);
|
||||
setJobProg(j.progress);
|
||||
if (j.progress && j.progress.dl.done > lastDlDone.current) {
|
||||
lastDlDone.current = j.progress.dl.done;
|
||||
setRefreshSignal((n) => n + 1);
|
||||
}
|
||||
if (['completed', 'failed', 'stopped', 'interrupted'].includes(j.status)) clearInterval(timer);
|
||||
};
|
||||
void poll();
|
||||
const timer = setInterval(poll, 2000);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(timer);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [phase, jobId]);
|
||||
|
||||
const targetDir = () => {
|
||||
const s = sanitizeFolder(subfolder);
|
||||
if (!s) return basePath;
|
||||
@@ -284,11 +356,11 @@ export const VideoDownloadPanel = () => {
|
||||
<span className="truncate">Saving to {folderLabel}</span>
|
||||
</div>
|
||||
|
||||
{phase === 'input' ? (
|
||||
{phase === 'input' && (
|
||||
<form
|
||||
onSubmit={(ev) => {
|
||||
ev.preventDefault();
|
||||
void fetchMeta();
|
||||
void onFetch();
|
||||
}}
|
||||
className="flex flex-col gap-3"
|
||||
>
|
||||
@@ -299,6 +371,7 @@ export const VideoDownloadPanel = () => {
|
||||
placeholder="https://www.youtube.com/watch?v=… or …/playlist?list=…"
|
||||
className="h-10 w-full rounded-md border border-duck-dark/20 bg-background/60 px-3 text-sm text-duck-dark outline-none placeholder:text-duck-dark/40 focus:border-duck-teal/50"
|
||||
/>
|
||||
{inputError && <p className="text-xs text-red-500">{inputError}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!url.trim() || fetching}
|
||||
@@ -308,12 +381,84 @@ export const VideoDownloadPanel = () => {
|
||||
Fetch
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
)}
|
||||
|
||||
{phase === 'decide' && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhase('input')}
|
||||
className="flex cursor-pointer items-center gap-1 self-start text-sm text-duck-dark/60 hover:text-duck-dark"
|
||||
>
|
||||
<ChevronLeft size={15} /> Back
|
||||
</button>
|
||||
<p className="text-sm text-duck-dark">
|
||||
Found <span className="font-semibold">{expandedUrls.length}</span> items.
|
||||
</p>
|
||||
<input
|
||||
value={subfolder}
|
||||
onChange={(ev) => setSubfolder(ev.target.value)}
|
||||
placeholder="Subfolder (optional) — leave blank for this folder"
|
||||
className="h-9 w-full rounded-md border border-duck-dark/20 bg-background/60 px-3 text-sm text-duck-dark outline-none placeholder:text-duck-dark/40 focus:border-duck-teal/50"
|
||||
/>
|
||||
<div className="flex gap-1">
|
||||
{(['audio', 'video'] as Fmt[]).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
type="button"
|
||||
onClick={() => setJobFormat(f)}
|
||||
className={`flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md px-3 py-2 text-sm font-medium transition-colors ${
|
||||
jobFormat === f
|
||||
? 'bg-duck-teal text-duck-yellow'
|
||||
: 'border border-duck-dark/20 text-duck-dark/70 hover:bg-duck-dark/5'
|
||||
}`}
|
||||
>
|
||||
{f === 'audio' ? <Music size={14} /> : <Film size={14} />} {f === 'audio' ? 'Audio' : 'Video'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void startJob()}
|
||||
className={`${btn} flex items-center justify-center gap-2 bg-duck-teal text-duck-yellow hover:bg-duck-teal/90`}
|
||||
>
|
||||
<Download size={15} /> Download all as a job
|
||||
</button>
|
||||
{inputError && <p className="text-xs text-red-500">{inputError}</p>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setPhase('preview');
|
||||
void fetchInline(expandedUrls);
|
||||
}}
|
||||
className="cursor-pointer text-xs text-duck-dark/50 hover:text-duck-dark/80"
|
||||
>
|
||||
or fetch inline to pick individually
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === 'job' && (
|
||||
<JobView
|
||||
prog={jobProg}
|
||||
status={jobStatus}
|
||||
audio={jobFormat === 'audio'}
|
||||
onOpen={() => jobId && navigate(`/jobs/${jobId}`)}
|
||||
onNew={() => {
|
||||
setPhase('input');
|
||||
setUrl('');
|
||||
setJobId(null);
|
||||
setJobProg(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{phase === 'preview' && (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhase('input')}
|
||||
onClick={() => setPhase(expandedUrls.length > 1 ? 'decide' : 'input')}
|
||||
className="flex cursor-pointer items-center gap-1 text-sm text-duck-dark/60 hover:text-duck-dark"
|
||||
>
|
||||
<ChevronLeft size={15} /> Back
|
||||
@@ -408,6 +553,103 @@ export const VideoDownloadPanel = () => {
|
||||
);
|
||||
};
|
||||
|
||||
// ── Job progress view ──
|
||||
|
||||
const jobPct = (c: JobCounts) => (c.total ? ((c.done + c.failed) / c.total) * 100 : 0);
|
||||
|
||||
const JobView = ({
|
||||
prog,
|
||||
status,
|
||||
audio,
|
||||
onOpen,
|
||||
onNew,
|
||||
}: {
|
||||
prog: JobProgress | null;
|
||||
status: string;
|
||||
audio: boolean;
|
||||
onOpen: () => void;
|
||||
onNew: () => void;
|
||||
}) => {
|
||||
const terminal = ['completed', 'failed', 'stopped', 'interrupted'].includes(status);
|
||||
const phaseLabel =
|
||||
!prog || prog.phase === 'expanding'
|
||||
? 'Preparing…'
|
||||
: prog.phase === 'metadata'
|
||||
? 'Fetching metadata'
|
||||
: prog.phase === 'download'
|
||||
? 'Downloading'
|
||||
: 'Done';
|
||||
const Bar = ({ label, c, saved, failed }: { label: string; c: JobCounts; saved: string; failed: string }) => (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between text-xs">
|
||||
<span className="font-medium text-duck-dark">{label}</span>
|
||||
<span className="tabular-nums text-duck-dark/50">
|
||||
{c.done + c.failed}/{c.total || '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-duck-dark/10">
|
||||
<div
|
||||
className="h-full rounded-full bg-duck-teal transition-all duration-300"
|
||||
style={{ width: `${jobPct(c)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-3 text-[10px] text-duck-dark/50">
|
||||
<span className="text-duck-teal">
|
||||
{c.done} {saved}
|
||||
</span>
|
||||
{c.failed > 0 && (
|
||||
<span className="text-red-500/80">
|
||||
{c.failed} {failed}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{terminal ? (
|
||||
status === 'completed' ? (
|
||||
<CheckCircle2 size={16} className="text-duck-teal" />
|
||||
) : (
|
||||
<AlertCircle size={16} className="text-red-500" />
|
||||
)
|
||||
) : (
|
||||
<Loader2 size={16} className="animate-spin text-amber-500" />
|
||||
)}
|
||||
<span className="font-medium text-duck-dark">
|
||||
{terminal ? status[0]!.toUpperCase() + status.slice(1) : phaseLabel}
|
||||
</span>
|
||||
<span className="ml-auto text-xs text-duck-dark/40">{audio ? 'Audio' : 'Video'}</span>
|
||||
</div>
|
||||
<Bar label="Metadata" c={prog?.meta ?? { done: 0, failed: 0, total: 0 }} saved="found" failed="skipped" />
|
||||
<Bar label="Download" c={prog?.dl ?? { done: 0, failed: 0, total: 0 }} saved="saved" failed="failed" />
|
||||
{!terminal && prog?.phase === 'download' && prog.current && (
|
||||
<p className="truncate text-xs text-duck-dark/50" title={prog.current}>
|
||||
{prog.current}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-duck-teal/40 px-3 py-2 text-sm font-medium text-duck-teal hover:bg-duck-teal/10"
|
||||
>
|
||||
<ExternalLink size={14} /> View in Jobs
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onNew}
|
||||
className="cursor-pointer rounded-md px-3 py-2 text-sm text-duck-dark/60 hover:bg-duck-dark/5"
|
||||
>
|
||||
New
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[11px] text-duck-dark/40">Runs on the server — you can close this panel; it keeps going.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ── Cards ──
|
||||
|
||||
const GridCard = ({
|
||||
|
||||
Reference in New Issue
Block a user