// sonarr's events. The tool runtime imports this once the broker is bound. It watches the download // queue and turns its comings and goings into mesh events. // // Emits (novox/hq ADR 0041/0042): // module.sonarr.episode.grabbed — a release entered the queue (Sonarr grabbed it) // module.sonarr.download.completed — a release left the queue, imported. This exact routing key // is what the plex module consumes (module.*.download.completed) // to rescan, so the new episode becomes a visible item. // Consumes: none. // // The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a // restart mid-download does not re-announce everything already in flight as freshly grabbed. import { emit } from "@novox/mesh-sdk/events"; import { SonarrClient, type SonarrQueueItem } from "./client.js"; // Building the client throws when Sonarr has no URL/key yet. Like the tools (see tools/index.ts), // the events entrypoint must not crash the runtime for that — it stays idle until configured. function buildClient(): SonarrClient | null { try { return SonarrClient.fromEnv(); } catch { return null; } } const sonarr = buildClient(); // Sonarr removes an item from the queue once it has been imported; a "warning"/"failed" status is // how a stuck or broken grab shows itself, so we do not call those a completion when they vanish. const FAILED_STATUSES = new Set(["failed", "warning"]); const inQueue = new Map(); let primed = false; async function pollQueue(sonarr: SonarrClient): Promise { const { items } = await sonarr.getQueue(); const now = new Map(items.map((i) => [i.id, i])); if (primed) { // Entered the queue since last look — Sonarr grabbed a release. for (const [id, item] of now) { if (!inQueue.has(id)) await emit("module.sonarr.episode.grabbed", { title: item.title, status: item.status }); } // Left the queue — imported and done, unless it was last seen failing. for (const [id, item] of inQueue) { if (!now.has(id) && !FAILED_STATUSES.has(item.status)) { await emit("module.sonarr.download.completed", { title: item.title }); } } } inQueue.clear(); for (const [id, item] of now) inQueue.set(id, item); primed = true; } const tick = (fn: () => Promise, everyMs: number): void => { const run = (): void => void fn().catch((err) => console.error(`[sonarr] ${err}`)); setInterval(run, everyMs); run(); }; if (sonarr) { tick(() => pollQueue(sonarr), 30_000); console.log("[sonarr] watching the download queue, emitting grabs and completions"); } else { console.log("[sonarr] not configured — events idle until an API key is available"); }