import { httpFetch } from '../platform/native'; export const PRODUCT = 'Kaleido'; export const PLATFORM = 'Windows'; export class PlexError extends Error { constructor( message: string, public status = 0, ) { super(message); } } let clientId = ''; let version = '0.1.0'; let deviceName = 'Windows PC'; /** A stable, random identifier for this installation (not secret). */ export function clientIdentifier(): string { if (clientId) return clientId; clientId = localStorage.getItem('kaleido.clientId') ?? ''; if (!clientId) { clientId = crypto.randomUUID(); localStorage.setItem('kaleido.clientId', clientId); } return clientId; } export function configureClient(opts: { version?: string; deviceName?: string }) { if (opts.version) version = opts.version; if (opts.deviceName) deviceName = opts.deviceName; } export function plexHeaders(token?: string | null): Record { const h: Record = { Accept: 'application/json', 'X-Plex-Product': PRODUCT, 'X-Plex-Version': version, 'X-Plex-Client-Identifier': clientIdentifier(), 'X-Plex-Platform': PLATFORM, 'X-Plex-Platform-Version': '11', 'X-Plex-Device': 'Windows', 'X-Plex-Device-Name': `Kaleido (${deviceName})`, 'X-Plex-Model': 'Desktop', 'X-Plex-Provides': 'player', 'X-Plex-Language': navigator.language || 'en', }; if (token) h['X-Plex-Token'] = token; return h; } /** Query-string equivalents of the identification headers (for media URLs). */ export function plexQuery(token?: string | null): Record { const q: Record = { 'X-Plex-Product': PRODUCT, 'X-Plex-Version': version, 'X-Plex-Client-Identifier': clientIdentifier(), 'X-Plex-Platform': PLATFORM, 'X-Plex-Device': 'Windows', 'X-Plex-Device-Name': `Kaleido (${deviceName})`, }; if (token) q['X-Plex-Token'] = token; return q; } export type Params = Record; export function withParams(url: string, params?: Params): string { if (!params) return url; const u = new URL(url); for (const [k, v] of Object.entries(params)) { if (v === undefined || v === null || v === '') continue; u.searchParams.set(k, typeof v === 'boolean' ? (v ? '1' : '0') : String(v)); } return u.toString(); } export interface RequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; params?: Params; body?: BodyInit | null; headers?: Record; timeout?: number; signal?: AbortSignal; /** Return raw text instead of parsed JSON. */ text?: boolean; } const statusMessage = (status: number) => status === 401 || status === 403 ? 'Plex declined this request. Sign in again or check your access to this server.' : status === 404 ? 'This item is no longer available.' : status === 400 ? 'Plex could not process this request.' : status >= 500 ? `The Plex server reported an error (${status}).` : `Plex could not complete the request (${status}).`; export async function plexRequest(url: string, token: string | null | undefined, opts: RequestOptions = {}): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000); const onAbort = () => controller.abort(); opts.signal?.addEventListener('abort', onAbort); let response: Response; try { response = await httpFetch(withParams(url, opts.params), { method: opts.method ?? 'GET', headers: { ...plexHeaders(token), ...opts.headers }, body: opts.body ?? undefined, signal: controller.signal, }); } catch (e: any) { if (opts.signal?.aborted) throw e; throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0); } finally { clearTimeout(timer); opts.signal?.removeEventListener('abort', onAbort); } if (!response.ok) throw new PlexError(statusMessage(response.status), response.status); const text = await response.text(); if (opts.text) return text as unknown as T; if (!text.trim()) return {} as T; try { return JSON.parse(text); } catch { return text as unknown as T; } } /** A connection to one Plex Media Server. */ export class PlexServer { constructor( public readonly uri: string, public readonly token: string, public readonly machineId: string, public readonly name: string, public readonly owned: boolean, public readonly local: boolean, ) {} url(path: string, params?: Params): string { const base = path.startsWith('http') ? path : `${this.uri.replace(/\/$/, '')}/${path.replace(/^\//, '')}`; return withParams(base, params); } /** URL including the token, for media loaded outside fetch (images, video). */ signed(path: string, params?: Params): string { return this.url(path, { ...params, 'X-Plex-Token': this.token }); } async get(path: string, params?: Params, opts: RequestOptions = {}): Promise { return plexRequest(this.url(path), this.token, { ...opts, params }); } async container(path: string, params?: Params, opts: RequestOptions = {}): Promise { const j = await this.get(path, params, opts); return j?.MediaContainer ?? {}; } async send(method: 'POST' | 'PUT' | 'DELETE', path: string, params?: Params, opts: RequestOptions = {}): Promise { return plexRequest(this.url(path), this.token, { ...opts, method, params }); } /** Photo transcoder URL, sized for the device pixel ratio. */ image(path: string | undefined, width: number, height: number, opts: { blur?: number; quality?: number; format?: 'jpeg' | 'png' } = {}): string { if (!path) return ''; const dpr = Math.min(window.devicePixelRatio || 1, 2); const w = Math.round(width * dpr); const h = Math.round(height * dpr); return this.signed('/photo/:/transcode', { url: path, width: w, height: h, minSize: 1, upscale: 1, quality: opts.quality, blur: opts.blur, format: opts.format ?? 'jpeg', }); } }