Initial commit: playlink music library hardlink deduplicator

Go backend (chi, SQLite) with an embedded React/TypeScript UI that finds
songs present in both a host and a slave music library and replaces the
slave copy with a hardlink to the host copy.

- Path-first matching with format/title/album-folder fallbacks
- Auto-linking of byte-identical files, re-verified with cmp before linking
- Manual review with ffprobe quality comparison, downgrade guard and
  promote-to-host override
- Build mode to populate an empty slave library from the host
- Dry run by default, atomic stage+rename replacement, quarantine with
  retention, undo, path confinement and authenticated UI
- Dockerfile and compose file for Unraid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cdnutterandClaude Opus 5.5 committed 2026-09-22 15:38:25 -07:00
commit ac47e61b08
42 files changed
+8892

No files matched your search

+398
View File
@@ -0,0 +1,398 @@
import { useEffect, useState } from "react";
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, ArrowRight, 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";
const filters = [
{ id: "review", label: "Needs review" },
{ 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: "other album folder",
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);
useEffect(() => {
const t = setTimeout(() => setDebounced(q), 250);
return () => clearTimeout(t);
}, [q]);
useEffect(() => setPage(0), [status, debounced]);
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 === "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="relative ml-auto w-full 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>
{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 host.</div>
</div>
<Button variant="primary" onClick={() => setConfirmBulk(true)} disabled={running}>
<CopyCheck className="size-4" /> Link all identical
</Button>
</Card>
)}
<Card className="overflow-hidden">
{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} />)}
</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>
)}
<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 host counterpart once more, then atomically
replaced with a hardlink to the host 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 PathLine({ m }: { m: Match }) {
const same = m.rel_host === m.rel_slave || !m.rel_host;
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_host}>
<ArrowRight className="size-3 shrink-0" /> <span className="truncate mono">{m.rel_host}</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`;
}
function MatchRow({ m }: { m: Match }) {
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="flex items-center gap-3 px-4 py-2.5">
<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.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.host_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" /> host lower
</Badge>
)}
{better === "host" && <Badge tone="green">host better</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 hp = m.host_probe;
const sp = m.slave_probe;
const v = m.verdict;
const renamed = m.rel_host.split("/").pop() !== m.rel_slave.split("/").pop();
const link = useMutation({
mutationFn: (allow: boolean) => api.post<{ dry_run: boolean }>(`/matches/${m.id}/link`, { allow_downgrade: allow }),
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 host. The old host 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">
{(!hp || !sp) && <Alert tone="amber">No codec details available (ffprobe missing or failed). Compare the files yourself before linking.</Alert>}
{hp && 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">host</Badge> {better(v?.better === "host")}
</th>
<th className="py-1 font-medium">
<Badge>slave</Badge> {better(v?.better === "slave")}
</th>
</tr>
</thead>
<tbody>
{rows.map(([label, f]) => {
const a = hp.error ? "–" : f(hp, m.host_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">
{v?.notes?.map((n) => (
<Alert key={n} tone="amber" icon={<AlertTriangle className="mt-0.5 size-4 shrink-0" />}>
{n}
</Alert>
))}
{v?.better === "slave" && (
<Alert tone="amber" icon={<Crown className="mt-0.5 size-4 shrink-0" />}>
The host copy is lower quality. The host 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 host file.
</Alert>
)}
{renamed && (
<Alert tone="blue">
File names differ. Linking puts <code className="mono">{m.rel_host.split("/").pop()}</code> into the slave folder in place of{" "}
<code className="mono">{m.rel_slave.split("/").pop()}</code>, so playlists that point at the old name will need updating.
</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}>
<Link2 className="size-4" /> Link to host copy
</Button>
<Button variant={v?.better === "slave" ? "warn" : "secondary"} onClick={() => setConfirm("promote")}>
<Crown className="size-4" /> Use slave copy as host
</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 host file?">
<p className="text-sm text-gray-300">
The slave has the better copy ({qualityLabel(sp)} vs {qualityLabel(hp)}). Linking replaces it with the host's{" "}
{qualityLabel(hp)} 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 host file with the slave copy?">
<p className="text-sm text-gray-300">
This <b>changes the host library</b>. The host file <code className="mono break-all">{m.rel_host}</code> goes to quarantine, and the
slave's file (<code className="mono">{qualityLabel(sp)}</code>) is hardlinked into the host 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;
}