Repository Public
1import { lanJson } from "../ssrf";2import { redact } from "../secrets";34// Jellyfin connector: reads the libraries of a Jellyfin server you run, with an account of that server. Playback goes5// straight from the browser to Jellyfin (direct file when the browser can read it, Jellyfin's own HLS transcoding otherwise).6/** `server` is how this server reaches Jellyfin; `publicUrl` is how your devices reach it when that differs (reverse proxy, HTTPS). */7export interface JellyfinConfig { server: string; username: string; publicUrl?: string | null }8const base = (c: JellyfinConfig) => c.server.replace(/\/+$/, "");9const pub = (c: JellyfinConfig) => (c.publicUrl || c.server).replace(/\/+$/, "");10// One device identity per process: Jellyfin keeps a single session per device, so the web process and the worker must11// not share one (a login from one would silently revoke the other's token).12const DEVICE = `sp-tv-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;13const CLIENT = `MediaBrowser Client="SP TV", Device="SP TV", DeviceId="${DEVICE}", Version="3.0"`;1415interface Session { token: string; userId: string; at: number; checkedAt: number }16const sessions = new Map<string, Session>();17export async function login(c: JellyfinConfig, pw: string): Promise<Session> {18 const k = `${base(c)}|${c.username}`; const cur = sessions.get(k);19 if (cur && Date.now() - cur.at < 12 * 3600_000) {20 if (Date.now() - cur.checkedAt < 5 * 60_000) return cur;21 // A token can be revoked on the server (restart, sign-out everywhere): check it before handing out an address built with it.22 try { await lanJson(`${base(c)}/Users/Me`, { headers: { authorization: `${CLIENT}, Token="${cur.token}"` }, timeoutMs: 8000 }); cur.checkedAt = Date.now(); return cur; } catch { sessions.delete(k); }23 }24 try {25 const d = await lanJson<{ AccessToken: string; User: { Id: string } }>(`${base(c)}/Users/AuthenticateByName`, { method: "POST", headers: { authorization: CLIENT }, body: { Username: c.username, Pw: pw } });26 const s = { token: d.AccessToken, userId: d.User.Id, at: Date.now(), checkedAt: Date.now() }; sessions.set(k, s); return s;27 } catch (e) { throw new Error(/HTTP 401/.test((e as Error).message) ? "Identifiants refusés par Jellyfin" : redact((e as Error).message, pw)); }28}29export function forget(c: JellyfinConfig) { sessions.delete(`${base(c)}|${c.username}`); }30const get = <T,>(c: JellyfinConfig, s: Session, path: string) => lanJson<T>(`${base(c)}${path}`, { headers: { authorization: `${CLIENT}, Token="${s.token}"` } });3132export interface JfStream { Type: string; Codec?: string; Language?: string; DisplayTitle?: string; IsTextSubtitleStream?: boolean; Index: number; Height?: number; Width?: number }33export interface JfItem {34 Id: string; Name: string; Type: "Movie" | "Series" | "Episode"; OriginalTitle?: string; Overview?: string; ProductionYear?: number; RunTimeTicks?: number; Genres?: string[]; ProviderIds?: { Imdb?: string; Tmdb?: string };35 People?: { Name: string; Type: string }[]; ImageTags?: { Primary?: string }; BackdropImageTags?: string[]; ParentIndexNumber?: number; IndexNumber?: number; PremiereDate?: string;36 MediaSources?: { Id: string; Container?: string; Size?: number; MediaStreams?: JfStream[] }[]; ProductionLocations?: string[];37}38const FIELDS = "Overview,Genres,ProductionYear,RunTimeTicks,MediaSources,ProviderIds,People,OriginalTitle,ProductionLocations";39export async function serverInfo(c: JellyfinConfig): Promise<{ name: string; version: string }> {40 const d = await lanJson<{ ServerName: string; Version: string }>(`${base(c)}/System/Info/Public`); return { name: d.ServerName, version: d.Version };41}42export async function items(c: JellyfinConfig, s: Session, type: "Movie" | "Series"): Promise<JfItem[]> {43 const out: JfItem[] = [];44 for (let start = 0; ; start += 500) {45 const d = await get<{ Items: JfItem[]; TotalRecordCount: number }>(c, s, `/Users/${s.userId}/Items?IncludeItemTypes=${type}&Recursive=true&Fields=${FIELDS}&SortBy=SortName&StartIndex=${start}&Limit=500`);46 out.push(...d.Items); if (out.length >= d.TotalRecordCount || !d.Items.length) break;47 }48 return out;49}50export async function episodes(c: JellyfinConfig, s: Session, seriesId: string): Promise<JfItem[]> {51 return (await get<{ Items: JfItem[] }>(c, s, `/Shows/${seriesId}/Episodes?UserId=${s.userId}&Fields=Overview,MediaSources,RunTimeTicks`)).Items;52}53export const image = (c: JellyfinConfig, id: string, kind: "Primary" | "Backdrop", width: number) => `${pub(c)}/Items/${id}/Images/${kind}?maxWidth=${width}&quality=85`;5455/** Whether a browser can read the original file as is (same rule as the local library). */56export function directPlayable(i: JfItem): boolean {57 const m = i.MediaSources?.[0]; if (!m) return false;58 const v = m.MediaStreams?.find((x) => x.Type === "Video"), a = m.MediaStreams?.find((x) => x.Type === "Audio");59 return /^(mp4|m4v|mov)/.test(m.Container ?? "") && v?.Codec === "h264" && (!a || ["aac", "mp3"].includes(a.Codec ?? ""));60}61// Current servers read « ApiKey » and refuse the legacy « api_key » unless re-enabled; older ones only know the latter. Both are sent.62const key = (s: Session) => `ApiKey=${s.token}&api_key=${s.token}`;63export const directUrl = (c: JellyfinConfig, s: Session, id: string) => `${pub(c)}/Videos/${id}/stream?static=true&${key(s)}`;64export const hlsUrl = (c: JellyfinConfig, s: Session, id: string) =>65 `${pub(c)}/Videos/${id}/master.m3u8?${key(s)}&MediaSourceId=${id}&DeviceId=${DEVICE}&PlaySessionId=${Date.now().toString(36)}&VideoCodec=h264&AudioCodec=aac&MaxAudioChannels=2&TranscodingMaxAudioChannels=2&SegmentContainer=ts&MinSegments=1&BreakOnNonKeyFrames=true&VideoBitrate=6000000&AudioBitrate=192000&SubtitleMethod=Hls`;66