Duplicates, delete & storage, users page with J-ID avatars

Backend:
- Perceptual hashes (aHash/dHash/pHash/wHash via imagehash, no imgdd)
  stored on items, computed on upload/download and by the new
  compute_visual_hashes command
- Duplicates API: exact duplicates (multi-location items), visual matches
  for one item, union-find similarity groups with pagination
- Delete API with ownership/staff checks, per-item and per-copy deletion,
  watched-folder path validation; storage overview and temp cleanup;
  file list accepts j_ids batches
- Staged uploads are flagged visual_match with their library matches
  (threshold via VISUAL_MATCH_THRESHOLD)
- Staff users API: list with upload counts, set role and avatar by J-ID;
  User.avatar FK with signed avatar URLs
- Download threads close their DB connection and stale tasks are reaped,
  keeping behaviour Gunicorn-friendly

Frontend:
- /duplicates: exact duplicate groups with per-copy delete, visual
  similarity controls, search similar to a J-ID, paginated groups with
  selection, bulk delete and dismiss
- /delete: storage cards, delete by J-ID with preview grid, temp cleanup
- /users: staff directory with role selects and avatar J-ID inputs
- Nav + command palette entries; top-bar avatar; upload cards and the
  metadata modal show library visual matches
This commit is contained in:
2026-09-17 12:49:10 -05:00
parent 75b7ed35eb
commit cd490b0a23
28 changed files with 1966 additions and 22 deletions
@@ -0,0 +1,271 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link } from "react-router-dom";
import { Button, EmptyState, Spinner, inputClass } from "@/components/ui";
import { api, errorMessage } from "@/lib/api";
import { cn } from "@/lib/cn";
import { formatBytes } from "@/lib/format";
import type { MediaItem, Paginated, StorageInfo } from "@/lib/types";
function parseJIds(text: string): string[] {
return text
.split(/[\s,]+/)
.map((value) => value.trim().toUpperCase())
.filter((value) => /^J-\d+$/.test(value));
}
export default function DeletePage() {
const queryClient = useQueryClient();
const [jIdsInput, setJIdsInput] = useState("");
const [loadedIds, setLoadedIds] = useState<string[]>([]);
const [selected, setSelected] = useState<string[]>([]);
const [status, setStatus] = useState<string | null>(null);
const storageQuery = useQuery({
queryKey: ["storage"],
queryFn: () => api<StorageInfo>("/api/storage/"),
});
const filesQuery = useQuery({
queryKey: ["delete-files", loadedIds],
queryFn: () =>
api<Paginated<MediaItem>>(`/api/files/?j_ids=${loadedIds.join(",")}`),
enabled: loadedIds.length > 0,
});
const deleteMutation = useMutation({
mutationFn: (jIds: string[]) =>
api<{ deleted: string[]; errors: { j_id?: string; error: string }[] }>(
"/api/delete/",
{ method: "POST", json: { j_ids: jIds } },
),
onSuccess: (result) => {
setSelected([]);
setLoadedIds([]);
setStatus(
`Deleted ${result.deleted.length} item(s)${
result.errors.length > 0 ? ` · ${result.errors.length} failed` : ""
}.`,
);
void queryClient.invalidateQueries({ queryKey: ["storage"] });
void queryClient.invalidateQueries({ queryKey: ["files"] });
void queryClient.invalidateQueries({ queryKey: ["duplicates-md5"] });
},
onError: (error) => setStatus(errorMessage(error)),
});
const tempMutation = useMutation({
mutationFn: () =>
api<{ removed: number }>("/api/temp/clear/", { method: "POST" }),
onSuccess: (result) => {
setStatus(`Removed ${result.removed} temp file(s).`);
void queryClient.invalidateQueries({ queryKey: ["storage"] });
},
onError: (error) => setStatus(errorMessage(error)),
});
function toggleSelected(jId: string) {
setSelected((current) =>
current.includes(jId)
? current.filter((value) => value !== jId)
: [...current, jId],
);
}
const storage = storageQuery.data;
return (
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6">
<header>
<h1 className="text-lg font-semibold">Delete &amp; storage</h1>
<p className="mt-1 text-sm text-ctp-overlay0">
Inspect disk usage and remove files from the library.
</p>
</header>
{status ? (
<p className="rounded-md border border-ctp-surface1 bg-ctp-base px-3 py-2 text-xs text-ctp-subtext0">
{status}
</p>
) : null}
<section className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{storageQuery.isPending ? (
<Spinner className="h-5 w-5" />
) : storage ? (
<>
<div className="rounded-lg border border-ctp-surface0 bg-ctp-base p-3">
<p className="text-[11px] uppercase tracking-wide text-ctp-overlay0">
Library size
</p>
<p className="mt-1 font-mono text-sm text-ctp-subtext1">
{formatBytes(storage.watched_folder.library_size)}
</p>
<p className="mt-1 truncate font-mono text-[10px] text-ctp-overlay0" title={storage.watched_folder.path}>
{storage.watched_folder.path}
</p>
<p className="font-mono text-[10px] text-ctp-overlay0">
{storage.library_items} items
</p>
</div>
<div className="rounded-lg border border-ctp-surface0 bg-ctp-base p-3">
<p className="text-[11px] uppercase tracking-wide text-ctp-overlay0">
Disk
</p>
<p className="mt-1 font-mono text-sm text-ctp-subtext1">
{formatBytes(storage.watched_folder.used)} /{" "}
{formatBytes(storage.watched_folder.total)}
</p>
<div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-ctp-surface0">
<div
className={cn(
"h-full",
storage.watched_folder.percent_used >= 95
? "bg-ctp-red"
: storage.watched_folder.percent_used >= 80
? "bg-ctp-peach"
: "bg-ctp-blue",
)}
style={{ width: `${storage.watched_folder.percent_used}%` }}
/>
</div>
<p className="mt-1 font-mono text-[10px] text-ctp-overlay0">
{storage.watched_folder.percent_used}% used ·{" "}
{formatBytes(storage.watched_folder.free)} free
</p>
</div>
<div className="rounded-lg border border-ctp-surface0 bg-ctp-base p-3">
<p className="text-[11px] uppercase tracking-wide text-ctp-overlay0">
Media folder
</p>
<p className="mt-1 font-mono text-sm text-ctp-subtext1">
{formatBytes(storage.media.size)}
</p>
<p className="mt-1 truncate font-mono text-[10px] text-ctp-overlay0" title={storage.media.path}>
{storage.media.path}
</p>
</div>
<div className="rounded-lg border border-ctp-surface0 bg-ctp-base p-3">
<p className="text-[11px] uppercase tracking-wide text-ctp-overlay0">
Temp uploads
</p>
<p className="mt-1 font-mono text-sm text-ctp-subtext1">
{formatBytes(storage.temp.size)} · {storage.temp.files} file(s)
</p>
<Button
variant="secondary"
className="mt-2 px-2 py-1 text-xs"
disabled={tempMutation.isPending || storage.temp.files === 0}
onClick={() => tempMutation.mutate()}
>
{tempMutation.isPending ? "Clearing…" : "Clear temp folder"}
</Button>
</div>
</>
) : (
<EmptyState title="Could not load storage info" />
)}
</section>
<section className="flex flex-col gap-3">
<h2 className="text-sm font-semibold text-ctp-subtext1">
Delete files by J-ID
</h2>
<textarea
className={cn(inputClass, "min-h-20 resize-y font-mono")}
placeholder="J-12, J-34 J-56&#10;comma, space or newline separated"
value={jIdsInput}
onChange={(event) => setJIdsInput(event.target.value)}
/>
<div className="flex items-center gap-3">
<Button
variant="secondary"
onClick={() => {
setStatus(null);
setSelected([]);
setLoadedIds(parseJIds(jIdsInput));
}}
>
Load files
</Button>
{selected.length > 0 ? (
<Button
variant="danger"
disabled={deleteMutation.isPending}
onClick={() => deleteMutation.mutate(selected)}
>
{deleteMutation.isPending
? "Deleting…"
: `Delete ${selected.length} selected`}
</Button>
) : null}
</div>
{loadedIds.length === 0 ? (
<p className="text-xs text-ctp-overlay0">
Enter one or more J-IDs to preview them here.
</p>
) : filesQuery.isPending ? (
<Spinner className="h-5 w-5" />
) : (filesQuery.data?.results.length ?? 0) === 0 ? (
<EmptyState title="No matching library items" />
) : (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{filesQuery.data?.results.map((item) => {
const isSelected = selected.includes(item.j_id);
return (
<div
key={item.j_id}
className={cn(
"overflow-hidden rounded-lg border bg-ctp-base",
isSelected ? "border-ctp-mauve" : "border-ctp-surface0",
)}
>
<button
type="button"
onClick={() => toggleSelected(item.j_id)}
className="block w-full text-left"
>
<div className="relative aspect-square overflow-hidden bg-ctp-mantle">
<img
src={`/api/files/${item.j_id}/thumbnail/`}
alt={item.filename}
loading="lazy"
className="h-full w-full object-cover"
/>
<span
className={cn(
"absolute left-2 top-2 flex h-5 w-5 items-center justify-center rounded border text-[11px]",
isSelected
? "border-ctp-mauve bg-ctp-mauve text-ctp-crust"
: "border-ctp-surface1 bg-ctp-crust/70 text-transparent",
)}
>
✓
</span>
</div>
</button>
<div className="px-2 py-1.5">
<Link
to={`/detail/${item.j_id}`}
className="font-mono text-[10px] text-ctp-blue hover:underline"
>
{item.j_id}
</Link>
<p className="truncate font-mono text-[11px] text-ctp-subtext1" title={item.filename}>
{item.filename}
</p>
<p className="font-mono text-[10px] text-ctp-overlay0">
{formatBytes(item.size)}
</p>
</div>
</div>
);
})}
</div>
)}
</section>
</div>
);
}
@@ -0,0 +1,468 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Button, Spinner, inputClass } from "@/components/ui";
import { api, errorMessage } from "@/lib/api";
import { cn } from "@/lib/cn";
import { formatBytes } from "@/lib/format";
import type {
DuplicateEntry,
VisualGroupsResponse,
VisualMatchesResponse,
} from "@/lib/types";
const ALGORITHMS = [
{ value: "ahash", label: "aHash" },
{ value: "dhash", label: "dHash" },
{ value: "phash", label: "pHash" },
{ value: "whash", label: "wHash" },
];
interface DeleteResult {
deleted: string[];
errors: { j_id?: string; location?: number; error: string }[];
}
function MemberCard({
entry,
selected,
onToggle,
}: {
entry: DuplicateEntry;
selected: boolean;
onToggle: () => void;
}) {
return (
<div
className={cn(
"overflow-hidden rounded-lg border bg-ctp-base",
selected ? "border-ctp-mauve" : "border-ctp-surface0",
)}
>
<button type="button" onClick={onToggle} className="block w-full text-left">
<div className="relative aspect-square overflow-hidden bg-ctp-mantle">
<img
src={`/api/files/${entry.j_id}/thumbnail/`}
alt={entry.j_id}
loading="lazy"
className="h-full w-full object-cover"
/>
<span
className={cn(
"absolute left-2 top-2 flex h-5 w-5 items-center justify-center rounded border text-[11px]",
selected
? "border-ctp-mauve bg-ctp-mauve text-ctp-crust"
: "border-ctp-surface1 bg-ctp-crust/70 text-transparent",
)}
>
✓
</span>
{entry.similarity !== undefined ? (
<span className="absolute right-2 top-2 rounded-sm bg-ctp-crust/80 px-1.5 py-0.5 font-mono text-[10px] text-ctp-peach">
{entry.similarity}%
</span>
) : null}
</div>
</button>
<div className="px-2 py-1.5">
<Link
to={`/detail/${entry.j_id}`}
className="font-mono text-[10px] text-ctp-blue hover:underline"
>
{entry.j_id}
</Link>
<p
className="truncate font-mono text-[11px] text-ctp-subtext1"
title={entry.filename}
>
{entry.filename}
</p>
<p className="font-mono text-[10px] text-ctp-overlay0">
{formatBytes(entry.size)}
{entry.location_count > 1 ? ` · ${entry.location_count} copies` : ""}
</p>
</div>
</div>
);
}
export default function DuplicatesPage() {
const queryClient = useQueryClient();
const [threshold, setThreshold] = useState(80);
const [algorithms, setAlgorithms] = useState<string[]>(
ALGORITHMS.map((algorithm) => algorithm.value),
);
const [groupsPage, setGroupsPage] = useState(1);
const [groupsEnabled, setGroupsEnabled] = useState(false);
const [selected, setSelected] = useState<string[]>([]);
const [dismissed, setDismissed] = useState<string[]>([]);
const [similarTarget, setSimilarTarget] = useState("");
const [status, setStatus] = useState<string | null>(null);
const exactQuery = useQuery({
queryKey: ["duplicates-md5"],
queryFn: () =>
api<{ count: number; groups: DuplicateEntry[] }>("/api/duplicates/md5/"),
});
const groupsQuery = useQuery({
queryKey: [
"duplicate-groups",
groupsEnabled,
threshold,
algorithms,
groupsPage,
],
queryFn: () =>
api<VisualGroupsResponse>("/api/duplicates/visual_groups/", {
method: "POST",
json: { threshold, algorithms, page: groupsPage },
}),
enabled: groupsEnabled && algorithms.length > 0,
});
const similarMutation = useMutation({
mutationFn: (jId: string) =>
api<VisualMatchesResponse>("/api/duplicates/visual/", {
method: "POST",
json: { j_id: jId, threshold, algorithms },
}),
onError: (error) => setStatus(errorMessage(error)),
});
const deleteMutation = useMutation({
mutationFn: (payload: { j_ids?: string[]; location_ids?: number[] }) =>
api<DeleteResult>("/api/delete/", { method: "POST", json: payload }),
onSuccess: (result) => {
setSelected([]);
setStatus(
`Deleted ${result.deleted.length} entr${
result.deleted.length === 1 ? "y" : "ies"
}${result.errors.length > 0 ? ` · ${result.errors.length} failed` : ""}.`,
);
void queryClient.invalidateQueries({ queryKey: ["duplicates-md5"] });
void queryClient.invalidateQueries({ queryKey: ["duplicate-groups"] });
void queryClient.invalidateQueries({ queryKey: ["files"] });
},
onError: (error) => setStatus(errorMessage(error)),
});
function toggleSelected(jId: string) {
setSelected((current) =>
current.includes(jId)
? current.filter((value) => value !== jId)
: [...current, jId],
);
}
function toggleAlgorithm(value: string) {
setGroupsPage(1);
setAlgorithms((current) =>
current.includes(value)
? current.filter((algorithm) => algorithm !== value)
: [...current, value],
);
}
const groups = useMemo(
() =>
(groupsQuery.data?.groups ?? []).filter(
(group) =>
!dismissed.includes(
group.members
.map((member) => member.j_id)
.sort()
.join("|"),
),
),
[groupsQuery.data, dismissed],
);
return (
<div className="mx-auto flex w-full max-w-6xl flex-col gap-8">
<header>
<h1 className="text-lg font-semibold">Duplicates</h1>
<p className="mt-1 text-sm text-ctp-overlay0">
Clean up exact copies and visually similar files.
</p>
</header>
{status ? (
<p className="rounded-md border border-ctp-surface1 bg-ctp-base px-3 py-2 text-xs text-ctp-subtext0">
{status}
</p>
) : null}
<section className="flex flex-col gap-3">
<header className="flex items-center justify-between gap-2">
<h2 className="text-sm font-semibold text-ctp-subtext1">
Exact duplicates
</h2>
<span className="font-mono text-[11px] text-ctp-overlay0">
{exactQuery.data?.count ?? 0} item(s)
</span>
</header>
{exactQuery.isPending ? (
<Spinner className="h-5 w-5" />
) : (exactQuery.data?.count ?? 0) === 0 ? (
<p className="rounded-lg border border-dashed border-ctp-surface1 px-3 py-6 text-center text-xs text-ctp-overlay0">
No items exist at multiple paths.
</p>
) : (
<div className="flex flex-col gap-3">
{exactQuery.data?.groups.map((group) => (
<div
key={group.j_id}
className="flex flex-col gap-3 rounded-lg border border-ctp-surface0 bg-ctp-base p-3 lg:flex-row"
>
<div className="w-32 shrink-0">
<div className="aspect-square overflow-hidden rounded-md bg-ctp-mantle">
<img
src={`/api/files/${group.j_id}/thumbnail/`}
alt={group.j_id}
loading="lazy"
className="h-full w-full object-cover"
/>
</div>
<Link
to={`/detail/${group.j_id}`}
className="font-mono text-[10px] text-ctp-blue hover:underline"
>
{group.j_id}
</Link>
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-mono text-xs text-ctp-subtext1">
{group.filename}
</p>
<ul className="mt-2 flex flex-col gap-1.5">
{(group.locations ?? []).map((location) => (
<li
key={location.id}
className="flex items-center justify-between gap-3 rounded-md border border-ctp-surface0 px-2 py-1"
>
<span className="truncate font-mono text-[11px] text-ctp-overlay1" title={location.rel_path}>
{location.rel_path}
</span>
<button
type="button"
onClick={() =>
deleteMutation.mutate({ location_ids: [location.id] })
}
className="shrink-0 rounded-md px-1.5 py-0.5 font-mono text-[10px] text-ctp-red transition hover:bg-ctp-red/15"
>
delete copy
</button>
</li>
))}
</ul>
</div>
<div className="shrink-0">
<Button
variant="danger"
className="px-2 py-1 text-xs"
onClick={() => deleteMutation.mutate({ j_ids: [group.j_id] })}
>
Delete item
</Button>
</div>
</div>
))}
</div>
)}
</section>
<section className="flex flex-col gap-3">
<h2 className="text-sm font-semibold text-ctp-subtext1">
Visual similarity
</h2>
<div className="flex flex-col gap-3 rounded-lg border border-ctp-surface0 bg-ctp-base p-3">
<div className="flex flex-wrap items-center gap-4">
<label className="flex flex-1 items-center gap-3 text-xs text-ctp-subtext0">
Similarity {threshold}%
<input
type="range"
min={50}
max={100}
value={threshold}
onChange={(event) => {
setGroupsPage(1);
setThreshold(Number(event.target.value));
}}
className="flex-1"
/>
</label>
<div className="flex flex-wrap items-center gap-2">
{ALGORITHMS.map((algorithm) => (
<label
key={algorithm.value}
className={cn(
"cursor-pointer rounded-full border px-2.5 py-1 font-mono text-[11px] transition",
algorithms.includes(algorithm.value)
? "border-ctp-mauve/40 bg-ctp-mauve/15 text-ctp-mauve"
: "border-ctp-surface1 text-ctp-subtext0 hover:border-ctp-surface2",
)}
>
<input
type="checkbox"
className="hidden"
checked={algorithms.includes(algorithm.value)}
onChange={() => toggleAlgorithm(algorithm.value)}
/>
{algorithm.label}
</label>
))}
</div>
<Button
onClick={() => {
setGroupsEnabled(true);
void groupsQuery.refetch();
}}
disabled={algorithms.length === 0 || groupsQuery.isFetching}
>
{groupsQuery.isFetching ? "Comparing…" : "Find groups"}
</Button>
</div>
<div className="flex flex-wrap items-end gap-2 border-t border-ctp-surface0 pt-3">
<label className="flex flex-col gap-1 text-xs text-ctp-subtext0">
Find files similar to
<input
className={cn(inputClass, "w-32 font-mono")}
placeholder="J-123"
value={similarTarget}
onChange={(event) => setSimilarTarget(event.target.value)}
/>
</label>
<Button
variant="secondary"
onClick={() => similarMutation.mutate(similarTarget.trim())}
disabled={!similarTarget.trim() || similarMutation.isPending}
>
{similarMutation.isPending ? "Searching…" : "Search"}
</Button>
{similarMutation.isError ? (
<p className="text-xs text-ctp-red">
{errorMessage(similarMutation.error)}
</p>
) : null}
</div>
{similarMutation.data ? (
similarMutation.data.count === 0 ? (
<p className="text-xs text-ctp-overlay0">
No matches at {similarMutation.data.threshold}% similarity.
</p>
) : (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{similarMutation.data.matches.map((entry) => (
<MemberCard
key={entry.j_id}
entry={entry}
selected={selected.includes(entry.j_id)}
onToggle={() => toggleSelected(entry.j_id)}
/>
))}
</div>
)
) : null}
</div>
{groupsEnabled ? (
groupsQuery.isPending ? (
<Spinner className="h-5 w-5" />
) : groups.length === 0 ? (
<p className="rounded-lg border border-dashed border-ctp-surface1 px-3 py-6 text-center text-xs text-ctp-overlay0">
No groups at {threshold}% similarity.
</p>
) : (
<div className="flex flex-col gap-4">
{groups.map((group) => {
const groupKey = group.members
.map((member) => member.j_id)
.sort()
.join("|");
return (
<div
key={groupKey}
className="rounded-lg border border-ctp-surface0 bg-ctp-base p-3"
>
<header className="flex items-center justify-between gap-2">
<span className="font-mono text-[11px] text-ctp-overlay0">
{group.size} similar items
</span>
<button
type="button"
onClick={() => setDismissed((current) => [...current, groupKey])}
className="rounded-md px-1.5 py-0.5 font-mono text-[10px] text-ctp-overlay0 transition hover:bg-ctp-surface0 hover:text-ctp-text"
>
dismiss
</button>
</header>
<div className="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{group.members.map((member) => (
<MemberCard
key={member.j_id}
entry={member}
selected={selected.includes(member.j_id)}
onToggle={() => toggleSelected(member.j_id)}
/>
))}
</div>
</div>
);
})}
<div className="flex items-center justify-between gap-3">
<Button
variant="secondary"
disabled={groupsPage <= 1 || groupsQuery.isFetching}
onClick={() => setGroupsPage((page) => Math.max(1, page - 1))}
>
Previous
</Button>
<span className="font-mono text-xs text-ctp-overlay0">
Page {groupsQuery.data?.page ?? groupsPage} ·{" "}
{groupsQuery.data?.count ?? 0} group(s)
</span>
<Button
variant="secondary"
disabled={!groupsQuery.data?.has_next || groupsQuery.isFetching}
onClick={() => setGroupsPage((page) => page + 1)}
>
Next
</Button>
</div>
</div>
)
) : null}
{selected.length > 0 ? (
<div className="sticky bottom-16 z-20 flex items-center justify-between gap-3 rounded-lg border border-ctp-mauve/40 bg-ctp-surface0 px-3 py-2 shadow-[0_4px_12px_rgba(17,17,27,0.6)]">
<span className="text-xs text-ctp-subtext1">
{selected.length} selected
</span>
<div className="flex items-center gap-2">
<Button
variant="ghost"
className="px-2 py-1 text-xs"
onClick={() => setSelected([])}
>
Clear
</Button>
<Button
variant="danger"
className="px-2 py-1 text-xs"
disabled={deleteMutation.isPending}
onClick={() => deleteMutation.mutate({ j_ids: selected })}
>
{deleteMutation.isPending ? "Deleting…" : "Delete selected"}
</Button>
</div>
</div>
) : null}
</section>
</div>
);
}
+59 -2
View File
@@ -137,9 +137,11 @@ function TempCard({
No preview
</div>
)}
{temp.status === "visual_match" && temp.iqdb_data?.length ? (
{temp.status === "visual_match" &&
(temp.iqdb_data?.length ?? 0) + (temp.visual_matches?.length ?? 0) > 0 ? (
<span className="absolute left-2 top-2 rounded-full bg-ctp-peach/90 px-1.5 py-0.5 font-mono text-[10px] font-medium text-ctp-crust">
{temp.iqdb_data.length} similar
{(temp.iqdb_data?.length ?? 0) + (temp.visual_matches?.length ?? 0)}{" "}
similar
</span>
) : null}
</div>
@@ -282,6 +284,13 @@ function MetadataModal({
});
}
function discardUpload() {
void api(`/api/uploads/${temp.temp_id}/`, { method: "DELETE" }).then(() => {
void queryClient.invalidateQueries({ queryKey: ["uploads"] });
onClose();
});
}
return (
<div
className="fixed inset-0 z-[70] flex items-start justify-center overflow-y-auto bg-ctp-crust/70 px-4 py-10 backdrop-blur-sm"
@@ -364,6 +373,54 @@ function MetadataModal({
{tab === "link" ? (
<div className="flex flex-col gap-3">
{temp.visual_matches && temp.visual_matches.length > 0 ? (
<div>
<p className="text-xs font-medium uppercase tracking-wide text-ctp-overlay1">
Already in your library
</p>
<div className="mt-2 flex flex-col gap-2">
{temp.visual_matches.map((match) => (
<div
key={match.j_id}
className="flex items-center gap-3 rounded-md border border-ctp-surface0 bg-ctp-surface0/40 p-2"
>
<img
src={`/api/files/${match.j_id}/thumbnail/`}
alt={match.j_id}
loading="lazy"
className="h-12 w-12 shrink-0 rounded object-cover"
/>
<span className="min-w-0 flex-1">
<Link
to={`/detail/${match.j_id}`}
className="font-mono text-[11px] text-ctp-blue hover:underline"
>
{match.j_id}
</Link>
<span className="block truncate font-mono text-[11px] text-ctp-subtext0" title={match.filename}>
{match.filename}
</span>
</span>
<span className="shrink-0 font-mono text-[11px] text-ctp-peach">
{match.similarity}%
</span>
</div>
))}
</div>
<p className="mt-2 text-[11px] text-ctp-overlay0">
This upload looks like it is already in the library —
you can discard it below.
</p>
<button
type="button"
onClick={discardUpload}
className="mt-2 rounded-md px-1.5 py-0.5 font-mono text-[10px] text-ctp-red transition hover:bg-ctp-red/15"
>
discard this upload
</button>
</div>
) : null}
{temp.iqdb_data && temp.iqdb_data.length > 0 ? (
<div>
<p className="text-xs font-medium uppercase tracking-wide text-ctp-overlay1">
+180
View File
@@ -0,0 +1,180 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Button, EmptyState, Spinner, inputClass } from "@/components/ui";
import { api, errorMessage } from "@/lib/api";
import { cn } from "@/lib/cn";
import { formatDate } from "@/lib/format";
import type { AdminUser, Paginated } from "@/lib/types";
import { useAuth } from "@/store/auth";
const ROLE_OPTIONS = [
{ value: "user", label: "User" },
{ value: "uploader", label: "Uploader" },
{ value: "staff", label: "Staff" },
];
function UserRow({ profile }: { profile: AdminUser }) {
const queryClient = useQueryClient();
const [avatarJId, setAvatarJId] = useState(profile.avatar_j_id ?? "");
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const mutation = useMutation({
mutationFn: (payload: Record<string, string | null>) =>
api<AdminUser>(`/api/users/${profile.id}/`, {
method: "PATCH",
json: payload,
}),
onSuccess: (updated) => {
setMessage("Saved.");
setError(null);
setAvatarJId(updated.avatar_j_id ?? "");
void queryClient.invalidateQueries({ queryKey: ["users"] });
},
onError: (err) => {
setError(errorMessage(err));
setMessage(null);
},
});
return (
<div className="flex flex-col gap-3 rounded-lg border border-ctp-surface0 bg-ctp-base p-3 lg:flex-row lg:items-center">
<div className="flex min-w-0 flex-1 items-center gap-3">
{profile.avatar_url ? (
<img
src={profile.avatar_url}
alt={profile.username}
className="h-10 w-10 shrink-0 rounded-full border border-ctp-surface1 object-cover"
/>
) : (
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-ctp-surface1 font-mono text-sm font-semibold text-ctp-lavender">
{profile.username.slice(0, 1).toUpperCase()}
</span>
)}
<div className="min-w-0">
<p className="flex flex-wrap items-center gap-2 text-sm text-ctp-subtext1">
<span className="font-medium">{profile.username}</span>
{profile.is_superuser ? (
<span className="rounded-full border border-ctp-red/40 bg-ctp-red/10 px-2 py-0.5 font-mono text-[10px] text-ctp-red">
admin
</span>
) : null}
{profile.is_staff && !profile.is_superuser ? (
<span className="rounded-full border border-ctp-surface1 px-2 py-0.5 font-mono text-[10px] text-ctp-overlay0">
django staff
</span>
) : null}
</p>
<p className="truncate font-mono text-[11px] text-ctp-overlay0">
{profile.email || "no email"} · joined{" "}
{formatDate(profile.date_joined)} · {profile.uploads_count} upload
{profile.uploads_count === 1 ? "" : "s"}
</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<select
className={cn(inputClass, "w-32")}
value={profile.role}
onChange={(event) =>
mutation.mutate({ role: event.target.value })
}
disabled={mutation.isPending}
title="Role"
>
{ROLE_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
<input
className={cn(inputClass, "w-28 font-mono")}
placeholder="J-ID"
value={avatarJId}
onChange={(event) => setAvatarJId(event.target.value)}
title="Avatar library item"
/>
<Button
variant="secondary"
disabled={mutation.isPending}
onClick={() => mutation.mutate({ avatar_j_id: avatarJId.trim() })}
>
Save avatar
</Button>
</div>
{message ? (
<p className="text-xs text-ctp-green lg:w-20">{message}</p>
) : null}
{error ? (
<p className="text-xs text-ctp-red lg:w-40">{error}</p>
) : null}
</div>
);
}
export default function UsersPage() {
const user = useAuth((state) => state.user);
const [search, setSearch] = useState("");
const isStaff = Boolean(
user &&
(user.is_staff || user.is_superuser || user.role === "staff"),
);
const query = useQuery({
queryKey: ["users", search],
queryFn: () =>
api<Paginated<AdminUser>>(
`/api/users/${search ? `?search=${encodeURIComponent(search)}` : ""}`,
),
enabled: isStaff,
});
if (!isStaff) {
return (
<EmptyState
title="Staff only"
description="This page is limited to staff accounts."
/>
);
}
return (
<div className="mx-auto flex w-full max-w-5xl flex-col gap-4">
<header className="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 className="text-lg font-semibold">Users</h1>
<p className="mt-1 text-sm text-ctp-overlay0">
Manage roles and set profile pictures from library J-IDs.
</p>
</div>
<input
className={cn(inputClass, "w-56")}
placeholder="Search username…"
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
</header>
{query.isPending ? (
<div className="flex justify-center py-16">
<Spinner className="h-6 w-6" />
</div>
) : query.isError || !query.data ? (
<EmptyState title="Could not load users" />
) : query.data.results.length === 0 ? (
<EmptyState title="No users found" />
) : (
<div className="flex flex-col gap-3">
{query.data.results.map((profile) => (
<UserRow key={profile.id} profile={profile} />
))}
</div>
)}
</div>
);
}