Jellyfin: who is watching, and don't update a machine mid-film

New Jellyfin integration (read-only, every 2 minutes): version, restart wanted,
streams and transcoding, failed scheduled tasks, item counts, failed sign-ins.
Monitoring -> Jellyfin page with a peak-streams history, three alerts, /metrics.

When Jellyfin runs on a managed server, an update run asks first if people are
streaming (409 "watching" unless startAnyway), and a patch plan waits up to two
hours for them before updating that server.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-24 22:01:18 +02:00
1 parent 2f082ca5c2
commit 0146eb8bca
38 files changed
+8136 -13

No files matched your search

+4
View File
@@ -29,6 +29,7 @@ import { getSourceStatus } from "../services/integrationHealthMonitor.js";
import { removeIntegrationData, syncUnifiIntegration } from "../services/unifiSync.js";
import { removeHomeAssistantData, syncHomeAssistant } from "../services/homeAssistantSync.js";
import { forgetUps, syncUps } from "../services/upsSync.js";
import { forgetJellyfin, syncJellyfin } from "../services/jellyfinSync.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { getSettings, updateSettings } from "../services/settingsStore.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -131,6 +132,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res)
if (type === "unifi") void syncUnifiIntegration(created.id).then(() => invalidateAlertsCache());
if (type === "homeassistant") void syncHomeAssistant(created.id).then(() => invalidateAlertsCache());
if (type === "ups") void syncUps(created.id).then(() => invalidateAlertsCache());
if (type === "jellyfin") void syncJellyfin(created.id).then(() => invalidateAlertsCache());
res.status(201).json({
integration: {
@@ -234,6 +236,7 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req,
if (updated.type === "unifi" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUnifiIntegration(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "homeassistant" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncHomeAssistant(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "ups" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUps(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "jellyfin" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncJellyfin(updated.id).then(() => invalidateAlertsCache());
res.json({
integration: {
@@ -313,6 +316,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req,
if (existing.type === "unifi") await removeIntegrationData(id);
if (existing.type === "homeassistant") await removeHomeAssistantData(id);
if (existing.type === "ups") await forgetUps(id);
if (existing.type === "jellyfin") await forgetJellyfin(id);
await db.delete(integrations).where(eq(integrations.id, id));
if (existing.credentialId) {
await db.delete(integrationCredentials).where(eq(integrationCredentials.id, existing.credentialId));
+77
View File
@@ -0,0 +1,77 @@
import { Router } from "express";
import { and, asc, eq, gte } from "drizzle-orm";
import { db } from "../db/client.js";
import { integrations, jellyfinReadings, jellyfinState, servers } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { hostOfAddress } from "../services/kumaTargets.js";
import { bucketPeaks, isJellyfinFresh, jellyfinProblems, jellyfinSyncStatuses, READING_KEEP_DAYS, streamsOf, tasksOf, watchingOnServer, watchingWords } from "../services/jellyfinSync.js";
import { matchServerForTarget } from "../services/uptimeKumaMatch.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const jellyfinRouter = Router();
jellyfinRouter.use(requireAuth);
const DAY_MS = 86_400_000;
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
/** Every Jellyfin, how it is and who is streaming from it, from what the last read stored. Everyone signed in can see it, like the other pages made of stored readings. */
jellyfinRouter.get("/", asyncHandler(async (_req, res) => {
const [rows, states, statuses, serverRows] = await Promise.all([
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled, baseUrl: integrations.baseUrl }).from(integrations).where(eq(integrations.type, "jellyfin")).orderBy(integrations.name),
db.select().from(jellyfinState),
jellyfinSyncStatuses(),
db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ipAddresses: servers.ipAddresses }).from(servers),
]);
const matchable = serverRows.map((s) => {
let ips: string[] = [];
try {
const v = JSON.parse(s.ipAddresses ?? "[]");
ips = Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
// none
}
return { id: s.id, name: s.name, hostname: s.hostname, ips };
});
const byId = new Map(states.map((s) => [s.integrationId, s]));
const now = Date.now();
res.json({
jellyfins: rows.map((r) => {
const state = byId.get(r.id) ?? null;
const status = statuses[r.id] ?? null;
const fresh = isJellyfinFresh(status ?? undefined, now);
const machine = matchServerForTarget(hostOfAddress(r.baseUrl), matchable);
return {
id: r.id,
name: r.name,
enabled: r.enabled,
runsOn: machine ? { id: machine.id, name: machine.name } : null,
status,
fresh,
state: state ? { serverName: state.serverName, version: state.version, os: state.os, pendingRestart: state.pendingRestart, updateAvailable: state.updateAvailable, streams: streamsOf(state), tasks: tasksOf(state), counts: { movies: state.movies, series: state.series, episodes: state.episodes, songs: state.songs }, failedLogins24h: state.failedLogins24h, updatedAt: state.updatedAt } : null,
problems: state && fresh ? jellyfinProblems(r.id, r.name, state) : [],
};
}),
});
}));
/** Who is streaming from the Jellyfin that runs on a server, for the warning before it is restarted. */
jellyfinRouter.get("/watching", asyncHandler(async (req, res) => {
const serverId = idOf(String(req.query.serverId ?? ""));
if (!Number.isInteger(serverId)) return res.status(400).json({ error: "invalid_id" });
const watching = await watchingOnServer(serverId);
res.json({ watching, words: watchingWords(watching) });
}));
/** How many were streaming over time, as peaks (readings are kept 35 days). */
jellyfinRouter.get("/:id/history", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [row] = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).where(eq(integrations.id, id)).limit(1);
if (!row || row.type !== "jellyfin") return res.status(404).json({ error: "not_found" });
const asked = Number(req.query.days);
const days = Number.isFinite(asked) ? Math.min(READING_KEEP_DAYS, Math.max(1, Math.round(asked))) : 7;
const to = Date.now();
const from = to - days * DAY_MS;
const rows = await db.select().from(jellyfinReadings).where(and(eq(jellyfinReadings.integrationId, id), gte(jellyfinReadings.at, new Date(from).toISOString()))).orderBy(asc(jellyfinReadings.at));
res.json({ jellyfin: { id: row.id, name: row.name }, days, points: bucketPeaks(rows, from, to, 200) });
}));
+2
View File
@@ -18,6 +18,8 @@ const startSchema = z.object({
templateId: z.number().int().positive(),
limit: z.string().trim().regex(/^[A-Za-z0-9][A-Za-z0-9._,:*\-]{0,199}$/, "Use the host name as it is in the Semaphore inventory, like web01"),
windowMinutes: z.number().int().min(15).max(480).default(90),
// Somebody is streaming from the machine and the person has seen the warning.
startAnyway: z.boolean().optional(),
});
const shape = (r: Awaited<ReturnType<typeof listUpdateRuns>>[number]) => ({