Files
Homelab-manager/server/src/integrations/jellyfin/adapter.ts
T
bobbanandClaude Sonnet 5.5 0146eb8bca 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>
2026-10-24 22:01:18 +02:00

170 lines
7.4 KiB
TypeScript

/**
* Jellyfin adapter. Config: url, apiKey (made in Jellyfin under Dashboard → API Keys); optional: insecure.
*
* Reading only: the server's own information (version, whether it wants a restart or an update), who is streaming right now and whether it is being transcoded, the scheduled tasks
* (a library scan that failed), how many items there are and how many sign-ins failed lately. Nothing is sent to Jellyfin but requests for these.
*
* Endpoints and field names are from Jellyfin's published API (`/System/Info`, `/Sessions`, `/ScheduledTasks`, `/Items/Counts`, `/System/ActivityLog/Entries`) and have not
* been checked against a live server here; every field is read defensively, and one that is missing is just left out.
*/
import { requestJson } from "../httpJson.js";
import { withDiagLogging } from "../../services/diagLog.js";
export interface JellyfinConfig {
url: string;
apiKey: string;
insecure?: boolean;
}
export interface JellyfinStream {
user: string;
client: string | null;
device: string | null;
/** What is being watched or listened to, with the series it is of. */
title: string;
/** Converted on the fly, which is what loads the server. */
transcoding: boolean;
paused: boolean;
}
export interface JellyfinTask {
name: string;
category: string | null;
state: string;
/** Completed, Failed, Cancelled or Aborted; null when it has never run. */
lastStatus: string | null;
lastEndedAt: string | null;
error: string | null;
}
export interface JellyfinRead {
name: string | null;
version: string | null;
os: string | null;
pendingRestart: boolean;
updateAvailable: boolean;
streams: JellyfinStream[];
tasks: JellyfinTask[];
counts: { movies: number | null; series: number | null; episodes: number | null; songs: number | null };
/** Failed sign-ins in the last day; null when the activity log could not be read. */
failedLogins24h: number | null;
}
export interface JellyfinAdapter {
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
read(now?: Date): Promise<JellyfinRead>;
}
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
const iso = (v: unknown): string | null => {
const s = str(v);
return s && Number.isFinite(Date.parse(s)) ? new Date(s).toISOString() : null;
};
/** Pure: what /System/Info says. */
export function parseSystemInfo(raw: unknown): Pick<JellyfinRead, "name" | "version" | "os" | "pendingRestart" | "updateAvailable"> {
const o = obj(raw);
return { name: str(o.ServerName), version: str(o.Version), os: str(o.OperatingSystemDisplayName) ?? str(o.OperatingSystem), pendingRestart: o.HasPendingRestart === true, updateAvailable: o.HasUpdateAvailable === true };
}
/** Pure: the sessions that are playing something. A session with nothing playing is just somebody signed in. */
export function parseSessions(raw: unknown): JellyfinStream[] {
const out: JellyfinStream[] = [];
for (const item of Array.isArray(raw) ? raw : []) {
const s = obj(item);
const playing = obj(s.NowPlayingItem);
const name = str(playing.Name);
if (!name) continue;
const series = str(playing.SeriesName);
const state = obj(s.PlayState);
out.push({
user: str(s.UserName) ?? "someone",
client: str(s.Client),
device: str(s.DeviceName),
title: series ? `${series} — ${name}` : name,
transcoding: str(state.PlayMethod)?.toLowerCase() === "transcode" || (s.TranscodingInfo !== undefined && s.TranscodingInfo !== null && Object.keys(obj(s.TranscodingInfo)).length > 0),
paused: state.IsPaused === true,
});
}
return out;
}
/** Pure: the scheduled tasks with how they last ended. */
export function parseTasks(raw: unknown): JellyfinTask[] {
const out: JellyfinTask[] = [];
for (const item of Array.isArray(raw) ? raw : []) {
const t = obj(item);
const name = str(t.Name);
if (!name || t.IsHidden === true) continue;
const last = obj(t.LastExecutionResult);
out.push({ name, category: str(t.Category), state: str(t.State) ?? "Idle", lastStatus: str(last.Status), lastEndedAt: iso(last.EndTimeUtc), error: str(last.ErrorMessage) });
}
return out;
}
/** Pure: how many of the activity log's entries from the last day are failed sign-ins. */
export function countFailedLogins(raw: unknown, now: Date): number | null {
const items = obj(raw).Items;
if (!Array.isArray(items)) return null;
const since = now.getTime() - 86_400_000;
return items.filter((i) => {
const e = obj(i);
const at = Date.parse(String(e.Date ?? ""));
return str(e.Type) === "AuthenticationFailed" && (!Number.isFinite(at) || at >= since);
}).length;
}
export function createJellyfinAdapter(config: JellyfinConfig): JellyfinAdapter {
const base = String(config.url ?? "").replace(/\/+$/, "");
const insecure = config.insecure === true;
const headers = { "X-Emby-Token": config.apiKey, Authorization: `MediaBrowser Token="${config.apiKey}"` };
async function get(path: string): Promise<unknown> {
const res = await requestJson(`${base}${path}`, { headers, insecure });
if (res.status === 401 || res.status === 403) throw new Error(`Jellyfin did not accept the API key (HTTP ${res.status})`);
if (res.status === 404) throw new Error("Jellyfin has no API at this address — check the address and port (8096)");
if (res.status < 200 || res.status >= 300) throw new Error(`Jellyfin error: HTTP ${res.status}`);
if (res.json === null) throw new Error("Jellyfin answered with something that isn't JSON — is the address its own?");
return res.json;
}
async function read(now: Date = new Date()): Promise<JellyfinRead> {
const info = parseSystemInfo(await get("/System/Info"));
// The rest is worth having but not worth failing for: a Jellyfin that answers about itself and not about its sessions still says it is up.
const soft = async <T>(path: string, parse: (raw: unknown) => T, fallback: T): Promise<T> => {
try {
return parse(await get(path));
} catch {
return fallback;
}
};
const [streams, tasks, countsRaw, failed] = await Promise.all([
soft("/Sessions?ActiveWithinSeconds=300", parseSessions, [] as JellyfinStream[]),
soft("/ScheduledTasks?isHidden=false", parseTasks, [] as JellyfinTask[]),
soft("/Items/Counts", obj, {} as Record<string, unknown>),
soft(`/System/ActivityLog/Entries?startIndex=0&limit=100&minDate=${encodeURIComponent(new Date(now.getTime() - 86_400_000).toISOString())}`, (r) => countFailedLogins(r, now), null as number | null),
]);
return {
...info,
streams,
tasks,
counts: { movies: num(countsRaw.MovieCount), series: num(countsRaw.SeriesCount), episodes: num(countsRaw.EpisodeCount), songs: num(countsRaw.SongCount) },
failedLogins24h: failed,
};
}
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
const start = Date.now();
try {
await get("/System/Info");
return { ok: true, latencyMs: Date.now() - start };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
return withDiagLogging("jellyfin", { ping, read });
}