Build OverSnitch dashboard

Full implementation on top of the Next.js scaffold:

- Leaderboard with per-user request count, storage, avg GB/req, and
  optional Tautulli watch stats (plays, watch hours), each with dense
  per-metric rank (#N/total)
- SWR cache on /api/stats (5-min stale, force-refresh via button);
  client-side localStorage seed so the UI is instant on return visits
- Alerting system: content-centric alerts (unfulfilled downloads,
  partial TV downloads, stale pending requests) and user-behavior
  alerts (ghost requester, low watch rate, declined streak)
- Partial TV detection: flags ended series with <90% of episodes on disk
- Alert persistence in data/alerts.json with open/closed state,
  auto-resolve when condition clears, manual close with per-category
  cooldown, and per-alert notes
- Alert detail page rendered as a server component for instant load
- Dark UI with Tailwind v4, severity-colored left borders, summary
  cards with icons, sortable leaderboard table

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-12 11:13:57 -04:00
parent ef061ea910
commit f871f86284
25 changed files with 2084 additions and 86 deletions

3
.gitignore vendored
View File

@@ -39,3 +39,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
# alert persistence
/data/alerts.json

4
package-lock.json generated
View File

@@ -1,11 +1,11 @@
{
"name": "oversnitch-tmp",
"name": "oversnitch",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "oversnitch-tmp",
"name": "oversnitch",
"version": "0.1.0",
"dependencies": {
"next": "16.2.3",

View File

@@ -1,5 +1,5 @@
{
"name": "oversnitch-tmp",
"name": "oversnitch",
"version": "0.1.0",
"private": true,
"scripts": {

View File

@@ -0,0 +1,170 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { Alert, AlertSeverity } from "@/lib/types";
const severityAccent: Record<AlertSeverity, string> = {
danger: "border-l-red-500",
warning: "border-l-yellow-500",
info: "border-l-blue-500",
};
function timeAgo(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const mins = Math.floor(diff / 60_000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
return `${Math.floor(hrs / 24)}d ago`;
}
function shortDate(iso: string): string {
return new Date(iso).toLocaleDateString(undefined, {
month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
});
}
export default function AlertDetail({ initialAlert }: { initialAlert: Alert }) {
const [alert, setAlert] = useState<Alert>(initialAlert);
const [actionLoading, setActionLoading] = useState(false);
const [commentText, setCommentText] = useState("");
const [commentLoading, setCommentLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function toggleStatus() {
setActionLoading(true);
setError(null);
try {
const newStatus = alert.status === "open" ? "closed" : "open";
const res = await fetch(`/api/alerts/${alert.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status: newStatus }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
setAlert(await res.json());
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setActionLoading(false);
}
}
async function submitComment(e: React.FormEvent) {
e.preventDefault();
if (!commentText.trim()) return;
setCommentLoading(true);
setError(null);
try {
const res = await fetch(`/api/alerts/${alert.id}/comments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: commentText.trim() }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const comment = await res.json();
setAlert((prev) => ({ ...prev, comments: [...prev.comments, comment] }));
setCommentText("");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setCommentLoading(false);
}
}
const isOpen = alert.status === "open";
const isResolved = alert.closeReason === "resolved";
const statusTime = isOpen ? alert.firstSeen : (alert.closedAt ?? alert.firstSeen);
return (
<main className="mx-auto max-w-2xl px-4 py-8 space-y-5">
<Link
href="/?tab=alerts"
className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-300 transition-colors"
>
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
</svg>
All Alerts
</Link>
{error && (
<div className="rounded-lg border border-red-800 bg-red-950/30 px-4 py-3 text-red-300 text-sm">
{error}
</div>
)}
{/* Alert card */}
<div className={`rounded-xl bg-slate-800/40 border border-slate-700/60 border-l-4 px-6 py-5 space-y-3 ${severityAccent[alert.severity]}`}>
{/* Status row */}
<div className="flex items-center justify-between gap-3">
<span className={`inline-flex items-center gap-1.5 text-xs font-semibold ${
isOpen ? "text-green-400" : isResolved ? "text-teal-400" : "text-slate-500"
}`}>
{isOpen && <span className="h-1.5 w-1.5 rounded-full bg-green-400 shrink-0" />}
{isOpen ? "Open" : isResolved ? "Auto-resolved" : "Closed"}
<span className="text-slate-700 font-normal">·</span>
<span className="text-slate-600 font-normal">{timeAgo(statusTime)}</span>
</span>
<button
onClick={toggleStatus}
disabled={actionLoading}
className={`rounded-lg px-4 py-1.5 text-xs font-semibold transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${
isOpen
? "bg-slate-700 hover:bg-slate-600 text-white"
: "bg-green-900/50 hover:bg-green-800/50 text-green-300 border border-green-800"
}`}
>
{actionLoading ? "…" : isOpen ? "Close" : "Reopen"}
</button>
</div>
{/* Title + description */}
<div className="space-y-1.5">
<h1 className="text-lg font-bold text-white leading-snug">{alert.title}</h1>
<p className="text-sm text-slate-400 leading-relaxed">{alert.description}</p>
</div>
</div>
{/* Notes */}
<section className="space-y-3 pt-1">
<h2 className="text-xs font-semibold uppercase tracking-widest text-slate-600">Notes</h2>
{alert.comments.length === 0 && (
<p className="text-sm text-slate-700">No notes yet.</p>
)}
{alert.comments.map((c) => (
<div key={c.id} className="space-y-1">
<p className="text-xs text-slate-600">{shortDate(c.createdAt)}</p>
<p className="text-sm text-slate-300 whitespace-pre-wrap leading-relaxed">{c.body}</p>
</div>
))}
<form onSubmit={submitComment} className="flex flex-col gap-2 pt-1">
<textarea
value={commentText}
onChange={(e) => setCommentText(e.target.value)}
placeholder="Add a note…"
rows={3}
className="w-full rounded-lg bg-slate-800/40 border border-slate-700/60 focus:border-slate-500 text-sm text-white placeholder-slate-700 px-4 py-3 focus:outline-none resize-none transition-colors"
/>
<div className="flex justify-end">
<button
type="submit"
disabled={commentLoading || !commentText.trim()}
className="rounded-lg bg-slate-700 hover:bg-slate-600 disabled:opacity-40 disabled:cursor-not-allowed px-4 py-2 text-sm font-medium text-white transition-colors"
>
{commentLoading ? "Saving…" : "Save"}
</button>
</div>
</form>
</section>
</main>
);
}

View File

@@ -0,0 +1,14 @@
import { getAlertById } from "@/lib/db";
import { notFound } from "next/navigation";
import AlertDetail from "./AlertDetail";
export default async function AlertPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const alert = getAlertById(Number(id));
if (!alert) notFound();
return <AlertDetail initialAlert={alert} />;
}

View File

@@ -0,0 +1,26 @@
import { addComment } from "@/lib/db";
export async function POST(
req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
let body: { body: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
if (!body.body?.trim()) {
return Response.json({ error: "Comment body is required" }, { status: 400 });
}
const comment = addComment(Number(id), body.body.trim());
if (!comment) {
return Response.json({ error: "Alert not found" }, { status: 404 });
}
return Response.json(comment, { status: 201 });
}

View File

@@ -0,0 +1,42 @@
import { getAlertById, closeAlert, reopenAlert } from "@/lib/db";
export async function GET(
_req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const alert = getAlertById(Number(id));
if (!alert) {
return Response.json({ error: "Alert not found" }, { status: 404 });
}
return Response.json(alert);
}
export async function PATCH(
req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const numId = Number(id);
let body: { status: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
if (body.status === "closed") {
const updated = closeAlert(numId);
if (!updated) return Response.json({ error: "Alert not found" }, { status: 404 });
return Response.json(updated);
}
if (body.status === "open") {
const updated = reopenAlert(numId);
if (!updated) return Response.json({ error: "Alert not found" }, { status: 404 });
return Response.json(updated);
}
return Response.json({ error: "status must be 'open' or 'closed'" }, { status: 400 });
}

View File

@@ -0,0 +1,11 @@
import { getAllAlerts } from "@/lib/db";
export async function GET() {
try {
const alerts = getAllAlerts();
return Response.json(alerts);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return Response.json({ error: message }, { status: 500 });
}
}

View File

@@ -0,0 +1,65 @@
import { buildRadarrMap } from "@/lib/radarr";
import { buildSonarrMap } from "@/lib/sonarr";
import { fetchAllUsers, fetchUserRequests } from "@/lib/overseerr";
import { buildTautulliMap } from "@/lib/tautulli";
import { computeStats } from "@/lib/aggregate";
import { DashboardStats, OverseerrRequest } from "@/lib/types";
const BATCH_SIZE = 5;
// ── Server-side SWR cache ────────────────────────────────────────────────────
// Persists in the Node.js process between requests.
// Background-refreshes after STALE_MS so reads always return instantly.
const STALE_MS = 5 * 60 * 1000; // start background refresh after 5 min
let cache: { stats: DashboardStats; at: number } | null = null;
let refreshing = false;
async function buildStats(): Promise<DashboardStats> {
const [radarrMap, sonarrMap, users, tautulliMap] = await Promise.all([
buildRadarrMap(),
buildSonarrMap(),
fetchAllUsers(),
buildTautulliMap(),
]);
const allRequests = new Map<number, OverseerrRequest[]>();
for (let i = 0; i < users.length; i += BATCH_SIZE) {
const chunk = users.slice(i, i + BATCH_SIZE);
const results = await Promise.all(
chunk.map((u) => fetchUserRequests(u.id))
);
chunk.forEach((u, idx) => allRequests.set(u.id, results[idx]));
}
return computeStats(users, allRequests, radarrMap, sonarrMap, tautulliMap);
}
export async function GET(req: Request) {
const force = new URL(req.url).searchParams.has("force");
try {
// Force (Refresh button) or cold start: wait for fresh data
if (force || !cache) {
const stats = await buildStats();
cache = { stats, at: Date.now() };
return Response.json(cache.stats);
}
// Stale: kick off background refresh, return cache immediately
const age = Date.now() - cache.at;
if (age > STALE_MS && !refreshing) {
refreshing = true;
buildStats()
.then((stats) => { cache = { stats, at: Date.now() }; })
.catch(() => {})
.finally(() => { refreshing = false; });
}
return Response.json(cache.stats);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return Response.json({ error: message }, { status: 500 });
}
}

View File

@@ -1,26 +1,7 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
background: #020617; /* slate-950 */
color: #f8fafc;
font-family: var(--font-geist-sans), Arial, Helvetica, sans-serif;
}

View File

@@ -13,8 +13,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "OverSnitch",
description: "Overseerr user request analytics",
};
export default function RootLayout({
@@ -27,7 +27,7 @@ export default function RootLayout({
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
<body className="min-h-full bg-slate-950 text-white">{children}</body>
</html>
);
}

View File

@@ -1,65 +1,188 @@
import Image from "next/image";
"use client";
import { useEffect, useState, useCallback, useRef, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { DashboardStats } from "@/lib/types";
import SummaryCards from "@/components/SummaryCards";
import LeaderboardTable from "@/components/LeaderboardTable";
import AlertsPanel from "@/components/AlertsPanel";
import RefreshButton from "@/components/RefreshButton";
type Tab = "leaderboard" | "alerts";
const LS_KEY = "oversnitch_stats";
function timeAgo(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const mins = Math.floor(diff / 60_000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
return new Date(iso).toLocaleDateString();
}
function DashboardContent() {
const searchParams = useSearchParams();
const router = useRouter();
const tab = (searchParams.get("tab") ?? "leaderboard") as Tab;
const [data, setData] = useState<DashboardStats | null>(null);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const didInit = useRef(false);
const load = useCallback(async (force = false) => {
setData((prev) => {
if (prev) setRefreshing(true);
else setLoading(true);
return prev;
});
setError(null);
try {
const res = await fetch(force ? "/api/stats?force=1" : "/api/stats");
const json = await res.json();
if (!res.ok) throw new Error(json.error ?? `HTTP ${res.status}`);
const stats = json as DashboardStats;
setData(stats);
try { localStorage.setItem(LS_KEY, JSON.stringify(stats)); } catch {}
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
if (didInit.current) return;
didInit.current = true;
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) setData(JSON.parse(raw) as DashboardStats);
} catch {}
load();
}, [load]);
function setTab(t: Tab) {
const params = new URLSearchParams(searchParams.toString());
params.set("tab", t);
router.push(`?${params.toString()}`, { scroll: false });
}
const hasTautulli = data?.summary.totalWatchHours !== null;
const openAlertCount = data?.summary.openAlertCount ?? 0;
const generatedAt = data?.generatedAt ?? null;
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
<main className="mx-auto max-w-6xl px-4 py-8 space-y-6">
{/* Header */}
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-3xl font-bold tracking-tight">
Over<span className="text-yellow-400">Snitch</span>
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
<p className="text-slate-400 text-sm mt-1.5">Request &amp; usage analytics</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
<div className="flex flex-col items-end gap-1.5 shrink-0">
<RefreshButton onRefresh={() => load(true)} loading={refreshing || loading} />
{generatedAt && (
<span className="text-xs text-slate-600">
{refreshing
? <span className="text-yellow-600/80">Refreshing</span>
: <>Updated {timeAgo(generatedAt)}</>
}
</span>
)}
</div>
</div>
{/* First-ever load spinner */}
{loading && !data && (
<div className="flex flex-col items-center justify-center py-24 gap-4">
<svg
className="animate-spin h-8 w-8 text-yellow-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
</svg>
<div className="text-center space-y-1">
<p className="text-slate-300 text-sm font-medium">Fetching data</p>
<p className="text-slate-600 text-xs">This only takes a moment on first load.</p>
</div>
</div>
)}
{/* Error */}
{error && (
<div className="rounded-xl border border-red-800 bg-red-950/40 px-5 py-4 text-sm">
<span className="font-semibold text-red-400">Error: </span>
<span className="text-red-300">{error}</span>
</div>
)}
{data && (
<>
<SummaryCards
totalUsers={data.summary.totalUsers}
totalRequests={data.summary.totalRequests}
totalStorageGB={data.summary.totalStorageGB}
totalWatchHours={data.summary.totalWatchHours}
openAlertCount={data.summary.openAlertCount}
onAlertsClick={() => setTab("alerts")}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
{/* Tab bar */}
<div className="border-b border-slate-700/60">
<div className="flex gap-1 -mb-px">
{(["leaderboard", "alerts"] as const).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
tab === t
? "border-yellow-400 text-white"
: "border-transparent text-slate-500 hover:text-slate-300"
}`}
>
Documentation
</a>
{t === "alerts" ? (
<span className="flex items-center gap-2">
Alerts
{openAlertCount > 0 && (
<span className="rounded-full bg-yellow-500 text-black text-xs font-bold px-1.5 py-0.5 leading-none">
{openAlertCount}
</span>
)}
</span>
) : (
"Leaderboard"
)}
</button>
))}
</div>
</div>
{tab === "leaderboard" && (
<LeaderboardTable users={data.users} hasTautulli={hasTautulli} />
)}
{tab === "alerts" && <AlertsPanel />}
</>
)}
</main>
</div>
);
}
export default function Page() {
return (
<Suspense>
<DashboardContent />
</Suspense>
);
}

View File

@@ -0,0 +1,178 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Alert, AlertSeverity } from "@/lib/types";
const severityIcon: Record<AlertSeverity, string> = {
danger:
"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z",
warning:
"M12 9v3.75m9.303 3.376c.866 1.5-.217 3.374-1.948 3.374H2.645c-1.73 0-2.813-1.874-1.948-3.374l7.658-13.25c.866-1.5 3.032-1.5 3.898 0zM12 15.75h.007v.008H12v-.008z",
info: "m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z",
};
const severityColor: Record<AlertSeverity, string> = {
danger: "text-red-400",
warning: "text-yellow-400",
info: "text-blue-400",
};
function timeAgo(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const mins = Math.floor(diff / 60_000);
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
return `${days}d ago`;
}
export default function AlertsPanel() {
const [alerts, setAlerts] = useState<Alert[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<"open" | "all">("open");
useEffect(() => {
fetch("/api/alerts")
.then((r) => r.json())
.then(setAlerts)
.finally(() => setLoading(false));
}, []);
const filtered =
filter === "open" ? alerts.filter((a) => a.status === "open") : alerts;
const openCount = alerts.filter((a) => a.status === "open").length;
if (loading) {
return (
<div className="text-slate-600 text-sm py-12 text-center">
Loading alerts
</div>
);
}
return (
<div className="space-y-4">
{/* Toolbar */}
<div className="flex items-center gap-3 flex-wrap">
<div className="flex rounded-lg overflow-hidden border border-slate-700 text-xs font-medium">
{(["open", "all"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 transition-colors ${
filter === f
? "bg-slate-700 text-white"
: "bg-transparent text-slate-500 hover:text-slate-300"
}`}
>
{f === "open" ? `Open (${openCount})` : `All (${alerts.length})`}
</button>
))}
</div>
<span className="text-xs text-slate-600">
Click an alert to view details, add notes, or close it.
</span>
</div>
{filtered.length === 0 && (
<div className="rounded-xl border border-slate-700/60 bg-slate-800/30 p-12 text-center">
<p className="text-slate-500 text-sm">
{filter === "open"
? "No open alerts — everything looks healthy."
: "No alerts recorded yet."}
</p>
</div>
)}
{/* Alert rows */}
<div className="space-y-2">
{filtered.map((alert) => (
<Link
key={alert.id}
href={`/alerts/${alert.id}`}
className={`flex items-start gap-3 rounded-xl border p-4 transition-colors ${
alert.status === "closed"
? "border-slate-700/40 bg-slate-800/20 opacity-50 hover:opacity-70"
: "border-slate-700/60 bg-slate-800/60 hover:bg-slate-800"
}`}
>
{/* Severity icon */}
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className={`h-5 w-5 mt-0.5 shrink-0 ${severityColor[alert.severity]}`}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d={severityIcon[alert.severity]}
/>
</svg>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold text-white text-sm leading-snug">
{alert.title}
</span>
{alert.status === "closed" && (
<span
className={`text-xs rounded-full px-2 py-0.5 font-medium ${
alert.closeReason === "resolved"
? "bg-teal-950/60 text-teal-500 border border-teal-800/60"
: "bg-slate-700/60 text-slate-500 border border-slate-600/60"
}`}
>
{alert.closeReason === "resolved" ? "Auto-resolved" : "Closed"}
</span>
)}
{alert.comments.length > 0 && (
<span className="inline-flex items-center gap-1 text-xs text-slate-600">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="h-3.5 w-3.5"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"
/>
</svg>
{alert.comments.length}
</span>
)}
</div>
<p className="text-sm text-slate-500 mt-0.5 line-clamp-2 leading-relaxed">
{alert.description}
</p>
</div>
{/* Time + chevron */}
<div className="flex items-center gap-1 shrink-0 mt-0.5">
<span className="text-xs text-slate-700">{timeAgo(alert.status === "open" ? alert.firstSeen : (alert.closedAt ?? alert.firstSeen))}</span>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
className="h-3.5 w-3.5 text-slate-700"
>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</div>
</Link>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,189 @@
"use client";
import { useState } from "react";
import { UserStat } from "@/lib/types";
type SortKey = "totalBytes" | "requestCount" | "avgGB" | "plays" | "watchHours";
interface LeaderboardTableProps {
users: UserStat[];
hasTautulli: boolean;
}
function formatGB(gb: number): string {
return gb >= 1000 ? `${(gb / 1000).toFixed(2)} TB` : `${gb.toFixed(1)} GB`;
}
function formatHours(h: number): string {
if (h >= 1000) return `${(h / 1000).toFixed(1)}k h`;
return `${h.toFixed(0)}h`;
}
function Rank({ rank, total }: { rank: number | null; total: number }) {
if (rank === null) return <span className="text-slate-700"></span>;
return (
<span className="text-xs font-mono text-slate-500">
#{rank}<span className="text-slate-700">/{total}</span>
</span>
);
}
function SortChevrons({ active, asc }: { active: boolean; asc: boolean }) {
return (
<span className="ml-1 inline-flex flex-col gap-px opacity-0 group-hover:opacity-100 transition-opacity">
{active ? (
<svg
className="h-3 w-3 text-yellow-400"
viewBox="0 0 12 12"
fill="currentColor"
>
{asc
? <path d="M6 2 L10 8 L2 8 Z" />
: <path d="M6 10 L10 4 L2 4 Z" />
}
</svg>
) : (
<svg className="h-3 w-3 text-slate-600" viewBox="0 0 12 12" fill="currentColor">
<path d="M6 1 L9 5 L3 5 Z M6 11 L9 7 L3 7 Z" />
</svg>
)}
</span>
);
}
export default function LeaderboardTable({
users,
hasTautulli,
}: LeaderboardTableProps) {
const [sortKey, setSortKey] = useState<SortKey>("totalBytes");
const [sortAsc, setSortAsc] = useState(false);
const sorted = [...users].sort((a, b) => {
const av = (a[sortKey] ?? -1) as number;
const bv = (b[sortKey] ?? -1) as number;
return sortAsc ? av - bv : bv - av;
});
function handleSort(key: SortKey) {
if (key === sortKey) setSortAsc((p) => !p);
else { setSortKey(key); setSortAsc(false); }
}
function Th({
label,
col,
right,
}: {
label: string;
col?: SortKey;
right?: boolean;
}) {
const active = col === sortKey;
return (
<th
onClick={col ? () => handleSort(col) : undefined}
className={[
"group py-3 px-4 text-xs font-semibold uppercase tracking-wider whitespace-nowrap select-none",
right ? "text-right" : "text-left",
col ? "cursor-pointer" : "",
active ? "text-yellow-400" : "text-slate-500 hover:text-slate-300",
].join(" ")}
>
{label}
{col && <SortChevrons active={active} asc={sortAsc} />}
</th>
);
}
const total = users.length;
return (
<div className="overflow-x-auto rounded-xl border border-slate-700/60">
<table className="w-full text-sm">
<thead className="bg-slate-800/80 border-b border-slate-700/60">
<tr>
<Th label="#" />
<Th label="User" />
<Th label="Requests" col="requestCount" right />
<Th label="Storage" col="totalBytes" right />
<Th label="Avg / Req" col="avgGB" right />
{hasTautulli && <Th label="Plays" col="plays" right />}
{hasTautulli && <Th label="Watch Time" col="watchHours" right />}
</tr>
</thead>
<tbody className="divide-y divide-slate-700/30">
{sorted.map((user, idx) => (
<tr
key={user.userId}
className="bg-slate-900 hover:bg-slate-800/50 transition-colors"
>
{/* Row index */}
<td className="py-3 px-4 text-slate-700 font-mono text-xs w-10 tabular-nums">
{idx + 1}
</td>
{/* User */}
<td className="py-3 px-4">
<div className="font-medium text-white leading-snug">{user.displayName}</div>
<div className="text-xs text-slate-600 mt-0.5">{user.email}</div>
</td>
{/* Requests */}
<td className="py-3 px-4 text-right">
<div className="text-slate-300 font-mono tabular-nums">
{user.requestCount.toLocaleString()}
</div>
<div className="mt-0.5 flex justify-end">
<Rank rank={user.requestRank} total={total} />
</div>
</td>
{/* Storage */}
<td className="py-3 px-4 text-right">
<div className="text-white font-semibold font-mono tabular-nums">
{formatGB(user.totalGB)}
</div>
<div className="mt-0.5 flex justify-end">
<Rank rank={user.storageRank} total={total} />
</div>
</td>
{/* Avg / Request */}
<td className="py-3 px-4 text-right text-slate-500 font-mono text-xs tabular-nums">
{user.requestCount > 0 ? formatGB(user.avgGB) : "—"}
</td>
{/* Plays */}
{hasTautulli && (
<td className="py-3 px-4 text-right">
<div className="text-slate-300 font-mono tabular-nums">
{user.plays !== null ? user.plays.toLocaleString() : "—"}
</div>
<div className="mt-0.5 flex justify-end">
<Rank rank={user.playsRank} total={total} />
</div>
</td>
)}
{/* Watch Time */}
{hasTautulli && (
<td className="py-3 px-4 text-right">
<div className="text-slate-500 font-mono text-xs tabular-nums">
{user.watchHours !== null && user.watchHours > 0
? formatHours(user.watchHours)
: user.watchHours === 0
? "0h"
: "—"}
</div>
<div className="mt-0.5 flex justify-end">
<Rank rank={user.watchRank} total={total} />
</div>
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
);
}

View File

@@ -0,0 +1,23 @@
interface PercentileBadgeProps {
label: string;
}
const colorMap: Record<string, string> = {
"Top 1%": "bg-yellow-400 text-black",
"Top 5%": "bg-yellow-500 text-black",
"Top 10%": "bg-green-500 text-white",
"Top 25%": "bg-green-700 text-white",
"Top 50%": "bg-blue-600 text-white",
"Bottom 50%": "bg-slate-600 text-slate-300",
};
export default function PercentileBadge({ label }: PercentileBadgeProps) {
const colorClass = colorMap[label] ?? "bg-slate-600 text-slate-300";
return (
<span
className={`inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold ${colorClass}`}
>
{label}
</span>
);
}

View File

@@ -0,0 +1,32 @@
"use client";
interface RefreshButtonProps {
onRefresh: () => void;
loading: boolean;
}
export default function RefreshButton({ onRefresh, loading }: RefreshButtonProps) {
return (
<button
onClick={onRefresh}
disabled={loading}
className="flex items-center gap-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 hover:border-slate-600 disabled:opacity-40 disabled:cursor-not-allowed px-3.5 py-1.5 text-sm font-medium text-slate-300 hover:text-white transition-colors"
>
<svg
className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
/>
</svg>
{loading ? "Loading…" : "Refresh"}
</button>
);
}

View File

@@ -0,0 +1,123 @@
interface SummaryCardsProps {
totalUsers: number;
totalRequests: number;
totalStorageGB: number;
totalWatchHours: number | null;
openAlertCount: number;
onAlertsClick?: () => void;
}
function formatStorage(gb: number): string {
if (gb >= 1000) return `${(gb / 1000).toFixed(1)} TB`;
return `${gb.toFixed(1)} GB`;
}
function formatHours(h: number): string {
if (h >= 1000) return `${(h / 1000).toFixed(1)}k hrs`;
return `${h.toFixed(0)} hrs`;
}
// Heroicons outline paths
const ICONS = {
users: "M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z",
requests: "M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 0 0-1.883 2.542l.857 6a2.25 2.25 0 0 0 2.227 1.932H19.05a2.25 2.25 0 0 0 2.227-1.932l.857-6a2.25 2.25 0 0 0-1.883-2.542m-16.5 0V6A2.25 2.25 0 0 1 6 3.75h3.879a1.5 1.5 0 0 1 1.06.44l2.122 2.12a1.5 1.5 0 0 0 1.06.44H18A2.25 2.25 0 0 1 20.25 9v.776",
storage: "M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 2.625c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125m16.5 2.625c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125",
watch: "M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 0 1-1.125-1.125M3.375 19.5h1.5C5.496 19.5 6 18.996 6 18.375m-3.75.125v-6.375c0-.621.504-1.125 1.125-1.125H4.5m0-3.375v3.375m0-3.375h12M4.5 7.5H18a.75.75 0 0 1 .75.75v9.375c0 .621-.504 1.125-1.125 1.125h-1.5m-13.5 0h13.5m0 0v-3.375m0 3.375v-9.375c0-.621.504-1.125 1.125-1.125H21",
alert: "M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z",
};
function Card({
label,
value,
sub,
icon,
accent,
onClick,
}: {
label: string;
value: string;
sub?: string;
icon: keyof typeof ICONS;
accent?: "yellow" | "green";
onClick?: () => void;
}) {
const base = "rounded-xl border p-5 flex flex-col gap-2 transition-colors";
const interactive = onClick ? "cursor-pointer" : "";
let colorClass: string;
if (accent === "yellow") {
colorClass = "bg-yellow-950/30 border-yellow-700/50 hover:bg-yellow-950/50";
} else if (accent === "green") {
colorClass = "bg-green-950/30 border-green-800/50";
} else {
colorClass = `bg-slate-800/60 border-slate-700/60 ${onClick ? "hover:bg-slate-800 hover:border-slate-600" : ""}`;
}
return (
<div onClick={onClick} className={`${base} ${colorClass} ${interactive}`}>
<div className="flex items-center justify-between">
<span className="text-xs font-semibold uppercase tracking-widest text-slate-500">
{label}
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className={`h-4 w-4 ${
accent === "yellow"
? "text-yellow-500/70"
: accent === "green"
? "text-green-500/70"
: "text-slate-600"
}`}
>
<path strokeLinecap="round" strokeLinejoin="round" d={ICONS[icon]} />
</svg>
</div>
<span className={`text-3xl font-bold tabular-nums ${accent === "yellow" ? "text-yellow-300" : "text-white"}`}>
{value}
</span>
{sub && (
<span className={`text-xs ${accent === "yellow" ? "text-yellow-600" : "text-slate-600"}`}>
{sub}
</span>
)}
</div>
);
}
export default function SummaryCards({
totalUsers,
totalRequests,
totalStorageGB,
totalWatchHours,
openAlertCount,
onAlertsClick,
}: SummaryCardsProps) {
const colCount = (totalWatchHours !== null ? 1 : 0) + 4;
return (
<div
className={`grid grid-cols-2 gap-3 ${
colCount >= 5 ? "sm:grid-cols-5" : "sm:grid-cols-4"
}`}
>
<Card label="Users" value={totalUsers.toLocaleString()} icon="users" />
<Card label="Requests" value={totalRequests.toLocaleString()} icon="requests" />
<Card label="Storage" value={formatStorage(totalStorageGB)} icon="storage" />
{totalWatchHours !== null && (
<Card label="Watch Time" value={formatHours(totalWatchHours)} icon="watch" accent="green" />
)}
<Card
label="Open Alerts"
value={openAlertCount.toString()}
sub={openAlertCount > 0 ? "Tap to review" : "All clear"}
icon="alert"
accent={openAlertCount > 0 ? "yellow" : undefined}
onClick={openAlertCount > 0 ? onAlertsClick : undefined}
/>
</div>
);
}

146
src/lib/aggregate.ts Normal file
View File

@@ -0,0 +1,146 @@
import {
OverseerrUser,
OverseerrRequest,
TautulliUser,
MediaEntry,
UserStat,
DashboardStats,
} from "@/lib/types";
import { lookupTautulliUser } from "@/lib/tautulli";
import { generateAlertCandidates } from "@/lib/alerts";
import { upsertAlerts } from "@/lib/db";
export function bytesToGB(bytes: number): number {
return Math.round((bytes / 1024 / 1024 / 1024) * 10) / 10;
}
/** Compute dense rank (1 = highest value, ties share the same rank). */
function computeRanks(
items: Array<{ userId: number; value: number | null }>
): Map<number, number> {
const withValues = items.filter((i) => i.value !== null) as Array<{
userId: number;
value: number;
}>;
const sorted = [...withValues].sort((a, b) => b.value - a.value);
const rankMap = new Map<number, number>();
let currentRank = 1;
for (let i = 0; i < sorted.length; i++) {
if (i > 0 && sorted[i].value < sorted[i - 1].value) {
currentRank = i + 1;
}
rankMap.set(sorted[i].userId, currentRank);
}
return rankMap;
}
export function computeStats(
users: OverseerrUser[],
allRequests: Map<number, OverseerrRequest[]>,
radarrMap: Map<number, MediaEntry>,
sonarrMap: Map<number, MediaEntry>,
tautulliMap: Map<string, TautulliUser> | null
): DashboardStats {
const hasTautulli = tautulliMap !== null;
// Compute raw per-user totals
const rawStats = users.map((user) => {
const requests = allRequests.get(user.id) ?? [];
let totalBytes = 0;
for (const req of requests) {
if (req.type === "movie") {
totalBytes += radarrMap.get(req.media.tmdbId)?.sizeOnDisk ?? 0;
} else if (req.type === "tv" && req.media.tvdbId) {
totalBytes += sonarrMap.get(req.media.tvdbId)?.sizeOnDisk ?? 0;
}
}
let plays: number | null = null;
let watchHours: number | null = null;
if (hasTautulli && tautulliMap) {
const tu = lookupTautulliUser(tautulliMap, user.email, user.displayName);
plays = tu?.plays ?? 0;
watchHours = tu ? Math.round((tu.duration / 3600) * 10) / 10 : 0;
}
return {
userId: user.id,
displayName: user.displayName,
email: user.email,
requestCount: requests.length,
totalBytes,
plays,
watchHours,
};
});
const totalUsers = rawStats.length;
// Compute per-metric ranks
const storageRanks = computeRanks(
rawStats.map((r) => ({ userId: r.userId, value: r.totalBytes }))
);
const requestRanks = computeRanks(
rawStats.map((r) => ({ userId: r.userId, value: r.requestCount }))
);
const playsRanks = hasTautulli
? computeRanks(rawStats.map((r) => ({ userId: r.userId, value: r.plays })))
: null;
const watchRanks = hasTautulli
? computeRanks(
rawStats.map((r) => ({ userId: r.userId, value: r.watchHours }))
)
: null;
const userStats: UserStat[] = rawStats.map((raw) => {
const totalGB = bytesToGB(raw.totalBytes);
const avgGB =
raw.requestCount > 0
? Math.round((totalGB / raw.requestCount) * 10) / 10
: 0;
return {
...raw,
totalGB,
avgGB,
storageRank: storageRanks.get(raw.userId) ?? totalUsers,
requestRank: requestRanks.get(raw.userId) ?? totalUsers,
playsRank: playsRanks?.get(raw.userId) ?? null,
watchRank: watchRanks?.get(raw.userId) ?? null,
totalUsers,
};
});
// Generate alert candidates and persist to DB
const candidates = generateAlertCandidates(
userStats,
allRequests,
radarrMap,
sonarrMap,
hasTautulli
);
const openAlertCount = upsertAlerts(candidates);
const totalRequests = userStats.reduce((s, u) => s + u.requestCount, 0);
const totalStorageGB = bytesToGB(
userStats.reduce((s, u) => s + u.totalBytes, 0)
);
const totalWatchHours = hasTautulli
? Math.round(userStats.reduce((s, u) => s + (u.watchHours ?? 0), 0) * 10) /
10
: null;
return {
users: userStats,
summary: {
totalUsers,
totalRequests,
totalStorageGB,
totalWatchHours,
openAlertCount,
},
generatedAt: new Date().toISOString(),
};
}

319
src/lib/alerts.ts Normal file
View File

@@ -0,0 +1,319 @@
import { UserStat, OverseerrRequest, MediaEntry, AlertCandidate } from "@/lib/types";
// ─── Tunables ─────────────────────────────────────────────────────────────────
/** A movie/show must have been approved this many days ago before we alert on it */
const UNFULFILLED_MIN_AGE_DAYS = 3;
/** A pending request must be this old before we alert on it */
const PENDING_MIN_AGE_DAYS = 7;
/** User must have made their first request at least this long ago before ghost/watchrate alerts */
const USER_MIN_AGE_DAYS = 14;
/** Minimum requests before ghost/watchrate alerts */
const MIN_REQUESTS_GHOST = 5;
const MIN_REQUESTS_WATCHRATE = 10;
/** Watch-rate threshold — below this fraction (plays/requests) triggers a warning */
const LOW_WATCH_RATE = 0.2;
/** Minimum declines in the lookback window to flag */
const MIN_DECLINES = 3;
const DECLINE_LOOKBACK_DAYS = 60;
// ─── Helpers ──────────────────────────────────────────────────────────────────
function daysSince(iso: string): number {
return (Date.now() - new Date(iso).getTime()) / 86_400_000;
}
// ─── Generator ───────────────────────────────────────────────────────────────
export function generateAlertCandidates(
userStats: UserStat[],
allRequests: Map<number, OverseerrRequest[]>,
radarrMap: Map<number, MediaEntry>,
sonarrMap: Map<number, MediaEntry>,
hasTautulli: boolean
): AlertCandidate[] {
const candidates: AlertCandidate[] = [];
// ── CONTENT-CENTRIC: one alert per piece of media ──────────────────────────
// Track which content we've already flagged to avoid duplicate per-user alerts
const flaggedMovies = new Set<number>();
const flaggedShows = new Set<number>();
// Collect all unfulfilled content across all users
// Key: tmdbId/tvdbId → { entry, requestedBy: string[], oldestApproval: Date }
interface UnfilledEntry {
entry: MediaEntry;
requestedBy: string[];
oldestAge: number; // days since oldest qualifying request
}
const unfilledMovies = new Map<number, UnfilledEntry>();
const unfilledShows = new Map<number, UnfilledEntry>();
for (const user of userStats) {
const requests = allRequests.get(user.userId) ?? [];
for (const req of requests) {
// Only look at approved requests old enough to have been expected to download
if (req.status !== 2) continue;
const age = daysSince(req.createdAt);
if (age < UNFULFILLED_MIN_AGE_DAYS) continue;
if (req.type === "movie") {
const entry = radarrMap.get(req.media.tmdbId);
// Skip if not yet released (Radarr's isAvailable = false)
if (entry && !entry.available) continue;
const isUnfilled = !entry || entry.sizeOnDisk === 0;
if (!isUnfilled) continue;
const title =
entry?.title ?? req.media.title ?? `Movie #${req.media.tmdbId}`;
const existing = unfilledMovies.get(req.media.tmdbId);
if (existing) {
if (!existing.requestedBy.includes(user.displayName))
existing.requestedBy.push(user.displayName);
existing.oldestAge = Math.max(existing.oldestAge, age);
} else {
unfilledMovies.set(req.media.tmdbId, {
entry: { title, sizeOnDisk: 0, available: true },
requestedBy: [user.displayName],
oldestAge: age,
});
}
} else if (req.type === "tv" && req.media.tvdbId) {
const entry = sonarrMap.get(req.media.tvdbId);
// Skip if series hasn't started airing yet (Sonarr status = "upcoming")
if (entry && !entry.available) continue;
const isNothingDownloaded = !entry || entry.sizeOnDisk === 0;
// Partial: ended series with < 90% of episodes on disk
const isPartiallyDownloaded =
entry !== undefined &&
entry.sizeOnDisk > 0 &&
entry.seriesStatus === "ended" &&
entry.percentOfEpisodes !== undefined &&
entry.percentOfEpisodes < 90;
const isUnfilled = isNothingDownloaded || isPartiallyDownloaded;
if (!isUnfilled) continue;
const title =
entry?.title ?? req.media.title ?? `Show #${req.media.tvdbId}`;
const partial = !isNothingDownloaded && isPartiallyDownloaded;
const existing = unfilledShows.get(req.media.tvdbId);
if (existing) {
if (!existing.requestedBy.includes(user.displayName))
existing.requestedBy.push(user.displayName);
existing.oldestAge = Math.max(existing.oldestAge, age);
// Upgrade to partial flag if we now know it's partial
if (partial) (existing as UnfilledEntry & { partial?: boolean }).partial = true;
} else {
const record: UnfilledEntry & { partial?: boolean } = {
entry: { title, sizeOnDisk: entry?.sizeOnDisk ?? 0, available: true },
requestedBy: [user.displayName],
oldestAge: age,
};
if (partial) record.partial = true;
unfilledShows.set(req.media.tvdbId, record);
}
}
}
}
for (const [tmdbId, { entry, requestedBy, oldestAge }] of unfilledMovies) {
if (flaggedMovies.has(tmdbId)) continue;
flaggedMovies.add(tmdbId);
const daysStr = Math.floor(oldestAge) === 1 ? "1 day" : `${Math.floor(oldestAge)} days`;
const byStr = requestedBy.slice(0, 3).join(", ") + (requestedBy.length > 3 ? ` +${requestedBy.length - 3}` : "");
candidates.push({
key: `unfulfilled:movie:${tmdbId}`,
category: "unfulfilled",
severity: "warning",
title: `Not Downloaded: ${entry.title}`,
description: `Approved ${daysStr} ago but no file found in Radarr. Requested by ${byStr}.`,
mediaId: tmdbId,
mediaType: "movie",
mediaTitle: entry.title,
});
}
for (const [tvdbId, data] of unfilledShows) {
if (flaggedShows.has(tvdbId)) continue;
flaggedShows.add(tvdbId);
const { entry, requestedBy, oldestAge } = data;
const partial = (data as UnfilledEntry & { partial?: boolean }).partial ?? false;
const sonarrEntry = sonarrMap.get(tvdbId);
const daysStr = Math.floor(oldestAge) === 1 ? "1 day" : `${Math.floor(oldestAge)} days`;
const byStr = requestedBy.slice(0, 3).join(", ") + (requestedBy.length > 3 ? ` +${requestedBy.length - 3}` : "");
const pct = partial && sonarrEntry?.episodeFileCount !== undefined && sonarrEntry.totalEpisodeCount
? Math.round((sonarrEntry.episodeFileCount / sonarrEntry.totalEpisodeCount) * 100)
: null;
const description = partial && pct !== null
? `Only ${pct}% of episodes downloaded (${sonarrEntry!.episodeFileCount}/${sonarrEntry!.totalEpisodeCount}). Approved ${daysStr} ago. Requested by ${byStr}.`
: `Approved ${daysStr} ago but no files found in Sonarr. Requested by ${byStr}.`;
candidates.push({
key: `unfulfilled:tv:${tvdbId}`,
category: "unfulfilled",
severity: "warning",
title: partial ? `Incomplete Download: ${entry.title}` : `Not Downloaded: ${entry.title}`,
description,
mediaId: tvdbId,
mediaType: "tv",
mediaTitle: entry.title,
});
}
// ── CONTENT-CENTRIC: stale pending requests ───────────────────────────────
// One alert per pending request item (not per user)
const flaggedPending = new Set<number>();
for (const user of userStats) {
const requests = allRequests.get(user.userId) ?? [];
for (const req of requests) {
if (req.status !== 1) continue;
if (daysSince(req.createdAt) < PENDING_MIN_AGE_DAYS) continue;
const age = Math.floor(daysSince(req.createdAt));
const ageStr = age === 1 ? "1 day" : `${age} days`;
if (req.type === "movie" && !flaggedPending.has(req.id)) {
// Skip if movie isn't released yet
const movieEntry = radarrMap.get(req.media.tmdbId);
if (movieEntry && !movieEntry.available) continue;
flaggedPending.add(req.id);
const title =
radarrMap.get(req.media.tmdbId)?.title ??
req.media.title ??
`Movie #${req.media.tmdbId}`;
candidates.push({
key: `pending:req:${req.id}`,
category: "pending",
severity: "warning",
title: `Pending Approval: ${title}`,
description: `Awaiting approval for ${ageStr}. Requested by ${user.displayName}.`,
mediaId: req.media.tmdbId,
mediaType: "movie",
mediaTitle: title,
userId: user.userId,
userName: user.displayName,
});
} else if (req.type === "tv" && req.media.tvdbId && !flaggedPending.has(req.id)) {
// Skip if show hasn't started airing yet
const showEntry = sonarrMap.get(req.media.tvdbId);
if (showEntry && !showEntry.available) continue;
flaggedPending.add(req.id);
const title =
showEntry?.title ?? req.media.title ?? `Show #${req.media.tvdbId}`;
candidates.push({
key: `pending:req:${req.id}`,
category: "pending",
severity: "warning",
title: `Pending Approval: ${title}`,
description: `Awaiting approval for ${ageStr}. Requested by ${user.displayName}.`,
mediaId: req.media.tvdbId,
mediaType: "tv",
mediaTitle: title,
userId: user.userId,
userName: user.displayName,
});
}
}
}
// ── USER-BEHAVIOR: one category per user, most severe wins ───────────────
// Ghost Requester takes priority over Low Watch Rate for the same user.
// Only generate these alerts if the user is "established" (old enough account).
for (const user of userStats) {
const requests = allRequests.get(user.userId) ?? [];
if (requests.length === 0) continue;
// Check if user is established (has at least one request old enough)
const oldestRequestAge = Math.max(...requests.map((r) => daysSince(r.createdAt)));
const isEstablished = oldestRequestAge >= USER_MIN_AGE_DAYS;
if (!isEstablished) continue;
// ── Ghost Requester ───────────────────────────────────────────────────
if (
hasTautulli &&
user.plays === 0 &&
user.requestCount >= MIN_REQUESTS_GHOST
) {
candidates.push({
key: `ghost:${user.userId}`,
category: "ghost",
severity: "warning",
title: `Ghost Requester`,
description: `${user.displayName} has ${user.requestCount} requests but has never watched anything on Plex.`,
userId: user.userId,
userName: user.displayName,
});
// Ghost takes priority — skip watch-rate check for this user
continue;
}
// ── Low Watch Rate ────────────────────────────────────────────────────
if (
hasTautulli &&
user.plays !== null &&
user.plays > 0 &&
user.requestCount >= MIN_REQUESTS_WATCHRATE
) {
const ratio = user.plays / user.requestCount;
if (ratio < LOW_WATCH_RATE) {
const pct = Math.round(ratio * 100);
candidates.push({
key: `watchrate:${user.userId}`,
category: "watchrate",
severity: "info",
title: `Low Watch Rate`,
description: `${user.displayName} watches ~${pct}% of what they request (${user.plays.toLocaleString()} plays, ${user.requestCount} requests).`,
userId: user.userId,
userName: user.displayName,
});
continue; // don't also check declines for same priority slot
}
}
// ── Declined Streak ───────────────────────────────────────────────────
const recentDeclines = requests.filter(
(r) => r.status === 3 && daysSince(r.createdAt) <= DECLINE_LOOKBACK_DAYS
);
if (recentDeclines.length >= MIN_DECLINES) {
candidates.push({
key: `declined:${user.userId}`,
category: "declined",
severity: "info",
title: `Frequent Declines`,
description: `${user.displayName} has had ${recentDeclines.length} requests declined in the last ${DECLINE_LOOKBACK_DAYS} days.`,
userId: user.userId,
userName: user.displayName,
});
}
}
// ── SYSTEM: Tautulli configured but no matches ────────────────────────────
if (hasTautulli) {
const totalPlays = userStats.reduce((s, u) => s + (u.plays ?? 0), 0);
if (totalPlays === 0 && userStats.length > 0) {
candidates.push({
key: "tautulli-no-matches",
category: "tautulli-no-matches",
severity: "danger",
title: "No Tautulli Watch Data",
description:
"Tautulli is configured but no plays were matched to any user. Check that emails align between Overseerr and Tautulli.",
});
}
}
// Sort: danger → warning → info
const order: Record<string, number> = { danger: 0, warning: 1, info: 2 };
candidates.sort((a, b) => order[a.severity] - order[b.severity]);
return candidates;
}

243
src/lib/db.ts Normal file
View File

@@ -0,0 +1,243 @@
/**
* Lightweight JSON file store for alert persistence.
* Lives at data/alerts.json (gitignored, created on first run).
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
import { join } from "path";
import {
AlertCandidate,
AlertStatus,
AlertCloseReason,
AlertComment,
Alert,
} from "./types";
const DATA_DIR = join(process.cwd(), "data");
const DB_PATH = join(DATA_DIR, "alerts.json");
// Cooldown days applied on MANUAL close — suppresses re-opening for this long.
// Auto-resolved alerts have no cooldown and can reopen immediately if the
// condition returns.
const COOLDOWN: Record<string, number> = {
unfulfilled: 3,
pending: 3,
ghost: 14,
watchrate: 14,
declined: 14,
"tautulli-no-matches": 1,
"dark-library": 30,
};
const DEFAULT_COOLDOWN = 7;
interface Store {
nextId: number;
nextCommentId: number;
alerts: Record<string, StoredAlert>; // keyed by alert.key
}
interface StoredAlert {
id: number;
key: string;
category: string;
severity: string;
title: string;
description: string;
userId?: number;
userName?: string;
mediaId?: number;
mediaType?: string;
mediaTitle?: string;
status: AlertStatus;
closeReason: AlertCloseReason | null;
suppressedUntil: string | null;
firstSeen: string;
lastSeen: string;
closedAt: string | null;
comments: Array<{ id: number; body: string; createdAt: string }>;
}
function load(): Store {
if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
if (!existsSync(DB_PATH)) {
const empty: Store = { nextId: 1, nextCommentId: 1, alerts: {} };
writeFileSync(DB_PATH, JSON.stringify(empty, null, 2));
return empty;
}
return JSON.parse(readFileSync(DB_PATH, "utf-8")) as Store;
}
function save(store: Store) {
writeFileSync(DB_PATH, JSON.stringify(store, null, 2));
}
function toAlert(s: StoredAlert): Alert {
return {
id: s.id,
key: s.key,
category: s.category,
severity: s.severity as Alert["severity"],
title: s.title,
description: s.description,
userId: s.userId,
userName: s.userName,
mediaId: s.mediaId,
mediaType: s.mediaType as Alert["mediaType"],
mediaTitle: s.mediaTitle,
status: s.status,
closeReason: s.closeReason ?? null,
suppressedUntil: s.suppressedUntil,
firstSeen: s.firstSeen,
lastSeen: s.lastSeen,
closedAt: s.closedAt,
comments: s.comments,
};
}
/**
* Merge generated candidates into the store, then auto-resolve any open alerts
* whose condition is no longer present (key not in this run's candidate set).
*
* Auto-resolved alerts:
* - Are marked closed with closeReason = "resolved"
* - Have NO suppressedUntil — they can reopen immediately if the condition returns
*
* Manually closed alerts:
* - Have suppressedUntil set (cooldown per category)
* - Won't be re-opened by upsertAlerts until that cooldown expires
*
* Returns the count of open alerts after the merge.
*/
export function upsertAlerts(candidates: AlertCandidate[]): number {
const store = load();
const now = new Date();
const nowISO = now.toISOString();
const candidateKeys = new Set(candidates.map((c) => c.key));
// ── Step 1: upsert candidates ─────────────────────────────────────────────
for (const c of candidates) {
const existing = store.alerts[c.key];
if (existing) {
const isSuppressed =
existing.status === "closed" &&
existing.suppressedUntil !== null &&
new Date(existing.suppressedUntil) > now;
if (isSuppressed) continue;
// Re-open if previously closed (manually or resolved) and not suppressed
if (existing.status === "closed") {
existing.status = "open";
existing.closeReason = null;
existing.closedAt = null;
existing.suppressedUntil = null;
existing.firstSeen = nowISO; // treat as a new occurrence
existing.comments = [];
}
// Refresh content and lastSeen
existing.lastSeen = nowISO;
existing.title = c.title;
existing.description = c.description;
if (c.userName) existing.userName = c.userName;
if (c.mediaTitle) existing.mediaTitle = c.mediaTitle;
} else {
store.alerts[c.key] = {
id: store.nextId++,
key: c.key,
category: c.category,
severity: c.severity,
title: c.title,
description: c.description,
userId: c.userId,
userName: c.userName,
mediaId: c.mediaId,
mediaType: c.mediaType,
mediaTitle: c.mediaTitle,
status: "open",
closeReason: null,
suppressedUntil: null,
firstSeen: nowISO,
lastSeen: nowISO,
closedAt: null,
comments: [],
};
}
}
// ── Step 2: auto-resolve alerts whose condition is gone ───────────────────
for (const alert of Object.values(store.alerts)) {
if (alert.status !== "open") continue;
if (candidateKeys.has(alert.key)) continue;
// Condition no longer exists — resolve it automatically, no cooldown
alert.status = "closed";
alert.closeReason = "resolved";
alert.closedAt = nowISO;
alert.suppressedUntil = null;
}
save(store);
return Object.values(store.alerts).filter((a) => a.status === "open").length;
}
export function getAllAlerts(): Alert[] {
const store = load();
return Object.values(store.alerts)
.sort((a, b) => {
if (a.status !== b.status) return a.status === "open" ? -1 : 1;
return new Date(b.lastSeen).getTime() - new Date(a.lastSeen).getTime();
})
.map(toAlert);
}
export function getAlertById(id: number): Alert | null {
const store = load();
const found = Object.values(store.alerts).find((a) => a.id === id);
return found ? toAlert(found) : null;
}
export function closeAlert(id: number): Alert | null {
const store = load();
const alert = Object.values(store.alerts).find((a) => a.id === id);
if (!alert) return null;
const cooldownDays = COOLDOWN[alert.category] ?? DEFAULT_COOLDOWN;
const suppressUntil = new Date();
suppressUntil.setDate(suppressUntil.getDate() + cooldownDays);
alert.status = "closed";
alert.closeReason = "manual";
alert.closedAt = new Date().toISOString();
alert.suppressedUntil = suppressUntil.toISOString();
save(store);
return toAlert(alert);
}
export function reopenAlert(id: number): Alert | null {
const store = load();
const alert = Object.values(store.alerts).find((a) => a.id === id);
if (!alert) return null;
alert.status = "open";
alert.closeReason = null;
alert.closedAt = null;
alert.suppressedUntil = null;
save(store);
return toAlert(alert);
}
export function addComment(alertId: number, body: string): AlertComment | null {
const store = load();
const alert = Object.values(store.alerts).find((a) => a.id === alertId);
if (!alert) return null;
const comment = {
id: store.nextCommentId++,
body,
createdAt: new Date().toISOString(),
};
alert.comments.push(comment);
save(store);
return comment;
}

51
src/lib/overseerr.ts Normal file
View File

@@ -0,0 +1,51 @@
import { OverseerrUser, OverseerrRequest } from "@/lib/types";
const TAKE = 100;
export async function fetchAllUsers(): Promise<OverseerrUser[]> {
const all: OverseerrUser[] = [];
let skip = 0;
while (true) {
const res = await fetch(
`${process.env.SEERR_URL}/api/v1/user?take=${TAKE}&skip=${skip}&sort=created`,
{ headers: { "X-Api-Key": process.env.SEERR_API! } }
);
if (!res.ok) {
throw new Error(`Overseerr users API error: ${res.status} ${res.statusText}`);
}
const data: { results: OverseerrUser[] } = await res.json();
all.push(...data.results);
if (data.results.length < TAKE) break;
skip += TAKE;
}
return all;
}
export async function fetchUserRequests(userId: number): Promise<OverseerrRequest[]> {
const all: OverseerrRequest[] = [];
let skip = 0;
while (true) {
const res = await fetch(
`${process.env.SEERR_URL}/api/v1/request?requestedBy=${userId}&take=${TAKE}&skip=${skip}`,
{ headers: { "X-Api-Key": process.env.SEERR_API! } }
);
if (!res.ok) {
throw new Error(`Overseerr requests API error for user ${userId}: ${res.status} ${res.statusText}`);
}
const data: { results: OverseerrRequest[] } = await res.json();
all.push(...data.results);
if (data.results.length < TAKE) break;
skip += TAKE;
}
return all;
}

19
src/lib/radarr.ts Normal file
View File

@@ -0,0 +1,19 @@
import { RadarrMovie, MediaEntry } from "@/lib/types";
export async function buildRadarrMap(): Promise<Map<number, MediaEntry>> {
const res = await fetch(`${process.env.RADARR_URL}/api/v3/movie`, {
headers: { "X-Api-Key": process.env.RADARR_API! },
});
if (!res.ok) {
throw new Error(`Radarr API error: ${res.status} ${res.statusText}`);
}
const movies: RadarrMovie[] = await res.json();
return new Map(
movies.map((m) => [
m.tmdbId,
{ title: m.title, sizeOnDisk: m.sizeOnDisk, available: m.isAvailable },
])
);
}

28
src/lib/sonarr.ts Normal file
View File

@@ -0,0 +1,28 @@
import { SonarrSeries, MediaEntry } from "@/lib/types";
export async function buildSonarrMap(): Promise<Map<number, MediaEntry>> {
const res = await fetch(`${process.env.SONARR_URL}/api/v3/series`, {
headers: { "X-Api-Key": process.env.SONARR_API! },
});
if (!res.ok) {
throw new Error(`Sonarr API error: ${res.status} ${res.statusText}`);
}
const series: SonarrSeries[] = await res.json();
return new Map(
series.map((s) => [
s.tvdbId,
{
title: s.title,
sizeOnDisk: s.statistics.sizeOnDisk,
// "upcoming" = series hasn't started airing yet
available: s.status !== "upcoming",
episodeFileCount: s.statistics.episodeFileCount,
totalEpisodeCount: s.statistics.totalEpisodeCount,
percentOfEpisodes: s.statistics.percentOfEpisodes,
seriesStatus: s.status,
},
])
);
}

78
src/lib/tautulli.ts Normal file
View File

@@ -0,0 +1,78 @@
import { TautulliUser } from "@/lib/types";
interface TautulliRow {
friendly_name: string;
email: string;
plays: number;
duration: number;
last_seen: number | null;
}
interface TautulliResponse {
response: {
result: string;
data: {
data: TautulliRow[];
};
};
}
/**
* Returns a Map<lowercaseEmail, TautulliUser>.
* Returns null if TAUTULLI_URL/TAUTULLI_API are not set.
*/
export async function buildTautulliMap(): Promise<Map<string, TautulliUser> | null> {
const url = process.env.TAUTULLI_URL;
const key = process.env.TAUTULLI_API;
if (!url || !key) return null;
const res = await fetch(
`${url}/api/v2?apikey=${key}&cmd=get_users_table&length=1000&order_column=friendly_name&order_dir=asc`,
{ cache: "no-store" }
);
if (!res.ok) {
throw new Error(`Tautulli API error: ${res.status} ${res.statusText}`);
}
const json: TautulliResponse = await res.json();
if (json.response.result !== "success") {
throw new Error(`Tautulli API returned non-success result`);
}
const map = new Map<string, TautulliUser>();
for (const row of json.response.data.data) {
const user: TautulliUser = {
friendly_name: row.friendly_name,
email: row.email ?? "",
plays: row.plays ?? 0,
duration: row.duration ?? 0,
last_seen: row.last_seen ?? null,
};
if (user.email) {
map.set(user.email.toLowerCase(), user);
}
// Also index by friendly_name as fallback key
if (user.friendly_name) {
map.set(`name:${user.friendly_name.toLowerCase()}`, user);
}
}
return map;
}
export function lookupTautulliUser(
tautulliMap: Map<string, TautulliUser>,
email: string,
displayName: string
): TautulliUser | null {
return (
tautulliMap.get(email.toLowerCase()) ??
tautulliMap.get(`name:${displayName.toLowerCase()}`) ??
null
);
}

134
src/lib/types.ts Normal file
View File

@@ -0,0 +1,134 @@
// ─── Raw API shapes ───────────────────────────────────────────────────────────
export interface OverseerrUser {
id: number;
displayName: string;
email: string;
requestCount: number;
userType: number;
}
export interface OverseerrRequest {
id: number;
type: "movie" | "tv";
status: number; // 1=pending, 2=approved, 3=declined, 4=available
createdAt: string; // ISO timestamp
media: {
tmdbId: number;
tvdbId?: number;
title?: string;
};
}
export interface RadarrMovie {
tmdbId: number;
title: string;
sizeOnDisk: number; // bytes
isAvailable: boolean; // false = unreleased / below minimum availability
}
export interface SonarrSeries {
tvdbId: number;
title: string;
status: string; // "continuing" | "ended" | "upcoming" | "deleted"
statistics: {
sizeOnDisk: number; // bytes
episodeFileCount: number;
totalEpisodeCount: number;
percentOfEpisodes: number; // 0100
};
}
export interface TautulliUser {
friendly_name: string;
email: string;
plays: number;
duration: number; // seconds
last_seen: number | null; // unix timestamp
}
// ─── Richer map value types ───────────────────────────────────────────────────
export interface MediaEntry {
title: string;
sizeOnDisk: number; // bytes
available: boolean; // false = unreleased, skip unfulfilled alerts
// TV-specific (undefined for movies)
episodeFileCount?: number;
totalEpisodeCount?: number;
percentOfEpisodes?: number; // 0100
seriesStatus?: string; // "continuing" | "ended" | "upcoming" | "deleted"
}
// ─── Aggregated output ────────────────────────────────────────────────────────
export interface UserStat {
userId: number;
displayName: string;
email: string;
requestCount: number;
totalBytes: number;
totalGB: number;
avgGB: number;
// Tautulli (null when not configured)
plays: number | null;
watchHours: number | null;
// Per-metric ranks (1 = top user for that metric, null = Tautulli not available)
storageRank: number;
requestRank: number;
playsRank: number | null;
watchRank: number | null;
totalUsers: number;
}
export interface DashboardStats {
users: UserStat[];
summary: {
totalUsers: number;
totalRequests: number;
totalStorageGB: number;
totalWatchHours: number | null;
openAlertCount: number;
};
generatedAt: string;
}
// ─── Alerts ───────────────────────────────────────────────────────────────────
export type AlertSeverity = "danger" | "warning" | "info";
export type AlertStatus = "open" | "closed";
/** In-memory candidate produced by alert generation logic */
export interface AlertCandidate {
key: string; // deterministic dedup key, e.g. "unfulfilled:movie:12345"
category: string; // e.g. "unfulfilled", "ghost", "pending"
severity: AlertSeverity;
title: string;
description: string;
// At most one of userId or mediaId is the "subject"
userId?: number;
userName?: string;
mediaId?: number;
mediaType?: "movie" | "tv";
mediaTitle?: string;
}
export interface AlertComment {
id: number;
body: string;
createdAt: string;
}
export type AlertCloseReason = "manual" | "resolved";
/** Full persisted alert returned by the API */
export interface Alert extends AlertCandidate {
id: number; // auto-increment DB id (used in URLs)
status: AlertStatus;
closeReason: AlertCloseReason | null; // null = still open
suppressedUntil: string | null; // only set on manual close
firstSeen: string;
lastSeen: string;
closedAt: string | null;
comments: AlertComment[];
}