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
+146
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
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
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
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
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
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
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
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[];
}