Files
playlink/web/src/pages/Review.tsx
T
cdnutterandClaude Opus 5.5 e0617047f7 Go back to the hardlink deduplicator (1da0132), keeping backups
Restores the code of 1da0132 ("Add a setting to hide the quarantine from
Plex") and removes everything added after it: the tag editor, album art,
organizing/naming, the step-by-step tune-up and library types.

Kept:
- Database backups (Settings -> Backups): scheduled, manual, download,
  restore, and the optional backup before every action.
- The .env-driven docker-compose.yml for Arcane.

Databases that already ran the later migrations keep working: migrations
6-10 stay in the list (they only add columns) so numbering never goes
backwards, and Undo refuses History entries of removed features instead
of treating them as links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 10:43:29 -07:00

536 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useState } from "react";
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, ArrowRight, ArrowUpCircle, Disc3, Download, ListMusic, ChevronDown, ChevronRight, CopyCheck, EyeOff, Eye, Link2, Search, Crown } from "lucide-react";
import { ApiError, api, type Match, type Page, type Pair, type ProbeInfo } from "../api";
import { Alert, Badge, Button, Card, Empty, Modal, Spinner, cx, formatBytes, formatDuration, inputCls, statusTone } from "../ui";
import { useToast } from "../toast";
import { AlbumView, BulkBar, TriCheckbox, toggleIDs, type Selection } from "./Bulk";
const filters = [
{ id: "review", label: "Needs review" },
{ id: "upgrade", label: "Upgrades" },
{ id: "identical", label: "Identical" },
{ id: "linked", label: "Linked" },
{ id: "unmatched", label: "Slave only" },
{ id: "error", label: "Errors" },
{ id: "ignored", label: "Ignored" },
{ id: "", label: "All" },
];
const kindLabel: Record<Match["kind"], string> = {
path: "same path",
path_case: "path differs in case",
extension: "other format",
fuzzy: "similar title",
elsewhere: "same top folder, other subfolder",
approximate: "approximate match",
none: "no match",
};
function hashParam(name: string) {
const q = window.location.hash.split("?")[1];
return new URLSearchParams(q ?? "").get(name);
}
const PAGE = 50;
export function Review({ pair }: { pair: Pair }) {
const qc = useQueryClient();
const toast = useToast();
const [status, setStatus] = useState(() => hashParam("status") ?? (pair.summary.review > 0 ? "review" : "identical"));
const [q, setQ] = useState("");
const [debounced, setDebounced] = useState("");
const [page, setPage] = useState(0);
const [confirmBulk, setConfirmBulk] = useState(false);
const [view, setView] = useState<"songs" | "albums">(() => {
try {
return localStorage.getItem("playlink.reviewView") === "albums" ? "albums" : "songs";
} catch {
return "songs";
}
});
const [sel, setSel] = useState<Selection>(new Set());
const chooseView = (v: "songs" | "albums") => {
setView(v);
try {
localStorage.setItem("playlink.reviewView", v);
} catch {
/* private mode: the choice just isn't remembered */
}
};
useEffect(() => {
const t = setTimeout(() => setDebounced(q), 250);
return () => clearTimeout(t);
}, [q]);
useEffect(() => setPage(0), [status, debounced]);
// A selection only makes sense for the list it was made in.
useEffect(() => setSel(new Set()), [status, debounced, pair.id]);
const list = useQuery({
queryKey: ["matches", pair.id, status, debounced, page],
queryFn: () =>
api.get<Page<Match>>(`/pairs/${pair.id}/matches?status=${status}&q=${encodeURIComponent(debounced)}&limit=${PAGE}&offset=${page * PAGE}`),
placeholderData: keepPreviousData,
});
const bulk = useMutation({
mutationFn: () => api.post(`/pairs/${pair.id}/link-identical`),
onSuccess: () => {
setConfirmBulk(false);
qc.invalidateQueries({ queryKey: ["pair", pair.id] });
},
onError: (e) => toast("err", e.message),
});
const c = pair.summary.counts;
const count = (id: string) =>
id === "review" ? pair.summary.review : id === "upgrade" ? pair.summary.upgrades : id === "ignored" ? pair.summary.ignored : id === "" ? undefined : c[id] ?? 0;
const identical = c.identical ?? 0;
const running = pair.job?.state === "running";
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
{filters.map((f) => (
<button
key={f.id}
onClick={() => setStatus(f.id)}
className={cx(
"flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs cursor-pointer",
status === f.id ? "border-accent bg-accent/15 text-white" : "border-line text-muted hover:text-white",
)}
>
{f.label}
{count(f.id) !== undefined && <span className="tabular-nums opacity-70">{count(f.id)}</span>}
</button>
))}
<div className="ml-auto flex w-full items-center gap-2 sm:w-auto">
<div className="relative flex-1 sm:w-64">
<Search className="absolute left-2.5 top-2.5 size-4 text-muted" />
<input className={inputCls + " pl-8"} placeholder="Filter by path…" value={q} onChange={(e) => setQ(e.target.value)} />
</div>
<div className="flex rounded-lg border border-line p-0.5" role="tablist" aria-label="Group by">
{(["songs", "albums"] as const).map((v) => (
<button
key={v}
role="tab"
aria-selected={view === v}
onClick={() => chooseView(v)}
className={cx("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs capitalize cursor-pointer", view === v ? "bg-panel-2 text-white" : "text-muted hover:text-white")}
>
{v === "songs" ? <ListMusic className="size-3.5" /> : <Disc3 className="size-3.5" />}
{v}
</button>
))}
</div>
<ExportMenu pairId={pair.id} status={status} query={debounced} viewCount={list.data?.total} filterLabel={filters.find((f) => f.id === status)?.label ?? "All"} />
</div>
</div>
{status === "identical" && identical > 0 && (
<Card className="flex flex-wrap items-center justify-between gap-3 p-4">
<div className="text-sm">
<b>{identical}</b> byte-identical files ({formatBytes(pair.summary.reclaimable_bytes)}) can be replaced with hardlinks.
<div className="text-xs text-muted">Each one is compared byte for byte again right before linking. No quarantine is needed because the data stays in the master.</div>
</div>
<Button variant="primary" onClick={() => setConfirmBulk(true)} disabled={running}>
<CopyCheck className="size-4" /> Link all identical
</Button>
</Card>
)}
{view === "albums" ? (
<AlbumView pair={pair} status={status} query={debounced} sel={sel} setSel={setSel} />
) : (
<>
<Card className="overflow-hidden">
{list.data && list.data.items.length > 0 && (
<label className="flex items-center gap-3 border-b border-line bg-panel-2 px-4 py-2 text-xs text-muted">
<TriCheckbox
label="Select all songs on this page"
checked={list.data.items.every((m) => sel.has(m.id))}
partial={list.data.items.some((m) => sel.has(m.id))}
onChange={(v) => setSel(toggleIDs(sel, list.data!.items.map((m) => m.id), v))}
/>
Select all {list.data.items.length} songs on this page
<span className="text-gray-600">· switch to Albums to select whole albums</span>
</label>
)}
{list.isLoading && (
<div className="p-8">
<Spinner />
</div>
)}
{list.data?.items.length === 0 && (
<Empty icon={<CopyCheck className="size-8" />} title={pair.last_scan_at ? "Nothing here" : "Not scanned yet"}>
{pair.last_scan_at ? "No files match this filter." : "Run a scan to compare the two libraries."}
</Empty>
)}
{list.data?.items.map((m) => (
<MatchRow key={m.id} m={m} selected={sel.has(m.id)} onToggle={(v) => setSel(toggleIDs(sel, [m.id], v))} />
))}
</Card>
{list.data && list.data.total > PAGE && (
<div className="flex items-center justify-between text-sm text-muted">
<span>
{page * PAGE + 1}–{Math.min((page + 1) * PAGE, list.data.total)} of {list.data.total}
</span>
<div className="flex gap-2">
<Button size="sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
Previous
</Button>
<Button size="sm" disabled={(page + 1) * PAGE >= list.data.total} onClick={() => setPage(page + 1)}>
Next
</Button>
</div>
</div>
)}
</>
)}
<BulkBar pair={pair} status={status} sel={sel} clear={() => setSel(new Set())} />
<Modal open={confirmBulk} onClose={() => setConfirmBulk(false)} title="Link all identical files?">
<p className="text-sm text-gray-300">
Each of the <b>{identical}</b> slave files will be compared byte for byte with its master counterpart once more, then atomically
replaced with a hardlink to the master file. Files whose paths differ only by letter case are included.
</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={() => setConfirmBulk(false)}>
Cancel
</Button>
<Button variant="primary" onClick={() => bulk.mutate()} loading={bulk.isPending}>
Link {identical} files
</Button>
</div>
</Modal>
</div>
);
}
function ExportMenu({ pairId, status, query, viewCount, filterLabel }: { pairId: number; status: string; query: string; viewCount?: number; filterLabel: string }) {
const [open, setOpen] = useState(false);
useEffect(() => {
if (!open) return;
const close = () => setOpen(false);
window.addEventListener("click", close);
return () => window.removeEventListener("click", close);
}, [open]);
const href = (s: string, q: string) => `/api/pairs/${pairId}/export.csv?status=${encodeURIComponent(s)}&q=${encodeURIComponent(q)}`;
const item = "flex w-full flex-col items-start rounded-md px-3 py-2 text-left hover:bg-panel-2";
return (
<div className="relative" onClick={(e) => e.stopPropagation()}>
<Button onClick={() => setOpen(!open)} title="Export scan results as CSV">
<Download className="size-4" /> <span className="hidden md:inline">Export CSV</span>
</Button>
{open && (
<div className="absolute right-0 z-30 mt-1 w-64 rounded-lg border border-line bg-panel p-1 shadow-xl">
<a className={item} href={href(status, query)} download onClick={() => setOpen(false)}>
<span className="text-sm">This view</span>
<span className="text-xs text-muted">
{filterLabel}
{query && <> · “{query}”</>}
{viewCount !== undefined && <> · {viewCount} rows</>}
</span>
</a>
<a className={item} href={href("", "")} download onClick={() => setOpen(false)}>
<span className="text-sm">Entire scan</span>
<span className="text-xs text-muted">Every scanned slave file, including linked and slave-only</span>
</a>
</div>
)}
</div>
);
}
function PathLine({ m }: { m: Match }) {
const same = m.rel_master === m.rel_slave || !m.rel_master;
return (
<div className="min-w-0 text-sm">
<div className="truncate mono text-[13px]" title={m.rel_slave}>
{m.rel_slave}
</div>
{!same && (
<div className="flex min-w-0 items-center gap-1 text-xs text-muted" title={m.rel_master}>
<ArrowRight className="size-3 shrink-0" /> <span className="truncate mono">{m.rel_master}</span>
</div>
)}
</div>
);
}
function qualityLabel(p?: ProbeInfo) {
if (!p || p.error) return "?";
if (p.lossless) return `${p.codec.toUpperCase()} ${p.bit_depth || "?"}/${(p.sample_rate / 1000).toFixed(1)}`;
return `${p.codec.toUpperCase()} ${Math.round(p.bitrate / 1000)}k`;
}
export function MatchRow({ m, selected, onToggle }: { m: Match; selected?: boolean; onToggle?: (v: boolean) => void }) {
const reviewable = m.status === "different" || m.status === "similar";
const [open, setOpen] = useState(false);
const qc = useQueryClient();
const toast = useToast();
const refresh = () => {
qc.invalidateQueries({ queryKey: ["matches"] });
qc.invalidateQueries({ queryKey: ["pair", m.pair_id] });
};
const link = useMutation({
mutationFn: () => api.post<{ dry_run: boolean }>(`/matches/${m.id}/link`, {}),
onSuccess: (op) => {
toast("ok", op.dry_run ? "Planned (dry run): nothing changed" : "Linked");
refresh();
},
onError: (e) => toast("err", e.message),
});
const ignore = useMutation({
mutationFn: () => api.post(`/matches/${m.id}/ignore`, { ignored: !m.ignored }),
onSuccess: refresh,
});
const better = m.verdict?.better;
return (
<div className="border-b border-line last:border-0">
<div className={cx("flex items-center gap-3 px-4 py-2.5", selected && "bg-accent/5")}>
{onToggle && (
<input
type="checkbox"
aria-label={`Select ${m.rel_slave}`}
className="size-4 shrink-0 accent-violet-500 cursor-pointer"
checked={!!selected}
onChange={(e) => onToggle(e.target.checked)}
/>
)}
<button
className={cx("text-muted", reviewable ? "cursor-pointer hover:text-white" : "invisible")}
onClick={() => setOpen(!open)}
aria-label="Expand"
>
{open ? <ChevronDown className="size-4" /> : <ChevronRight className="size-4" />}
</button>
<div className="flex w-28 shrink-0 flex-col items-start gap-1">
<Badge tone={statusTone[m.status]}>{m.status}</Badge>
{m.kind !== "path" && m.kind !== "none" && <span className="text-[10px] text-muted">{kindLabel[m.kind]}</span>}
</div>
<div className="min-w-0 flex-1" onClick={() => reviewable && setOpen(!open)}>
<PathLine m={m} />
{m.reason && <div className="truncate text-[11px] text-muted" title={m.reason}>{m.reason}</div>}
{m.note && <div className="text-xs text-red-300">{m.note}</div>}
</div>
{reviewable && (
<div className="hidden items-center gap-1.5 text-xs md:flex">
<span className="text-muted">{qualityLabel(m.master_probe)}</span>
<span className="text-gray-600">vs</span>
<span className="text-muted">{qualityLabel(m.slave_probe)}</span>
{better === "slave" && (
<Badge tone="amber">
<AlertTriangle className="size-3" /> master lower
</Badge>
)}
{better === "master" && (
<Badge tone="green">
<ArrowUpCircle className="size-3" /> upgrade
</Badge>
)}
{better === "equal" && <Badge>equal</Badge>}
</div>
)}
<div className="hidden w-20 text-right text-xs tabular-nums text-muted sm:block">{formatBytes(m.slave_size)}</div>
<div className="flex shrink-0 gap-1.5">
{m.status === "identical" && !m.ignored && (
<Button size="sm" variant="primary" onClick={() => link.mutate()} loading={link.isPending}>
<Link2 className="size-3.5" /> Link
</Button>
)}
{reviewable && !m.ignored && (
<Button size="sm" onClick={() => setOpen(!open)}>
Review
</Button>
)}
{(reviewable || m.status === "identical") && (
<Button size="sm" variant="ghost" onClick={() => ignore.mutate()} title={m.ignored ? "Un-ignore" : "Ignore"}>
{m.ignored ? <Eye className="size-3.5" /> : <EyeOff className="size-3.5" />}
</Button>
)}
</div>
</div>
{open && reviewable && <ComparePanel m={m} onDone={refresh} />}
</div>
);
}
const rows: [string, (p: ProbeInfo, size: number) => string][] = [
["Codec", (p) => `${p.codec}${p.lossless ? " (lossless)" : ""}`],
["Bitrate", (p) => (p.bitrate ? `${Math.round(p.bitrate / 1000)} kbps` : "–")],
["Sample rate", (p) => (p.sample_rate ? `${(p.sample_rate / 1000).toFixed(1)} kHz` : "–")],
["Bit depth", (p) => (p.bit_depth ? `${p.bit_depth}-bit` : "–")],
["Channels", (p) => String(p.channels || "–")],
["Duration", (p) => formatDuration(p.duration)],
["Size", (_, s) => formatBytes(s)],
["Title tag", (p) => p.title || "–"],
["Album tag", (p) => p.album || "–"],
];
function ComparePanel({ m, onDone }: { m: Match; onDone: () => void }) {
const toast = useToast();
const [confirm, setConfirm] = useState<null | "downgrade" | "promote">(null);
const mp = m.master_probe;
const sp = m.slave_probe;
const v = m.verdict;
const renamed = m.rel_master.split("/").pop() !== m.rel_slave.split("/").pop();
const dir = (p: string) => p.split("/").slice(0, -1).join("/");
const base = (p: string) => p.split("/").pop() ?? p;
// Cross-folder matches mirror the master's folders unless the user keeps the slave's folder.
const [keepFolder, setKeepFolder] = useState(false);
const movesFolder = dir(m.link_target) !== dir(m.rel_slave);
const target = keepFolder && movesFolder ? [dir(m.rel_slave), base(m.rel_master)].filter(Boolean).join("/") : m.link_target;
const link = useMutation({
mutationFn: (allow: boolean) => api.post<{ dry_run: boolean }>(`/matches/${m.id}/link`, { allow_downgrade: allow, keep_folder: keepFolder }),
onSuccess: (op) => {
setConfirm(null);
toast("ok", op.dry_run ? "Planned (dry run): nothing changed" : "Linked. The original slave file is in quarantine.");
onDone();
},
onError: (e) => {
if (e instanceof ApiError && e.status === 409 && e.message.includes("lower quality")) setConfirm("downgrade");
else toast("err", e.message);
},
});
const promote = useMutation({
mutationFn: () => api.post<{ dry_run: boolean }>(`/matches/${m.id}/promote`, { confirm: true }),
onSuccess: (op) => {
setConfirm(null);
toast("ok", op.dry_run ? "Planned (dry run): nothing changed" : "Slave file promoted to master. The old master file is in quarantine.");
onDone();
},
onError: (e) => toast("err", e.message),
});
return (
<div className="border-t border-line bg-panel-2/50 px-4 py-4 md:pl-14">
{(!mp || !sp) && <Alert tone="amber">No codec details available (ffprobe missing or failed). Compare the files yourself before linking.</Alert>}
{mp && sp && (
<div className="overflow-x-auto">
<table className="w-full max-w-2xl text-sm">
<thead>
<tr className="text-left text-xs text-muted">
<th className="py-1 pr-4 font-normal"></th>
<th className="py-1 pr-4 font-medium">
<Badge tone="violet">master</Badge> {better(v?.better === "master")}
</th>
<th className="py-1 font-medium">
<Badge>slave</Badge> {better(v?.better === "slave")}
</th>
</tr>
</thead>
<tbody>
{rows.map(([label, f]) => {
const a = mp.error ? "–" : f(mp, m.master_size);
const b = sp.error ? "–" : f(sp, m.slave_size);
return (
<tr key={label} className="border-t border-line/60">
<td className="py-1 pr-4 text-xs text-muted">{label}</td>
<td className={cx("py-1 pr-4", a !== b && "text-white")}>{a}</td>
<td className={cx("py-1", a !== b && "text-white")}>{b}</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
<div className="mt-3 space-y-2">
{/* Scans before this change stored an upgrade note; the green alert below covers it. */}
{v?.notes?.filter((n) => !n.startsWith("master is lossless")).map((n) => (
<Alert key={n} tone="amber" icon={<AlertTriangle className="mt-0.5 size-4 shrink-0" />}>
{n}
</Alert>
))}
{m.kind === "approximate" && (
<Alert tone="blue">
Approximate match: {m.reason}. Check that the titles and durations really are the same song before linking.
</Alert>
)}
{v?.better === "master" && (
<Alert tone="green" icon={<ArrowUpCircle className="mt-0.5 size-4 shrink-0" />}>
Recommended: the master copy is better ({qualityLabel(mp)} vs {qualityLabel(sp)}). Linking upgrades the slave to it and frees the
slave's copy.
</Alert>
)}
{v?.better === "slave" && (
<Alert tone="amber" icon={<Crown className="mt-0.5 size-4 shrink-0" />}>
The master copy is lower quality. The master is normally kept because it belongs to a complete album. You can still link to it (the
slave's better copy goes to quarantine), or override and make the slave's copy the master file.
</Alert>
)}
{target !== m.rel_slave && (
<Alert tone="blue">
<div>
Linking places the file at <code className="mono break-all text-white">{target}</code> in the slave library
{movesFolder && !keepFolder ? ", matching the master's folders. The old folder is removed if it ends up empty." : "."} Playlists
that point at the old path will need updating.
</div>
{movesFolder && (
<label className="mt-2 flex items-center gap-2 text-xs cursor-pointer">
<input type="checkbox" className="accent-violet-500" checked={keepFolder} onChange={(e) => setKeepFolder(e.target.checked)} />
Keep it in the slave's current folder instead: <code className="mono">{dir(m.rel_slave) || "library root"}</code>
</label>
)}
</Alert>
)}
</div>
<div className="mt-4 flex flex-wrap gap-2">
<Button variant="primary" onClick={() => (v?.better === "slave" ? setConfirm("downgrade") : link.mutate(false))} loading={link.isPending && !confirm}>
{v?.better === "master" ? <ArrowUpCircle className="size-4" /> : <Link2 className="size-4" />}
{v?.better === "master" ? "Upgrade to master copy" : "Link to master copy"}
</Button>
<Button variant={v?.better === "slave" ? "warn" : "secondary"} onClick={() => setConfirm("promote")}>
<Crown className="size-4" /> Use slave copy as master
</Button>
</div>
<p className="mt-2 text-xs text-muted">Whatever gets replaced is kept in quarantine and can be restored from History.</p>
<Modal open={confirm === "downgrade"} onClose={() => setConfirm(null)} title="Link to a lower-quality master file?">
<p className="text-sm text-gray-300">
The slave has the better copy ({qualityLabel(sp)} vs {qualityLabel(mp)}). Linking replaces it with the master's{" "}
{qualityLabel(mp)} file. The slave's original goes to quarantine and can be restored until it is purged.
</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={() => setConfirm(null)}>
Cancel
</Button>
<Button variant="warn" onClick={() => link.mutate(true)} loading={link.isPending}>
Link anyway
</Button>
</div>
</Modal>
<Modal open={confirm === "promote"} onClose={() => setConfirm(null)} title="Replace the master file with the slave copy?">
<p className="text-sm text-gray-300">
This <b>changes the master library</b>. The master file <code className="mono break-all">{m.rel_master}</code> goes to quarantine, and the
slave's file (<code className="mono">{qualityLabel(sp)}</code>) is hardlinked into the master album in its place
{renamed && (
<>
{" "}as <code className="mono">{m.rel_slave.split("/").pop()}</code>
</>
)}
. Both libraries then share one file.
</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={() => setConfirm(null)}>
Cancel
</Button>
<Button variant="warn" onClick={() => promote.mutate()} loading={promote.isPending}>
Promote slave copy
</Button>
</div>
</Modal>
</div>
);
}
function better(yes: boolean) {
return yes ? <span className="text-[11px] text-emerald-300">★ better</span> : null;
}