import { Router } from "express"; import { inArray } from "drizzle-orm"; import { db } from "../db/client.js"; import { arrState, integrations } from "../db/schema.js"; import { requireAuth } from "../auth/middleware.js"; import { ARR_KINDS, type ArrKind } from "../integrations/arr/adapter.js"; import { arrProblems, arrSyncStatuses, distinctDisks, isArrFresh, stuckItems, storedOf } from "../services/arrSync.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const arrRouter = Router(); arrRouter.use(requireAuth); /** Every Sonarr, Radarr and Prowlarr, how it is, from what the last reads stored: what it says is wrong, its queue (with what is stuck), disks, missing items and indexers. Everyone signed in can see it. Nothing here changes anything in them. */ arrRouter.get("/", asyncHandler(async (_req, res) => { const [rows, states, statuses] = await Promise.all([ db.select({ id: integrations.id, type: integrations.type, name: integrations.name, enabled: integrations.enabled, baseUrl: integrations.baseUrl }).from(integrations).where(inArray(integrations.type, ARR_KINDS)).orderBy(integrations.name), db.select().from(arrState), arrSyncStatuses(), ]); const byId = new Map(states.map((s) => [s.integrationId, s])); const now = Date.now(); res.json({ apps: rows.map((r) => { const row = byId.get(r.id); const state = row ? storedOf(row) : null; const status = statuses[r.id] ?? null; const fresh = isArrFresh(status ?? undefined, now); return { id: r.id, kind: r.type as ArrKind, name: r.name, enabled: r.enabled, url: r.baseUrl, status, fresh, state: state && { ...state, disks: state.disks && distinctDisks(state.disks), /** The ids of the queue items that are stuck, so the page marks them the way the alert counts them. */ stuck: stuckItems(state.queue, now).map((i) => i.id), }, problems: state && fresh ? arrProblems(r.type as ArrKind, r.id, r.name, state, now) : [], }; }), }); }));