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:
@@ -0,0 +1,233 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useParams, Link } from 'react-router';
|
||||
import { Loader2, CheckCircle2, XCircle, Ban, Clock, ArrowLeft, Square, Film, Music } from 'lucide-react';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// Detail view for a `download` job — a compact two-phase progress readout (metadata → download), polled
|
||||
// from the job's persisted progress (the executor emits counter snapshots, not per-item events).
|
||||
|
||||
type Counts = { done: number; failed: number; total: number };
|
||||
type DownloadProgress = {
|
||||
phase: 'expanding' | 'metadata' | 'download' | 'done';
|
||||
meta: Counts;
|
||||
dl: Counts;
|
||||
current?: string;
|
||||
};
|
||||
type DownloadJob = {
|
||||
id: string;
|
||||
mode: string;
|
||||
taskName: string;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'interrupted';
|
||||
error: string | null;
|
||||
cwd: string | null;
|
||||
inputs?: Record<string, unknown> | null;
|
||||
progress: DownloadProgress | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const POLL_MS = 1500;
|
||||
const isTerminal = (s: string) => s === 'completed' || s === 'failed' || s === 'stopped' || s === 'interrupted';
|
||||
|
||||
const statusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case 'running':
|
||||
return {
|
||||
icon: <Loader2 className="h-4 w-4 animate-spin" />,
|
||||
label: 'Running',
|
||||
cls: 'text-amber-600 dark:text-amber-500',
|
||||
};
|
||||
case 'pending':
|
||||
return { icon: <Clock className="h-4 w-4" />, label: 'Queued', cls: 'text-blue-600 dark:text-blue-400' };
|
||||
case 'completed':
|
||||
return { icon: <CheckCircle2 className="h-4 w-4" />, label: 'Completed', cls: 'text-duck-teal' };
|
||||
case 'failed':
|
||||
return { icon: <XCircle className="h-4 w-4" />, label: 'Failed', cls: 'text-red-600 dark:text-red-400' };
|
||||
case 'stopped':
|
||||
return { icon: <Ban className="h-4 w-4" />, label: 'Stopped', cls: 'text-duck-dark/50 dark:text-foreground/50' };
|
||||
default:
|
||||
return {
|
||||
icon: <XCircle className="h-4 w-4" />,
|
||||
label: 'Interrupted',
|
||||
cls: 'text-orange-600 dark:text-orange-400',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// A labelled progress bar: fill = processed/total; the caption states saved vs skipped/failed.
|
||||
const PhaseBar = ({
|
||||
label,
|
||||
c,
|
||||
active,
|
||||
savedLabel,
|
||||
failedLabel,
|
||||
}: {
|
||||
label: string;
|
||||
c: Counts;
|
||||
active: boolean;
|
||||
savedLabel: string;
|
||||
failedLabel: string;
|
||||
}) => {
|
||||
const processed = c.done + c.failed;
|
||||
const pct = c.total ? (processed / c.total) * 100 : 0;
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span
|
||||
className={`font-medium ${active ? 'text-duck-dark dark:text-foreground' : 'text-duck-dark/50 dark:text-foreground/50'}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span className="tabular-nums text-duck-dark/50 dark:text-foreground/50">
|
||||
{processed}/{c.total || '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-duck-dark/10 dark:bg-foreground/10">
|
||||
<div className="h-full rounded-full bg-duck-teal transition-all duration-300" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
<div className="flex gap-3 text-[11px] text-duck-dark/50 dark:text-foreground/50">
|
||||
<span className="text-duck-teal">
|
||||
{c.done} {savedLabel}
|
||||
</span>
|
||||
{c.failed > 0 && (
|
||||
<span className="text-red-500/80">
|
||||
{c.failed} {failedLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const DownloadJobDetail = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const client = useClient();
|
||||
const [job, setJob] = useState<DownloadJob | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
try {
|
||||
const j = await client.get<DownloadJob>(`/jobs/${id}`);
|
||||
if (!cancelled) setJob(j);
|
||||
return j;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
};
|
||||
void load();
|
||||
const timer = setInterval(async () => {
|
||||
const j = await load();
|
||||
if (j && isTerminal(j.status)) clearInterval(timer);
|
||||
}, POLL_MS);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
const stop = async () => {
|
||||
if (!id) return;
|
||||
try {
|
||||
await client.post(`/jobs/${id}/stop`, {});
|
||||
toast.success('Stop requested');
|
||||
} catch {
|
||||
toast.error('Failed to stop');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center text-duck-dark/50 dark:text-foreground/50">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
if (!job)
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center gap-3 text-duck-dark/60 dark:text-foreground/60">
|
||||
<span>Job not found.</span>
|
||||
<Link to="/jobs" className="text-duck-teal hover:underline">
|
||||
Back to jobs
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
const badge = statusBadge(job.status);
|
||||
const running = !isTerminal(job.status);
|
||||
const p = job.progress;
|
||||
const isAudio = job.inputs?.format !== 'video';
|
||||
const phaseLabel =
|
||||
!p || p.phase === 'expanding'
|
||||
? 'Preparing…'
|
||||
: p.phase === 'metadata'
|
||||
? 'Fetching metadata'
|
||||
: p.phase === 'download'
|
||||
? 'Downloading'
|
||||
: 'Done';
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
<div className="px-5 py-3 border-b border-duck-dark/10 flex items-center gap-3">
|
||||
<Link
|
||||
to="/jobs"
|
||||
className="text-duck-dark/50 dark:text-foreground/50 hover:text-duck-dark dark:hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Link>
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{isAudio ? (
|
||||
<Music className="h-4 w-4 shrink-0 text-duck-teal" />
|
||||
) : (
|
||||
<Film className="h-4 w-4 shrink-0 text-duck-teal" />
|
||||
)}
|
||||
<div className="flex flex-col min-w-0">
|
||||
<span className="text-sm font-medium text-duck-dark dark:text-foreground truncate">{job.taskName}</span>
|
||||
{job.cwd && <span className="text-xs text-duck-dark/40 dark:text-foreground/40 truncate">→ {job.cwd}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<span className={`ml-auto flex items-center gap-1.5 text-sm ${badge.cls}`}>
|
||||
{badge.icon} {badge.label}
|
||||
</span>
|
||||
{running && (
|
||||
<button
|
||||
onClick={stop}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-red-500/10 text-red-600 dark:text-red-400 hover:bg-red-500/20 cursor-pointer transition-colors"
|
||||
>
|
||||
<Square className="h-3 w-3" /> Stop
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-5">
|
||||
<div className="mx-auto flex max-w-md flex-col gap-5">
|
||||
<div className="text-sm text-duck-dark/60 dark:text-foreground/60">{phaseLabel}</div>
|
||||
<PhaseBar
|
||||
label="Metadata"
|
||||
c={p?.meta ?? { done: 0, failed: 0, total: 0 }}
|
||||
active={p?.phase === 'metadata'}
|
||||
savedLabel="found"
|
||||
failedLabel="skipped"
|
||||
/>
|
||||
<PhaseBar
|
||||
label="Download"
|
||||
c={p?.dl ?? { done: 0, failed: 0, total: 0 }}
|
||||
active={p?.phase === 'download'}
|
||||
savedLabel="saved"
|
||||
failedLabel="failed"
|
||||
/>
|
||||
{running && p?.phase === 'download' && p.current && (
|
||||
<div className="truncate text-xs text-duck-dark/50 dark:text-foreground/50" title={p.current}>
|
||||
<Loader2 className="mr-1.5 inline h-3 w-3 animate-spin" />
|
||||
{p.current}
|
||||
</div>
|
||||
)}
|
||||
{job.error && !running && <div className="text-xs text-red-600 dark:text-red-400">{job.error}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,11 +1,23 @@
|
||||
import { useState, useEffect, useCallback, type ReactNode, type MouseEvent } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router';
|
||||
import { Search, CheckCircle2, AlertCircle, Clock, Loader2, StopCircle, AlertTriangle, Inbox, Square, Trash2 } from 'lucide-react';
|
||||
import {
|
||||
Search,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Clock,
|
||||
Loader2,
|
||||
StopCircle,
|
||||
AlertTriangle,
|
||||
Inbox,
|
||||
Square,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { WorkspaceLayout } from 'officerdev';
|
||||
import type { LayoutNode, PanelComponents } from 'officerdev';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
import { Card } from '@/components/Card';
|
||||
import { ScriptJobDetail } from './ScriptJobDetail';
|
||||
import { DownloadJobDetail } from './DownloadJobDetail';
|
||||
import { PipelineJobDetail } from './JobDetail';
|
||||
|
||||
type JobSummary = {
|
||||
@@ -28,12 +40,18 @@ const formatDate = (iso: string) =>
|
||||
|
||||
const StatusIcon = ({ status }: { status: JobSummary['status'] }) => {
|
||||
switch (status) {
|
||||
case 'completed': return <CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />;
|
||||
case 'failed': return <AlertCircle className="h-4 w-4 text-red-500 shrink-0" />;
|
||||
case 'running': return <Loader2 className="h-4 w-4 text-blue-500 shrink-0 animate-spin" />;
|
||||
case 'stopped': return <StopCircle className="h-4 w-4 text-amber-500 shrink-0" />;
|
||||
case 'interrupted': return <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />;
|
||||
case 'pending': return <Clock className="h-4 w-4 text-duck-dark/40 shrink-0" />;
|
||||
case 'completed':
|
||||
return <CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />;
|
||||
case 'failed':
|
||||
return <AlertCircle className="h-4 w-4 text-red-500 shrink-0" />;
|
||||
case 'running':
|
||||
return <Loader2 className="h-4 w-4 text-blue-500 shrink-0 animate-spin" />;
|
||||
case 'stopped':
|
||||
return <StopCircle className="h-4 w-4 text-amber-500 shrink-0" />;
|
||||
case 'interrupted':
|
||||
return <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />;
|
||||
case 'pending':
|
||||
return <Clock className="h-4 w-4 text-duck-dark/40 shrink-0" />;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -43,7 +61,14 @@ const useJobsData = () => {
|
||||
const [jobs, setJobs] = useState<JobSummary[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const load = useCallback(
|
||||
() => client.get<JobSummary[]>('/jobs').then((d) => { setJobs(d); setIsLoading(false); }).catch(() => setIsLoading(false)),
|
||||
() =>
|
||||
client
|
||||
.get<JobSummary[]>('/jobs')
|
||||
.then((d) => {
|
||||
setJobs(d);
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch(() => setIsLoading(false)),
|
||||
[client],
|
||||
);
|
||||
useEffect(() => {
|
||||
@@ -60,7 +85,12 @@ const useJobsData = () => {
|
||||
},
|
||||
[client, load],
|
||||
);
|
||||
const clearHistory = useCallback(() => { client.delete('/jobs/history').then(() => load()).catch(() => {}); }, [client, load]);
|
||||
const clearHistory = useCallback(() => {
|
||||
client
|
||||
.delete('/jobs/history')
|
||||
.then(() => load())
|
||||
.catch(() => {});
|
||||
}, [client, load]);
|
||||
return { jobs, isLoading, act, clearHistory };
|
||||
};
|
||||
|
||||
@@ -71,12 +101,21 @@ const JobRow = ({ job, onAction }: JobRowProps) => {
|
||||
const isRunning = job.status === 'running';
|
||||
const target = basename(job.target);
|
||||
return (
|
||||
<div className={`group w-full border-b border-duck-dark/5 flex items-center transition-colors ${job.id === activeId ? 'bg-duck-teal/10' : 'hover:bg-duck-dark/5'}`}>
|
||||
<button onClick={() => navigate(`/jobs/${job.id}`)} className="flex-1 min-w-0 text-left px-4 py-2.5 flex items-center gap-3 cursor-pointer">
|
||||
<div
|
||||
className={`group w-full border-b border-duck-dark/5 flex items-center transition-colors ${job.id === activeId ? 'bg-duck-teal/10' : 'hover:bg-duck-dark/5'}`}
|
||||
>
|
||||
<button
|
||||
onClick={() => navigate(`/jobs/${job.id}`)}
|
||||
className="flex-1 min-w-0 text-left px-4 py-2.5 flex items-center gap-3 cursor-pointer"
|
||||
>
|
||||
<StatusIcon status={job.status} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="text-sm font-medium text-duck-dark truncate block">{job.taskName}</span>
|
||||
{target && <span className="text-xs text-duck-dark/60 truncate block" title={job.target ?? undefined}>{target}</span>}
|
||||
{target && (
|
||||
<span className="text-xs text-duck-dark/60 truncate block" title={job.target ?? undefined}>
|
||||
{target}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-0.5">
|
||||
<span className="text-xs text-duck-dark/40">{formatDate(job.createdAt)}</span>
|
||||
{job.error && <span className="text-xs text-red-500 truncate max-w-[160px]">{job.error}</span>}
|
||||
@@ -153,7 +192,11 @@ const HistoryJobsPanel = () => {
|
||||
/>
|
||||
</div>
|
||||
{history.length > 0 && (
|
||||
<button onClick={clearHistory} title="Delete all finished jobs" className="shrink-0 text-xs font-medium text-duck-dark/50 hover:text-red-500 cursor-pointer">
|
||||
<button
|
||||
onClick={clearHistory}
|
||||
title="Delete all finished jobs"
|
||||
className="shrink-0 text-xs font-medium text-duck-dark/50 hover:text-red-500 cursor-pointer"
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
)}
|
||||
@@ -162,7 +205,9 @@ const HistoryJobsPanel = () => {
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">Loading…</div>
|
||||
) : history.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">{search ? 'No matches' : 'No finished jobs'}</div>
|
||||
<div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">
|
||||
{search ? 'No matches' : 'No finished jobs'}
|
||||
</div>
|
||||
) : (
|
||||
history.map((job) => <JobRow key={job.id} job={job} onAction={act} />)
|
||||
)}
|
||||
@@ -179,9 +224,15 @@ const JobDetailPanel = () => {
|
||||
const [mode, setMode] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) { setMode(null); return; }
|
||||
if (!id) {
|
||||
setMode(null);
|
||||
return;
|
||||
}
|
||||
setMode(null);
|
||||
client.get<{ mode?: string }>(`/jobs/${id}`).then((j) => setMode(j.mode ?? 'pipeline')).catch(() => setMode('notfound'));
|
||||
client
|
||||
.get<{ mode?: string }>(`/jobs/${id}`)
|
||||
.then((j) => setMode(j.mode ?? 'pipeline'))
|
||||
.catch(() => setMode('notfound'));
|
||||
}, [id]);
|
||||
|
||||
if (!id) {
|
||||
@@ -197,7 +248,9 @@ const JobDetailPanel = () => {
|
||||
if (mode === null) {
|
||||
return (
|
||||
<div className="h-full p-2">
|
||||
<Card className="h-full flex items-center justify-center text-duck-dark/40"><Loader2 className="h-5 w-5 animate-spin" /></Card>
|
||||
<Card className="h-full flex items-center justify-center text-duck-dark/40">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -208,11 +261,22 @@ const JobDetailPanel = () => {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Pipeline detail brings its own full chrome; the script terminal gets a card background here.
|
||||
// Pipeline detail brings its own full chrome; the script terminal + download progress get a card here.
|
||||
if (mode === 'script') {
|
||||
return (
|
||||
<div className="h-full p-2">
|
||||
<Card className="h-full flex flex-col overflow-hidden"><ScriptJobDetail key={id} /></Card>
|
||||
<Card className="h-full flex flex-col overflow-hidden">
|
||||
<ScriptJobDetail key={id} />
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (mode === 'download') {
|
||||
return (
|
||||
<div className="h-full p-2">
|
||||
<Card className="h-full flex flex-col overflow-hidden">
|
||||
<DownloadJobDetail key={id} />
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -73,9 +73,12 @@ export async function executeDownload(params: ExecuteDownloadParams): Promise<vo
|
||||
for (const u of urls) {
|
||||
checkAbort();
|
||||
const info = await reclipInfo(u).catch((): ReclipInfo => ({ error: 'fetch failed' }));
|
||||
if (info && !info.error) valid.push({ url: u, title: info.title ?? '' });
|
||||
else progress.meta.failed++;
|
||||
progress.meta.done++;
|
||||
if (info && !info.error) {
|
||||
valid.push({ url: u, title: info.title ?? '' });
|
||||
progress.meta.done++; // done = kept; failed = skipped (both phases read `(done+failed)/total`)
|
||||
} else {
|
||||
progress.meta.failed++;
|
||||
}
|
||||
emit();
|
||||
}
|
||||
emit(true);
|
||||
|
||||
@@ -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