feat(batch-upload): bulk footage plate upload matched by filename
Deploy / deploy (push) Successful in 6m39s

Adds a third section to the Batch Upload page that attaches plate movies to
shots derived from the filename: DH2_VFX_058_120_REF.mov becomes the plate
"REF" on shot DH2_VFX_058_120. Shot matching reuses findMatchingShotCode, so
it behaves like the rest of the page (case-insensitive, longest code wins,
underscore-boundary only) and the filename remainder becomes the label.

Bytes go straight to Hetzner via the existing presign endpoint since plates
are multi-GB, with XHR for per-file progress. Files whose shot already has a
plate of the same name are skipped so re-running a batch does not stack
duplicates.

Also resets the thumbnail and plate previews when the project changes — they
are resolved against a specific project, but only the version-upload flow was
being cleared.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
twotalesanimation
2026-09-12 12:15:29 +02:00
parent 469d782b4f
commit 2dee1bf6fc
5 changed files with 761 additions and 0 deletions
@@ -21,11 +21,14 @@ import {
ArrowRight,
RotateCcw,
ImageIcon,
Film,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useToast } from "@/components/ui/use-toast";
import { PLATE_EXTS, plateContentType } from "@/lib/batch-upload-parser";
import type { PreviewItem, PreviewItemStatus } from "@/app/api/batch-upload/preview/route";
import type { ThumbnailPreviewItem } from "@/app/api/batch-upload/thumbnails/route";
import type { PlatePreviewItem } from "@/app/api/batch-upload/plates/route";
interface Project {
id: string;
@@ -40,6 +43,12 @@ interface UploadState {
error?: string;
}
/** Footage plates are large, so they also carry per-file upload progress. */
interface PlateUploadState extends UploadState {
/** 0–1, only meaningful while status is "uploading" */
progress?: number;
}
interface BatchUploadClientProps {
projects: Project[];
}
@@ -76,6 +85,25 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
setThumbUploadComplete(false);
};
// ── Footage plate upload state ─────────────────────────────────────────────
const plateInputRef = useRef<HTMLInputElement>(null);
const [plateFiles, setPlateFiles] = useState<File[]>([]);
const [plateIsDragging, setPlateIsDragging] = useState(false);
const [platePreview, setPlatePreview] = useState<PlatePreviewItem[] | null>(null);
const [plateLoadingPreview, setPlateLoadingPreview] = useState(false);
const [plateUploadStates, setPlateUploadStates] = useState<Record<string, PlateUploadState>>({});
const [plateIsUploading, setPlateIsUploading] = useState(false);
const [plateUploadComplete, setPlateUploadComplete] = useState(false);
const acceptPlate = (f: File) => PLATE_EXTS.has(f.name.split(".").pop()?.toLowerCase() ?? "");
const resetPlates = () => {
setPlateFiles([]);
setPlatePreview(null);
setPlateUploadStates({});
setPlateUploadComplete(false);
};
const reset = () => {
setFiles([]);
setPreview(null);
@@ -324,6 +352,136 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
setThumbUploadComplete(true);
};
// ── Footage plate handlers ─────────────────────────────────────────────────
const handlePlateDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setPlateIsDragging(false);
const dropped = Array.from(e.dataTransfer.files).filter(acceptPlate);
if (dropped.length > 0) {
setPlateFiles(dropped);
setPlatePreview(null);
setPlateUploadStates({});
setPlateUploadComplete(false);
} else {
toast({
title: "No supported files",
description: "Only .mov, .mp4, .mxf, .avi, .mkv and .webm files are accepted.",
});
}
}, [toast]); // eslint-disable-line react-hooks/exhaustive-deps
const handlePlateInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const selected = Array.from(e.target.files ?? []).filter(acceptPlate);
if (selected.length > 0) {
setPlateFiles(selected);
setPlatePreview(null);
setPlateUploadStates({});
setPlateUploadComplete(false);
}
e.target.value = "";
};
const fetchPlatePreview = async () => {
if (!projectId || plateFiles.length === 0) return;
setPlateLoadingPreview(true);
try {
const res = await fetch("/api/batch-upload/plates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ projectId, fileNames: plateFiles.map((f) => f.name) }),
});
if (!res.ok) throw new Error("Preview failed");
const data = await res.json();
setPlatePreview(data.items);
const states: Record<string, PlateUploadState> = {};
for (const item of data.items as PlatePreviewItem[]) states[item.fileName] = { status: "pending" };
setPlateUploadStates(states);
} catch {
toast({ title: "Preview failed", variant: "destructive" });
} finally {
setPlateLoadingPreview(false);
}
};
const startPlateUpload = async () => {
if (!platePreview || !projectId) return;
setPlateIsUploading(true);
const matched = platePreview.filter((i) => i.status === "match");
for (const item of matched) {
const file = plateFiles.find((f) => f.name === item.fileName);
if (!file) continue;
setPlateUploadStates((prev) => ({
...prev,
[item.fileName]: { status: "uploading", progress: 0 },
}));
try {
// Step 1 — presigned PUT URL. Plates are multi-GB, so the bytes go
// straight to Hetzner and never touch this server or the proxy.
const presignRes = await fetch("/api/upload/presign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
fileName: file.name,
contentType: plateContentType(file.name),
folder: "videos",
}),
});
if (!presignRes.ok) {
const d = await presignRes.json().catch(() => ({ error: "Failed to get upload URL" }));
throw new Error((d as { error?: string }).error ?? "Failed to get upload URL");
}
const { presignedUrl, key } = (await presignRes.json()) as {
presignedUrl: string;
key: string;
};
// Step 2 — PUT directly to storage, tracking progress via XHR.
await putWithProgress(presignedUrl, file, (fraction) => {
setPlateUploadStates((prev) => ({
...prev,
[item.fileName]: { status: "uploading", progress: fraction },
}));
});
// Step 3 — commit the plate record against the matched shot.
const commitRes = await fetch("/api/batch-upload/plates/upload", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
projectId,
shotId: item.shotId,
key,
fileName: file.name,
fileSize: file.size,
label: item.label,
}),
});
if (!commitRes.ok) {
const d = await commitRes.json().catch(() => ({ error: "Failed to save plate" }));
throw new Error((d as { error?: string }).error ?? "Failed to save plate");
}
setPlateUploadStates((prev) => ({ ...prev, [item.fileName]: { status: "success" } }));
} catch (err) {
setPlateUploadStates((prev) => ({
...prev,
[item.fileName]: {
status: "error",
error: err instanceof Error ? err.message : "Upload failed",
},
}));
}
}
setPlateIsUploading(false);
setPlateUploadComplete(true);
};
// ── Derived counts ─────────────────────────────────────────────────────────
const uploadable = preview?.filter(
@@ -359,7 +517,11 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
value={projectId}
onValueChange={(v) => {
setProjectId(v);
// Every preview is resolved against a specific project, so none
// of them survive a project switch.
reset();
resetThumbs();
resetPlates();
}}
>
<SelectTrigger className="w-80 bg-zinc-800 border-zinc-700">
@@ -735,12 +897,260 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
</Card>
);
})()}
{/* ── Footage plate bulk upload ───────────────────────────────── */}
<div className="border-t border-zinc-800 pt-2">
<h2 className="text-base font-semibold text-white">Bulk Footage Plate Upload</h2>
<p className="text-zinc-400 text-sm mt-1">
Drop plate movies here to add them to a shot's Footage tab. The shot is taken
from the start of the filename and the remainder becomes the plate label —{" "}
<span className="text-zinc-300 font-mono text-xs">DH2_VFX_058_120_REF.mov</span>{" "}
becomes the plate <span className="text-zinc-300">REF</span> on shot{" "}
<span className="text-zinc-300 font-mono text-xs">DH2_VFX_058_120</span>.
</p>
</div>
{/* Plate drop zone */}
{!plateUploadComplete && (
<Card>
<CardContent className="pt-5">
<div
onDragOver={(e) => { e.preventDefault(); setPlateIsDragging(true); }}
onDragLeave={() => setPlateIsDragging(false)}
onDrop={handlePlateDrop}
onClick={() => plateInputRef.current?.click()}
className={cn(
"border-2 border-dashed rounded-xl p-10 text-center cursor-pointer transition-colors select-none",
plateIsDragging
? "border-emerald-400 bg-emerald-400/5"
: "border-zinc-700 hover:border-zinc-500 hover:bg-zinc-800/30"
)}
>
<Film className="h-9 w-9 text-zinc-500 mx-auto mb-3" />
<p className="text-zinc-300 font-medium">Drop footage plates here</p>
<p className="text-zinc-500 text-sm mt-1">
MOV, MP4, MXF, AVI, MKV, WebM · or click to browse
</p>
{plateFiles.length > 0 && (
<p className="text-emerald-400 text-sm mt-3 font-medium">
{plateFiles.length} file{plateFiles.length !== 1 ? "s" : ""} selected
</p>
)}
<input
ref={plateInputRef}
type="file"
multiple
accept=".mov,.mp4,.m4v,.mxf,.avi,.mkv,.webm,video/*"
className="hidden"
onChange={handlePlateInput}
/>
</div>
{plateFiles.length > 0 && !platePreview && (
<div className="mt-4 flex items-center gap-3">
<Button onClick={fetchPlatePreview} disabled={plateLoadingPreview}>
{plateLoadingPreview ? (
<><Loader2 className="h-4 w-4 mr-2 animate-spin" />Loading preview…</>
) : (
<>Preview<ChevronRight className="h-4 w-4 ml-2" /></>
)}
</Button>
<Button variant="ghost" onClick={resetPlates} disabled={plateLoadingPreview}>Clear</Button>
</div>
)}
</CardContent>
</Card>
)}
{/* Plate preview table */}
{platePreview && !plateUploadComplete && (() => {
const matched = platePreview.filter((i) => i.status === "match");
const skippedPlates = platePreview.filter((i) => i.status !== "match");
const dupes = platePreview.filter((i) => i.status === "duplicate");
const plateSuccess = Object.values(plateUploadStates).filter((s) => s.status === "success").length;
const plateErrors = Object.values(plateUploadStates).filter((s) => s.status === "error").length;
const plateDone = plateSuccess + plateErrors;
const plateProgress = matched.length > 0 ? (plateDone / matched.length) * 100 : 0;
return (
<Card>
<CardHeader className="pb-0">
<CardTitle className="text-base font-medium text-zinc-200">
Footage plate preview —{" "}
<span className="text-zinc-400 font-normal">
{matched.length} matched · {skippedPlates.length} skipped
</span>
</CardTitle>
</CardHeader>
<CardContent className="p-0 mt-4">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800">
<th className="text-left text-xs text-zinc-500 font-normal px-6 py-2.5">File</th>
<th className="text-left text-xs text-zinc-500 font-normal px-6 py-2.5">Matched Shot</th>
<th className="text-left text-xs text-zinc-500 font-normal px-6 py-2.5">Plate label</th>
<th className="text-left text-xs text-zinc-500 font-normal px-4 py-2.5 w-32">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-800/60">
{platePreview.map((item) => {
const state = plateUploadStates[item.fileName];
return (
<tr key={item.fileName} className="hover:bg-zinc-800/30 transition-colors">
<td className="px-6 py-3">
<div className="flex items-center gap-2">
<FileVideo className="h-4 w-4 text-zinc-500 shrink-0" />
<span className="text-zinc-200 font-mono text-xs truncate max-w-[240px]">{item.fileName}</span>
</div>
</td>
<td className="px-6 py-3">
{item.shotCode ? (
<span className="font-mono text-xs text-zinc-300">
{item.shotCode}
{item.existingPlateCount > 0 && (
<span className="text-zinc-600 ml-1.5 font-sans">
({item.existingPlateCount} plate{item.existingPlateCount !== 1 ? "s" : ""})
</span>
)}
</span>
) : (
<span className="text-xs text-zinc-600 italic">
{item.status === "unsupported" ? "unsupported file" : "no match"}
</span>
)}
</td>
<td className="px-6 py-3">
{item.status === "match" ? (
<span className="text-zinc-300 text-xs">{item.label}</span>
) : (
<span className="text-zinc-700 text-xs">—</span>
)}
</td>
<td className="px-4 py-3">
{item.status === "duplicate" ? (
<span className="flex items-center gap-1 text-xs text-zinc-500" title="This shot already has a plate with this filename">
<XCircle className="h-3.5 w-3.5" />already added
</span>
) : item.status !== "match" ? (
<span className="flex items-center gap-1 text-xs text-zinc-500"><XCircle className="h-3.5 w-3.5" />skip</span>
) : !state || state.status === "pending" ? (
<span className="flex items-center gap-1 text-xs text-emerald-400"><ArrowRight className="h-3.5 w-3.5" />add plate</span>
) : state.status === "uploading" ? (
<span className="flex items-center gap-1 text-xs text-amber-400">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{Math.round((state.progress ?? 0) * 100)}%
</span>
) : state.status === "success" ? (
<span className="flex items-center gap-1 text-xs text-emerald-400"><CheckCircle2 className="h-3.5 w-3.5" />done</span>
) : (
<span className="flex items-center gap-1 text-xs text-red-400" title={state.error}><XCircle className="h-3.5 w-3.5" />error</span>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{plateIsUploading && (
<div className="px-6 py-3 border-t border-zinc-800">
<div className="flex justify-between text-xs text-zinc-400 mb-1.5">
<span>Uploading {Math.min(plateDone + 1, matched.length)} of {matched.length}…</span>
<span>{Math.round(plateProgress)}%</span>
</div>
<Progress value={plateProgress} className="h-1.5" />
</div>
)}
<div className="px-6 py-4 border-t border-zinc-800 flex items-center justify-between gap-4">
<p className="text-zinc-500 text-xs">
{matched.length} plate{matched.length !== 1 ? "s" : ""} will be added
{skippedPlates.length > 0 && (
<span className="text-zinc-600">
{" "}· {skippedPlates.length} skipped
{dupes.length > 0 && ` (${dupes.length} already uploaded)`}
</span>
)}
</p>
<div className="flex gap-3 shrink-0">
<Button variant="ghost" size="sm" onClick={resetPlates} disabled={plateIsUploading}>Change files</Button>
<Button size="sm" onClick={startPlateUpload} disabled={plateIsUploading || matched.length === 0}>
{plateIsUploading ? (
<><Loader2 className="h-4 w-4 mr-2 animate-spin" />Uploading…</>
) : (
`Upload ${matched.length} plate${matched.length !== 1 ? "s" : ""}`
)}
</Button>
</div>
</div>
</CardContent>
</Card>
);
})()}
{/* Plate done summary */}
{plateUploadComplete && (() => {
const plateSuccess = Object.values(plateUploadStates).filter((s) => s.status === "success").length;
const plateErrors = Object.values(plateUploadStates).filter((s) => s.status === "error").length;
return (
<Card>
<CardContent className="pt-8 pb-8 flex flex-col items-center gap-4 text-center">
<CheckCircle2 className="h-12 w-12 text-green-500" />
<div>
<p className="text-white font-semibold text-lg">Footage plates uploaded</p>
<p className="text-zinc-400 text-sm mt-1">
{plateSuccess} added{plateErrors > 0 && <span className="text-red-400"> · {plateErrors} failed</span>}
</p>
</div>
<Button variant="outline" onClick={resetPlates} className="mt-2">
<RotateCcw className="h-4 w-4 mr-2" />Upload more plates
</Button>
</CardContent>
</Card>
);
})()}
</>
)}
</div>
);
}
// ── Helpers ────────────────────────────────────────────────────────────────────
/**
* PUT a file to a presigned storage URL, reporting upload progress.
*
* `fetch` gives no upload progress, and footage plates are big enough that a
* silent multi-minute wait per file is unusable — hence XHR.
*/
function putWithProgress(
url: string,
file: File,
onProgress: (fraction: number) => void
): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Content-Type", plateContentType(file.name));
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) onProgress(e.loaded / e.total);
});
xhr.addEventListener("load", () => {
if (xhr.status >= 200 && xhr.status < 300) resolve();
else if (xhr.status === 403)
reject(new Error("Storage upload failed — check Hetzner CORS / bucket policy"));
else reject(new Error(`Storage upload failed (HTTP ${xhr.status})`));
});
xhr.addEventListener("error", () => reject(new Error("Network error")));
xhr.addEventListener("abort", () => reject(new Error("Upload aborted")));
xhr.send(file);
});
}
// ── Sub-components ─────────────────────────────────────────────────────────────
function PreviewRow({