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 = { 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(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>(`/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 (
{filters.map((f) => ( ))}
setQ(e.target.value)} />
{(["songs", "albums"] as const).map((v) => ( ))}
f.id === status)?.label ?? "All"} />
{status === "identical" && identical > 0 && (
{identical} byte-identical files ({formatBytes(pair.summary.reclaimable_bytes)}) can be replaced with hardlinks.
Each one is compared byte for byte again right before linking. No quarantine is needed because the data stays in the master.
)} {view === "albums" ? ( ) : ( <> {list.data && list.data.items.length > 0 && ( )} {list.isLoading && (
)} {list.data?.items.length === 0 && ( } 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."} )} {list.data?.items.map((m) => ( setSel(toggleIDs(sel, [m.id], v))} /> ))}
{list.data && list.data.total > PAGE && (
{page * PAGE + 1}–{Math.min((page + 1) * PAGE, list.data.total)} of {list.data.total}
)} )} setSel(new Set())} /> setConfirmBulk(false)} title="Link all identical files?">

Each of the {identical} 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.

); } 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 (
e.stopPropagation()}> {open && (
setOpen(false)}> This view {filterLabel} {query && <> · “{query}”} {viewCount !== undefined && <> · {viewCount} rows} setOpen(false)}> Entire scan Every scanned slave file, including linked and slave-only
)}
); } function PathLine({ m }: { m: Match }) { const same = m.rel_master === m.rel_slave || !m.rel_master; return (
{m.rel_slave}
{!same && (
{m.rel_master}
)}
); } 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 (
{onToggle && ( onToggle(e.target.checked)} /> )}
{m.status} {m.kind !== "path" && m.kind !== "none" && {kindLabel[m.kind]}}
reviewable && setOpen(!open)}> {m.reason &&
{m.reason}
} {m.note &&
{m.note}
}
{reviewable && (
{qualityLabel(m.master_probe)} vs {qualityLabel(m.slave_probe)} {better === "slave" && ( master lower )} {better === "master" && ( upgrade )} {better === "equal" && equal}
)}
{formatBytes(m.slave_size)}
{m.status === "identical" && !m.ignored && ( )} {reviewable && !m.ignored && ( )} {(reviewable || m.status === "identical") && ( )}
{open && reviewable && }
); } 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); 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 (
{(!mp || !sp) && No codec details available (ffprobe missing or failed). Compare the files yourself before linking.} {mp && sp && (
{rows.map(([label, f]) => { const a = mp.error ? "–" : f(mp, m.master_size); const b = sp.error ? "–" : f(sp, m.slave_size); return ( ); })}
master {better(v?.better === "master")} slave {better(v?.better === "slave")}
{label} {a} {b}
)}
{/* 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) => ( }> {n} ))} {m.kind === "approximate" && ( Approximate match: {m.reason}. Check that the titles and durations really are the same song before linking. )} {v?.better === "master" && ( }> Recommended: the master copy is better ({qualityLabel(mp)} vs {qualityLabel(sp)}). Linking upgrades the slave to it and frees the slave's copy. )} {v?.better === "slave" && ( }> 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. )} {target !== m.rel_slave && (
Linking places the file at {target} 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.
{movesFolder && ( )}
)}

Whatever gets replaced is kept in quarantine and can be restored from History.

setConfirm(null)} title="Link to a lower-quality master file?">

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.

setConfirm(null)} title="Replace the master file with the slave copy?">

This changes the master library. The master file {m.rel_master} goes to quarantine, and the slave's file ({qualityLabel(sp)}) is hardlinked into the master album in its place {renamed && ( <> {" "}as {m.rel_slave.split("/").pop()} )} . Both libraries then share one file.

); } function better(yes: boolean) { return yes ? ★ better : null; }