Create Kaleido Desktop, a cinematic Plex client for Windows

Tauri 2 shell with a React/TypeScript interface and libmpv playback composed
beneath the web view (DirectComposition on Windows). Shared code with per-OS
platform modules and configs so macOS and Linux can follow.

- Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home
- Home, Movies and TV Shows (Discover, Library, Collections), search, people
- Title pages with logos, ratings, cast, extras, seasons and episodes
- Direct play with Plex conversion fallback, tracks, markers, autoplay
- Metadata editing, artwork, fix match, refresh, analyze and deletion
- Resumable offline downloads
- App settings and Plex server administration with a live dashboard
- Signed updater feed and Forgejo CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-10-30 16:26:37 -07:00
commit 00d72e70f4
121 changed files with 25315 additions and 0 deletions

182
src/plex/account.ts Normal file
View file

@ -0,0 +1,182 @@
import { arr, bool, num, str } from './parse';
import { clientIdentifier, PlexError, plexRequest, PRODUCT } from './client';
import type { HomeUser, PlexUser, ServerConnection, ServerResource } from './types';
const TV = 'https://plex.tv/api/v2';
export interface Pin {
id: number;
code: string;
}
export async function createPin(strong: boolean): Promise<Pin> {
const j = await plexRequest(`${TV}/pins`, null, { method: 'POST', params: { strong } });
return { id: num(j.id), code: str(j.code) };
}
export async function checkPin(pin: Pin): Promise<string | null> {
const j = await plexRequest(`${TV}/pins/${pin.id}`, null);
const token = str(j.authToken);
return token && token !== 'null' ? token : null;
}
/** The browser sign-in page for a strong PIN. */
export function authUrl(pin: Pin): string {
const params = new URLSearchParams({
clientID: clientIdentifier(),
code: pin.code,
'context[device][product]': PRODUCT,
'context[device][platform]': 'Windows',
'context[device][device]': 'Windows',
});
return `https://app.plex.tv/auth#?${params.toString()}`;
}
export async function getUser(token: string): Promise<PlexUser> {
const j = await plexRequest(`${TV}/user`, token);
return {
id: num(j.id),
uuid: str(j.uuid),
username: str(j.username),
title: str(j.title || j.friendlyName || j.username),
email: str(j.email),
thumb: str(j.thumb),
home: bool(j.home),
homeAdmin: bool(j.homeAdmin),
protected: bool(j.protected),
subscription: bool(j.subscription?.active),
};
}
export async function signOut(token: string) {
await plexRequest(`${TV}/users/signout`, token, { method: 'DELETE' }).catch(() => {});
}
export async function getResources(token: string): Promise<ServerResource[]> {
const list = await plexRequest<any[]>(`${TV}/resources`, token, {
params: { includeHttps: 1, includeRelay: 1, includeIPv6: 1 },
});
return arr(list)
.filter((r) => str(r.provides).split(',').includes('server'))
.map((r) => ({
id: str(r.clientIdentifier),
name: str(r.name),
owned: bool(r.owned),
accessToken: str(r.accessToken) || token,
productVersion: str(r.productVersion),
platform: str(r.platform),
presence: bool(r.presence),
publicAddress: str(r.publicAddress),
sourceTitle: str(r.sourceTitle),
httpsRequired: bool(r.httpsRequired),
connections: arr(r.connections).map(
(c): ServerConnection => ({
uri: str(c.uri),
local: bool(c.local),
relay: bool(c.relay),
protocol: str(c.protocol),
address: str(c.address),
port: num(c.port),
IPv6: bool(c.IPv6),
}),
),
}));
}
export async function getHomeUsers(token: string): Promise<HomeUser[]> {
const j = await plexRequest(`${TV}/home/users`, token);
return arr(j.users ?? j).map((u: any) => ({
id: num(u.id),
uuid: str(u.uuid),
title: str(u.title || u.username),
username: str(u.username),
thumb: str(u.thumb),
admin: bool(u.admin),
protected: bool(u.protected),
restricted: bool(u.restricted),
guest: bool(u.guest),
}));
}
/** Switches to a Plex Home user; returns that user's account token. */
export async function switchHomeUser(token: string, uuid: string, pin?: string): Promise<string> {
const j = await plexRequest(`${TV}/home/users/${uuid}/switch`, token, { method: 'POST', params: { pin } });
const t = str(j.authToken);
if (!t) throw new PlexError('Plex did not accept this profile PIN.', 401);
return t;
}
/** Whether a server address is on this network: plex.direct names encode the server's IP. */
export function isLocalAddress(url: string): boolean {
let host = '';
try {
host = new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g, '');
} catch {
return false;
}
const ip = host.endsWith('.plex.direct') ? host.split('.')[0].replace(/-/g, '.') : host;
if (host === 'localhost' || host.endsWith('.local') || (!host.includes('.') && !host.includes(':'))) return true;
if (ip.startsWith('fd') || ip.startsWith('fe80')) return true;
const o = ip.split('.').map(Number);
if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
const [a, b] = o;
return a === 10 || a === 127 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
}
export interface Reachable {
uri: string;
machineId: string;
name: string;
local: boolean;
relay: boolean;
latency: number;
}
async function probe(uri: string, token: string, timeout: number): Promise<Reachable> {
const start = performance.now();
const j = await plexRequest(`${uri.replace(/\/$/, '')}/identity`, token, { timeout });
const machineId = str(j?.MediaContainer?.machineIdentifier);
if (!machineId) throw new PlexError('Not a Plex Media Server');
return { uri, machineId, name: '', local: isLocalAddress(uri), relay: false, latency: performance.now() - start };
}
/**
* Finds the best reachable connection. Local direct connections win, then
* remote direct, then Plex Relay. Each tier is probed concurrently.
*/
export async function connect(resource: ServerResource, preferred?: string): Promise<Reachable> {
const conns = resource.connections.filter((c) => c.uri.startsWith('http'));
const tiers: ServerConnection[][] = [];
if (preferred) {
const p = conns.find((c) => c.uri === preferred);
if (p) tiers.push([p]);
}
tiers.push(
conns.filter((c) => c.local && !c.relay),
conns.filter((c) => !c.local && !c.relay),
conns.filter((c) => c.relay),
);
for (const tier of tiers) {
if (!tier.length) continue;
try {
const winner = await Promise.any(
tier.map((c) =>
probe(c.uri, resource.accessToken, c.relay ? 12000 : 6000).then((r) => ({ ...r, local: c.local, relay: c.relay, name: resource.name })),
),
);
return winner;
} catch {
/* next tier */
}
}
throw new PlexError(`Cannot reach ${resource.name}. Check that the server is online and reachable from this computer.`);
}
/** Validates a manual server address with a token. */
export async function connectManual(uri: string, token: string): Promise<Reachable & { name: string }> {
const base = uri.replace(/\/$/, '');
const j = await plexRequest(`${base}/`, token, { timeout: 8000 });
const mc = j?.MediaContainer;
if (!mc?.machineIdentifier) throw new PlexError('This address is not a Plex Media Server.');
return { uri: base, machineId: str(mc.machineIdentifier), name: str(mc.friendlyName) || 'Plex', local: isLocalAddress(base), relay: false, latency: 0 };
}

361
src/plex/admin.ts Normal file
View file

@ -0,0 +1,361 @@
/** Plex Media Server administration (owner accounts). */
import type { PlexServer } from './client';
import { arr, bool, num, parseItem, parseSection, str } from './parse';
import type { Item, Section } from './types';
export interface ServerSetting {
id: string;
label: string;
summary: string;
type: 'text' | 'bool' | 'int' | 'double' | string;
default: unknown;
value: unknown;
hidden: boolean;
advanced: boolean;
group: string;
options: { value: string; label: string }[] | null;
}
export async function prefs(s: PlexServer): Promise<ServerSetting[]> {
const mc = await s.container('/:/prefs');
return arr(mc.Setting).map((x: any) => ({
id: str(x.id),
label: str(x.label) || str(x.id),
summary: str(x.summary),
type: str(x.type),
default: x.default,
value: x.value,
hidden: bool(x.hidden),
advanced: bool(x.advanced),
group: str(x.group),
options: x.enumValues
? str(x.enumValues)
.split('|')
.map((pair) => {
const i = pair.indexOf(':');
return i < 0 ? { value: pair, label: pair } : { value: pair.slice(0, i), label: pair.slice(i + 1) };
})
: null,
}));
}
export async function setPrefs(s: PlexServer, values: Record<string, string | number | boolean>) {
const params: Record<string, string> = {};
for (const [k, v] of Object.entries(values)) params[k] = typeof v === 'boolean' ? (v ? 'true' : 'false') : String(v);
await s.send('PUT', '/:/prefs', params);
}
export interface Session {
sessionKey: string;
sessionId: string;
item: Item;
user: { title: string; thumb: string };
player: { title: string; product: string; platform: string; device: string; state: string; local: boolean; address: string; secure: boolean };
bandwidth: number;
location: string;
decision: { video: string; audio: string; container: string; transcodeHw: boolean; progress: number; speed: number; throttled: boolean; videoCodec: string; audioCodec: string; reason: string } | null;
viewOffset: number;
}
export async function sessions(s: PlexServer): Promise<Session[]> {
const mc = await s.container('/status/sessions');
return arr(mc.Metadata).map((m: any) => {
const t = m.TranscodeSession;
const sess = m.Session ?? {};
return {
sessionKey: str(m.sessionKey),
sessionId: str(sess.id),
item: parseItem(m),
user: { title: str(m.User?.title), thumb: str(m.User?.thumb) },
player: {
title: str(m.Player?.title),
product: str(m.Player?.product),
platform: str(m.Player?.platform),
device: str(m.Player?.device),
state: str(m.Player?.state),
local: bool(m.Player?.local),
address: str(m.Player?.address),
secure: bool(m.Player?.secure),
},
bandwidth: num(sess.bandwidth),
location: str(sess.location),
viewOffset: num(m.viewOffset),
decision: t
? {
video: str(t.videoDecision),
audio: str(t.audioDecision),
container: str(t.container),
transcodeHw: bool(t.transcodeHwRequested) || bool(t.transcodeHwFullPipeline),
progress: num(t.progress),
speed: num(t.speed),
throttled: bool(t.throttled),
videoCodec: str(t.videoCodec),
audioCodec: str(t.audioCodec),
reason: str(t.transcodeReason ?? ''),
}
: null,
};
});
}
export const terminateSession = (s: PlexServer, sessionId: string, reason: string) => s.get('/status/sessions/terminate', { sessionId, reason });
export interface HistoryEntry {
id: string;
title: string;
subtitle: string;
thumb: string;
viewedAt: number;
accountId: number;
deviceId: number;
type: string;
}
export async function history(s: PlexServer, size = 30): Promise<HistoryEntry[]> {
const mc = await s.container('/status/sessions/history/all', { sort: 'viewedAt:desc', 'X-Plex-Container-Size': size, 'X-Plex-Container-Start': 0 });
return arr(mc.Metadata).map((m: any) => ({
id: str(m.historyKey ?? m.ratingKey),
title: str(m.grandparentTitle || m.title),
subtitle: m.type === 'episode' ? `S${num(m.parentIndex)} · E${num(m.index)} ${str(m.title)}` : str(m.year ?? ''),
thumb: str(m.grandparentThumb || m.thumb),
viewedAt: num(m.viewedAt),
accountId: num(m.accountID),
deviceId: num(m.deviceID),
type: str(m.type),
}));
}
export async function accounts(s: PlexServer): Promise<Record<number, string>> {
const mc = await s.container('/accounts');
return Object.fromEntries(arr(mc.Account).map((a: any) => [num(a.id), str(a.name) || 'Owner']));
}
export interface Device {
id: number;
name: string;
platform: string;
clientIdentifier: string;
createdAt: number;
}
export async function devices(s: PlexServer): Promise<Device[]> {
const mc = await s.container('/devices');
return arr(mc.Device).map((d: any) => ({ id: num(d.id), name: str(d.name), platform: str(d.platform), clientIdentifier: str(d.clientIdentifier), createdAt: num(d.createdAt) }));
}
export const removeDevice = (s: PlexServer, id: number) => s.send('DELETE', `/devices/${id}`);
export interface BandwidthPoint {
at: number;
lan: number;
wan: number;
}
/** Bandwidth samples grouped by time (bytes per sample interval). */
export async function bandwidth(s: PlexServer, timespan = 6): Promise<{ points: BandwidthPoint[]; devices: Record<number, string> }> {
const mc = await s.container('/statistics/bandwidth', { timespan });
const byAt = new Map<number, BandwidthPoint>();
for (const b of arr(mc.StatisticsBandwidth)) {
const at = num(b.at);
const p = byAt.get(at) ?? { at, lan: 0, wan: 0 };
if (bool(b.lan)) p.lan += num(b.bytes);
else p.wan += num(b.bytes);
byAt.set(at, p);
}
return {
points: [...byAt.values()].sort((a, b) => a.at - b.at),
devices: Object.fromEntries(arr(mc.Device).map((d: any) => [num(d.id), str(d.name)])),
};
}
export interface ResourcePoint {
at: number;
hostCpu: number;
processCpu: number;
hostMemory: number;
processMemory: number;
}
export async function resources(s: PlexServer, timespan = 6): Promise<ResourcePoint[]> {
const mc = await s.container('/statistics/resources', { timespan });
return arr(mc.StatisticsResources)
.map((r: any) => ({
at: num(r.at),
hostCpu: num(r.hostCpuUtilization),
processCpu: num(r.processCpuUtilization),
hostMemory: num(r.hostMemoryUtilization),
processMemory: num(r.processMemoryUtilization),
}))
.sort((a, b) => a.at - b.at);
}
export interface Activity {
uuid: string;
type: string;
title: string;
subtitle: string;
progress: number;
cancellable: boolean;
}
export async function activities(s: PlexServer): Promise<Activity[]> {
const mc = await s.container('/activities');
return arr(mc.Activity).map((a: any) => ({
uuid: str(a.uuid),
type: str(a.type),
title: str(a.title),
subtitle: str(a.subtitle),
progress: num(a.progress),
cancellable: bool(a.cancellable),
}));
}
export const cancelActivity = (s: PlexServer, uuid: string) => s.send('DELETE', `/activities/${uuid}`);
export interface ButlerTask {
name: string;
title: string;
description: string;
interval: number;
enabled: boolean;
}
export async function butlerTasks(s: PlexServer): Promise<ButlerTask[]> {
const j = await s.get('/butler');
return arr(j?.ButlerTasks?.ButlerTask).map((t: any) => ({
name: str(t.name),
title: str(t.title) || str(t.name).replace(/^ButlerTask/, '').replace(/([a-z])([A-Z])/g, '$1 $2'),
description: str(t.description),
interval: num(t.interval),
enabled: bool(t.enabled),
}));
}
export const runButlerTask = (s: PlexServer, name: string) => s.send('POST', `/butler/${name}`);
export const stopButlerTasks = (s: PlexServer) => s.send('DELETE', '/butler');
export interface RemoteAccess {
mappingState: string;
mappingError: string;
signInState: string;
publicAddress: string;
publicPort: number;
privateAddress: string;
privatePort: number;
reachabilityPending: boolean;
}
export async function remoteAccess(s: PlexServer): Promise<RemoteAccess> {
const j = await s.get('/myplex/account');
const m = j?.MyPlex ?? {};
return {
mappingState: str(m.mappingState),
mappingError: str(m.mappingError),
signInState: str(m.signInState),
publicAddress: str(m.publicAddress),
publicPort: num(m.publicPort),
privateAddress: str(m.privateAddress),
privatePort: num(m.privatePort),
reachabilityPending: bool(m.reachabilityPending),
};
}
export const refreshReachability = (s: PlexServer) => s.send('PUT', '/myplex/refreshReachability');
// —— Libraries ——————————————————————————————————————————————————————
export const scanLibrary = (s: PlexServer, id: string, force = false) => s.get(`/library/sections/${id}/refresh`, force ? { force: 1 } : undefined);
export const cancelScan = (s: PlexServer, id: string) => s.send('DELETE', `/library/sections/${id}/refresh`);
export const emptyTrash = (s: PlexServer, id: string) => s.send('PUT', `/library/sections/${id}/emptyTrash`);
export const analyzeLibrary = (s: PlexServer, id: string) => s.send('PUT', `/library/sections/${id}/analyze`);
export const deleteLibrary = (s: PlexServer, id: string) => s.send('DELETE', `/library/sections/${id}`);
export const cleanBundles = (s: PlexServer) => s.send('PUT', '/library/clean/bundles');
export const optimizeDatabase = (s: PlexServer) => s.send('PUT', '/library/optimize', { async: 1 });
export const scanAll = (s: PlexServer) => s.get('/library/sections/all/refresh');
export async function librarySize(s: PlexServer, sec: Section): Promise<number> {
const mc = await s.container(`/library/sections/${sec.id}/all`, { 'X-Plex-Container-Size': 0, type: sec.type === 'show' ? 2 : sec.type === 'artist' ? 8 : undefined });
return num(mc.totalSize ?? mc.size);
}
export interface Agent {
identifier: string;
name: string;
}
export async function agents(s: PlexServer, mediaType: number): Promise<Agent[]> {
const mc = await s.container('/system/agents', { mediaType });
return arr(mc.Agent).map((a: any) => ({ identifier: str(a.identifier), name: str(a.name ?? a.title) }));
}
export async function scanners(s: PlexServer, type: number): Promise<string[]> {
const mc = await s.container(`/system/scanners/${type}`);
return arr(mc.Scanner).map((x: any) => str(x.name));
}
export interface BrowseEntry {
key: string;
path: string;
title: string;
}
/** The server's file system, for choosing library folders. */
export async function browse(s: PlexServer, key?: string): Promise<BrowseEntry[]> {
const mc = await s.container(key ?? '/services/browse', { includeFiles: 0 });
return arr(mc.Path).map((p: any) => ({ key: str(p.key), path: str(p.path), title: str(p.title) }));
}
export async function createLibrary(s: PlexServer, opts: { name: string; type: 'movie' | 'show'; agent: string; scanner: string; language: string; locations: string[] }) {
const u = new URL(s.url('/library/sections'));
u.searchParams.set('name', opts.name);
u.searchParams.set('type', opts.type);
u.searchParams.set('agent', opts.agent);
u.searchParams.set('scanner', opts.scanner);
u.searchParams.set('language', opts.language);
for (const l of opts.locations) u.searchParams.append('location', l);
await s.send('POST', u.toString());
}
export async function updateLibrary(s: PlexServer, sec: Section, opts: { name: string; locations: string[] }) {
const u = new URL(s.url(`/library/sections/${sec.id}`));
u.searchParams.set('name', opts.name);
u.searchParams.set('agent', sec.agent);
u.searchParams.set('language', sec.language);
for (const l of opts.locations) u.searchParams.append('location', l);
await s.send('PUT', u.toString());
}
export async function sectionDetail(s: PlexServer, id: string): Promise<Section> {
const mc = await s.container('/library/sections');
const d = arr(mc.Directory).find((x: any) => str(x.key) === id);
return parseSection(d ?? {});
}
// —— Updates & diagnostics ————————————————————————————————————————————
export interface UpdateStatus {
canInstall: boolean;
checkedAt: number;
status: number;
version: string;
added: string;
fixed: string;
state: string;
}
export async function updateStatus(s: PlexServer): Promise<UpdateStatus | null> {
const mc = await s.container('/updater/status');
const r = arr(mc.Release)[0];
return {
canInstall: bool(mc.canInstall),
checkedAt: num(mc.checkedAt),
status: num(mc.status),
version: str(r?.version),
added: str(r?.added),
fixed: str(r?.fixed),
state: str(r?.state),
};
}
export const checkForUpdates = (s: PlexServer) => s.send('PUT', '/updater/check', { download: 1 });
export const applyUpdate = (s: PlexServer) => s.send('PUT', '/updater/apply');

348
src/plex/api.ts Normal file
View file

@ -0,0 +1,348 @@
/** Library browsing and title operations against one server. */
import type { PlexServer, Params } from './client';
import { arr, num, parseHub, parseItem, parseSection, str } from './parse';
import type { FilterOption, Hub, Item, Page, Section } from './types';
const items = (mc: any) => arr(mc.Metadata).map(parseItem);
export async function sections(s: PlexServer): Promise<Section[]> {
const mc = await s.container('/library/sections');
return arr(mc.Directory).map(parseSection);
}
export async function serverInfo(s: PlexServer) {
return s.container('/');
}
const VIDEO_TYPES = new Set(['movie', 'show', 'season', 'episode', 'collection', 'clip']);
export async function homeHubs(s: PlexServer): Promise<Hub[]> {
const mc = await s.container('/hubs', { count: 20, includeExternalMetadata: 1, includeLibraryPlaylists: 0 });
return arr(mc.Hub)
.map(parseHub)
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
}
export async function sectionHubs(s: PlexServer, sectionId: string): Promise<Hub[]> {
const mc = await s.container(`/hubs/sections/${sectionId}`, { count: 20, includeExternalMetadata: 1 });
return arr(mc.Hub)
.map(parseHub)
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
}
/** Continue Watching across libraries (Plex's own hub honors removals). */
export async function continueWatching(s: PlexServer, sectionId?: string): Promise<Item[]> {
const path = sectionId ? `/hubs/sections/${sectionId}/continueWatching/items` : '/hubs/continueWatching/items';
try {
const mc = await s.container(path, { 'X-Plex-Container-Size': 40, includeExternalMetadata: 1 });
return items(mc);
} catch {
const mc = await s.container('/library/onDeck', { 'X-Plex-Container-Size': 40 });
return items(mc).filter((i) => !sectionId || i.librarySectionId === sectionId);
}
}
export async function hubItems(s: PlexServer, key: string, start = 0, size = 60): Promise<Page<Item>> {
const mc = await s.container(key, { 'X-Plex-Container-Start': start, 'X-Plex-Container-Size': size, includeExternalMetadata: 1 });
const list = items(mc).length ? items(mc) : arr(mc.Hub).flatMap((h: any) => arr(h.Metadata).map(parseItem));
return { items: list, total: num(mc.totalSize ?? mc.size), offset: start };
}
/** Metadata types used by library queries. */
export const TYPE_ID: Record<string, number> = { movie: 1, show: 2, season: 3, episode: 4, collection: 18 };
export async function libraryPage(
s: PlexServer,
sectionId: string,
opts: { type?: number; sort?: string; filters?: Record<string, string>; title?: string; start: number; size: number },
): Promise<Page<Item>> {
const params: Params = {
'X-Plex-Container-Start': opts.start,
'X-Plex-Container-Size': opts.size,
type: opts.type,
sort: opts.sort,
includeGuids: 0,
...opts.filters,
};
if (opts.title) params['title'] = opts.title;
const mc = await s.container(`/library/sections/${sectionId}/all`, params);
return { items: items(mc), total: num(mc.totalSize ?? mc.size), offset: opts.start };
}
export interface LibraryMeta {
filters: { filter: string; type: string; title: string; key: string }[];
sorts: { key: string; title: string; defaultDirection: string }[];
}
export async function libraryMeta(s: PlexServer, sectionId: string, type: number): Promise<LibraryMeta> {
const mc = await s.container(`/library/sections/${sectionId}/all`, { includeMeta: 1, 'X-Plex-Container-Size': 0, type });
const name = Object.entries(TYPE_ID).find(([, v]) => v === type)?.[0];
const t = arr(mc.Meta?.Type).find((x: any) => x.type === name) ?? arr(mc.Meta?.Type)[0];
return {
filters: arr(t?.Filter).map((f: any) => ({ filter: str(f.filter), type: str(f.filterType), title: str(f.title), key: str(f.key) })),
sorts: arr(t?.Sort).map((x: any) => ({ key: str(x.key), title: str(x.title), defaultDirection: str(x.defaultDirection) || 'asc' })),
};
}
export async function filterOptions(s: PlexServer, path: string, type?: number): Promise<FilterOption[]> {
const mc = await s.container(path, { type });
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title) }));
}
export async function firstCharacters(s: PlexServer, sectionId: string, params: Params): Promise<{ key: string; title: string; size: number }[]> {
const mc = await s.container(`/library/sections/${sectionId}/firstCharacter`, params);
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title), size: num(d.size) }));
}
export async function collections(s: PlexServer, sectionId: string): Promise<Item[]> {
const mc = await s.container(`/library/sections/${sectionId}/collections`, { includeCollections: 1, sort: 'titleSort:asc' });
return items(mc);
}
export async function metadata(s: PlexServer, id: string): Promise<Item> {
const mc = await s.container(`/library/metadata/${id}`, {
includeMarkers: 1,
includeChapters: 1,
includeExtras: 1,
includeConcerts: 1,
includeOnDeck: 1,
includeReviews: 0,
includePreferences: 1,
includeExternalMedia: 0,
checkFiles: 1,
asyncAugmentMetadata: 0,
});
const first = arr(mc.Metadata)[0];
if (!first) throw new Error('This title is unavailable.');
const item = parseItem(first);
item.raw.__librarySectionID = mc.librarySectionID;
if (!item.librarySectionId) item.librarySectionId = str(mc.librarySectionID);
return item;
}
export async function children(s: PlexServer, id: string): Promise<Item[]> {
const mc = await s.container(`/library/metadata/${id}/children`, { includeMarkers: 0, excludeAllLeaves: 1 });
return items(mc);
}
export async function allLeaves(s: PlexServer, id: string): Promise<Item[]> {
const mc = await s.container(`/library/metadata/${id}/allLeaves`);
return items(mc);
}
/** The show's next episode (Plex's OnDeck), if any. */
export async function onDeckFor(_s: PlexServer, item: Item): Promise<Item | null> {
const od = arr(item.raw?.OnDeck?.Metadata)[0];
if (od) return parseItem(od);
return null;
}
export async function related(s: PlexServer, id: string): Promise<Hub[]> {
const mc = await s.container(`/library/metadata/${id}/related`, { includeExternalMetadata: 1, count: 20 });
return arr(mc.Hub).map(parseHub).filter((h) => h.items.length);
}
export async function collectionItems(s: PlexServer, id: string): Promise<Item[]> {
const mc = await s.container(`/library/collections/${id}/children`);
return items(mc);
}
/** Titles featuring a person, across the server's movie and TV libraries. */
export async function personTitles(s: PlexServer, personId: string, libs: Section[]): Promise<Item[]> {
const video = libs.filter((l) => l.type === 'movie' || l.type === 'show');
const results = await Promise.all(
video.map(async (l) => {
const out: Item[] = [];
let start = 0;
for (let guard = 0; guard < 10; guard++) {
const mc = await s.container(`/library/sections/${l.id}/all`, {
actor: personId,
sort: 'originallyAvailableAt:desc',
'X-Plex-Container-Start': start,
'X-Plex-Container-Size': 100,
});
const batch = items(mc);
out.push(...batch);
start += batch.length;
if (!batch.length || start >= num(mc.totalSize ?? mc.size)) break;
}
// Directors and writers too, when the person has no acting credits here.
if (!out.length) {
for (const tag of ['director', 'writer']) {
const mc = await s.container(`/library/sections/${l.id}/all`, { [tag]: personId, sort: 'originallyAvailableAt:desc' });
out.push(...items(mc));
}
}
return out;
}),
);
const seen = new Set<string>();
return results.flat().filter((i) => (seen.has(i.id) ? false : (seen.add(i.id), true)));
}
export async function person(s: PlexServer, id: string): Promise<any> {
try {
const mc = await s.container(`/library/people/${id}`);
return arr(mc.Directory)[0] ?? arr(mc.Metadata)[0] ?? null;
} catch {
return null;
}
}
export interface SearchResult {
hubs: Hub[];
people: { id: string; tag: string; thumb: string }[];
}
export async function search(s: PlexServer, query: string, sectionId?: string): Promise<SearchResult> {
const mc = await s.container('/hubs/search', { query, limit: 30, includeCollections: 1, sectionId, includeExternalMedia: 0 });
const hubs = arr(mc.Hub);
const people = hubs
.filter((h: any) => h.type === 'actor' || h.type === 'director')
.flatMap((h: any) => arr(h.Directory ?? h.Metadata))
.map((p: any) => ({ id: str(p.id ?? p.ratingKey), tag: str(p.tag ?? p.title), thumb: str(p.thumb) }))
.filter((p: any) => p.id && p.tag);
const seenPeople = new Set<string>();
return {
hubs: hubs
.map(parseHub)
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type)),
people: people.filter((p) => (seenPeople.has(p.id) ? false : (seenPeople.add(p.id), true))),
};
}
// —— Watch state ————————————————————————————————————————————————
export async function setWatched(s: PlexServer, id: string, watched: boolean) {
await s.get(watched ? '/:/scrobble' : '/:/unscrobble', { key: id, identifier: 'com.plexapp.plugins.library' });
}
export async function removeFromContinueWatching(s: PlexServer, id: string) {
await s.send('PUT', '/actions/removeFromContinueWatching', { ratingKey: id });
}
export async function rate(s: PlexServer, id: string, rating: number) {
await s.send('PUT', '/:/rate', { key: id, identifier: 'com.plexapp.plugins.library', rating: rating < 0 ? -1 : rating });
}
export async function selectStreams(s: PlexServer, partId: string, sel: { audioStreamID?: string; subtitleStreamID?: string }) {
await s.send('PUT', `/library/parts/${partId}`, { allParts: 1, ...sel });
}
// —— Library management ——————————————————————————————————————————
export const refreshMetadata = (s: PlexServer, id: string, force = true) => s.send('PUT', `/library/metadata/${id}/refresh`, { force: force ? 1 : 0 });
export const analyze = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/analyze`);
export const unmatch = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/unmatch`);
export const splitApart = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/split`);
export const merge = (s: PlexServer, id: string, others: string[]) => s.send('PUT', `/library/metadata/${id}/merge`, { ids: others.join(',') });
export const deleteItem = (s: PlexServer, id: string) => s.send('DELETE', `/library/metadata/${id}`);
export const deleteMedia = (s: PlexServer, id: string, mediaId: string) => s.send('DELETE', `/library/metadata/${id}/media/${mediaId}`);
export interface MatchCandidate {
guid: string;
name: string;
year: number;
score: number;
thumb: string;
summary: string;
matched: boolean;
}
export async function matches(s: PlexServer, id: string, opts: { title?: string; year?: string; agent?: string; language?: string }): Promise<MatchCandidate[]> {
const mc = await s.container(`/library/metadata/${id}/matches`, {
manual: 1,
title: opts.title,
year: opts.year,
agent: opts.agent,
language: opts.language,
});
return arr(mc.SearchResult).map((r: any) => ({
guid: str(r.guid),
name: str(r.name),
year: num(r.year),
score: num(r.score),
thumb: str(r.thumb),
summary: str(r.summary),
matched: r.matched === 1 || r.matched === true || r.matched === '1',
}));
}
export const applyMatch = (s: PlexServer, id: string, guid: string, name: string, year?: number) =>
s.send('PUT', `/library/metadata/${id}/match`, { guid, name, year });
export async function artworkOptions(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos'): Promise<{ key: string; thumb: string; selected: boolean; provider: string }[]> {
const mc = await s.container(`/library/metadata/${id}/${kind}`);
return arr(mc.Metadata).map((m: any) => ({ key: str(m.key), thumb: str(m.thumb || m.key), selected: m.selected === true || m.selected === 1, provider: str(m.provider) }));
}
export const selectArtwork = (s: PlexServer, id: string, kind: 'poster' | 'art' | 'clearLogo', url: string) =>
s.send('PUT', `/library/metadata/${id}/${kind}`, { url });
export async function uploadArtwork(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos', data: Blob) {
await s.send('POST', `/library/metadata/${id}/${kind}`, undefined, { body: data });
}
/**
* Edits metadata through the section `all` endpoint, as Plex Web does. Field
* values are locked so later refreshes keep them.
*/
export async function editMetadata(
s: PlexServer,
item: Item,
fields: Record<string, string>,
tagFields: Record<string, { add: string[]; remove: string[] }> = {},
locks: Record<string, boolean> = {},
) {
const type = TYPE_ID[item.type] ?? 1;
const params: Params = { type, id: item.id, includeExternalMedia: 1 };
for (const [k, v] of Object.entries(fields)) {
params[`${k}.value`] = v;
params[`${k}.locked`] = locks[k] === false ? 0 : 1;
}
for (const [tag, change] of Object.entries(tagFields)) {
change.add.forEach((v, i) => (params[`${tag}[${i}].tag.tag`] = v));
if (change.remove.length) params[`${tag}[].tag.tag-`] = change.remove.join(',');
params[`${tag}.locked`] = locks[tag] === false ? 0 : 1;
}
for (const [k, locked] of Object.entries(locks)) {
if (!(k in fields) && !(k in tagFields)) params[`${k}.locked`] = locked ? 1 : 0;
}
const section = item.librarySectionId || str(item.raw?.__librarySectionID);
await s.send('PUT', `/library/sections/${section}/all`, params);
}
/** Collections: create, add, remove. */
export async function addToCollection(s: PlexServer, item: Item, collection: string) {
await editMetadata(s, item, {}, { collection: { add: [collection], remove: [] } });
}
export async function removeFromCollection(s: PlexServer, collectionId: string, itemId: string) {
await s.send('DELETE', `/library/collections/${collectionId}/items/${itemId}`);
}
export async function playlists(s: PlexServer): Promise<Item[]> {
const mc = await s.container('/playlists', { playlistType: 'video', smart: 0 });
return items(mc);
}
export async function addToPlaylist(s: PlexServer, playlistId: string, machineId: string, itemId: string) {
await s.send('PUT', `/playlists/${playlistId}/items`, { uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}` });
}
export async function createPlaylist(s: PlexServer, title: string, machineId: string, itemId: string) {
await s.send('POST', '/playlists', {
type: 'video',
title,
smart: 0,
uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}`,
});
}
/** Library change detection: small response; compared every few seconds. */
export async function libraryRevision(s: PlexServer): Promise<string> {
const mc = await s.container('/library/sections');
return arr(mc.Directory)
.map((d: any) => [d.key, d.contentChangedAt, d.scannedAt, d.updatedAt].join(':'))
.join('|');
}

183
src/plex/client.ts Normal file
View file

@ -0,0 +1,183 @@
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<string, string> {
const h: Record<string, string> = {
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<string, string> {
const q: Record<string, string> = {
'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<string, string | number | boolean | undefined | null>;
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<string, string>;
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<T = any>(url: string, token: string | null | undefined, opts: RequestOptions = {}): Promise<T> {
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<T = any>(path: string, params?: Params, opts: RequestOptions = {}): Promise<T> {
return plexRequest<T>(this.url(path), this.token, { ...opts, params });
}
async container(path: string, params?: Params, opts: RequestOptions = {}): Promise<any> {
const j = await this.get(path, params, opts);
return j?.MediaContainer ?? {};
}
async send(method: 'POST' | 'PUT' | 'DELETE', path: string, params?: Params, opts: RequestOptions = {}): Promise<any> {
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',
});
}
}

248
src/plex/parse.ts Normal file
View file

@ -0,0 +1,248 @@
import type { AudienceScore, Chapter, Hub, Item, Marker, Media, Part, Role, Section, Stream, Tag } from './types';
const arr = (v: any): any[] => (Array.isArray(v) ? v : v ? [v] : []);
const str = (v: any): string => (v === undefined || v === null ? '' : String(v));
const num = (v: any): number => {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
};
const bool = (v: any): boolean => v === true || v === 1 || v === '1' || v === 'true';
const tags = (v: any): Tag[] =>
arr(v).map((t) => ({ id: str(t.id), tag: str(t.tag), filter: str(t.filter) })).filter((t) => t.tag);
export function parseStream(s: any): Stream {
return {
id: str(s.id),
streamType: num(s.streamType),
codec: str(s.codec),
index: s.index === undefined ? -1 : num(s.index),
language: str(s.language),
languageCode: str(s.languageCode ?? s.languageTag),
displayTitle: str(s.displayTitle ?? s.title ?? s.language),
extendedDisplayTitle: str(s.extendedDisplayTitle ?? s.displayTitle),
title: str(s.title),
selected: bool(s.selected),
default: bool(s.default),
forced: bool(s.forced),
key: str(s.key),
channels: num(s.channels),
audioChannelLayout: str(s.audioChannelLayout),
bitrate: num(s.bitrate),
width: num(s.width),
height: num(s.height),
frameRate: num(s.frameRate),
profile: str(s.profile),
colorTrc: str(s.colorTrc),
colorPrimaries: str(s.colorPrimaries),
bitDepth: num(s.bitDepth),
doviPresent: bool(s.DOVIPresent),
hearingImpaired: bool(s.hearingImpaired),
samplingRate: num(s.samplingRate),
};
}
function parsePart(p: any): Part {
return {
id: str(p.id),
key: str(p.key),
file: str(p.file),
size: num(p.size),
duration: num(p.duration),
container: str(p.container),
indexes: str(p.indexes),
streams: arr(p.Stream).map(parseStream),
accessible: p.accessible === undefined ? true : bool(p.accessible),
exists: p.exists === undefined ? true : bool(p.exists),
};
}
export function dynamicRange(video?: Stream): string {
if (!video) return '';
if (video.doviPresent) return 'Dolby Vision';
if (video.colorTrc === 'smpte2084') return 'HDR10';
if (video.colorTrc === 'arib-std-b67') return 'HLG';
return '';
}
function parseMedia(m: any): Media {
const parts = arr(m.Part).map(parsePart);
const streams = parts.flatMap((p) => p.streams);
const video = streams.find((s) => s.streamType === 1);
const audio = streams.filter((s) => s.streamType === 2);
return {
id: str(m.id),
container: str(m.container),
videoCodec: str(m.videoCodec),
audioCodec: str(m.audioCodec),
videoResolution: str(m.videoResolution),
width: num(m.width),
height: num(m.height),
bitrate: num(m.bitrate),
duration: num(m.duration),
audioChannels: num(m.audioChannels),
videoProfile: str(m.videoProfile),
videoFrameRate: str(m.videoFrameRate),
aspectRatio: num(m.aspectRatio),
optimizedForStreaming: bool(m.optimizedForStreaming),
title: str(m.title),
parts,
dynamicRange: dynamicRange(video) || (str(m.videoDynamicRange ?? '') === 'HDR' ? 'HDR10' : ''),
atmos: audio.some((s) => /atmos/i.test(s.displayTitle + s.extendedDisplayTitle + s.title)),
};
}
/** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */
export function parseScores(j: any): AudienceScore[] {
const out: AudienceScore[] = [];
const add = (image: string, value: number, kind: 'audience' | 'critic') => {
if (!Number.isFinite(value) || value < 0 || value > 10 || !image) return;
let source: AudienceScore['source'] | null = null;
if (image.startsWith('rottentomatoes://')) source = 'Rotten Tomatoes';
else if (image.startsWith('imdb://')) source = 'IMDb';
else if (image.startsWith('themoviedb://')) source = 'TMDB';
else if (image.startsWith('thetvdb://') || image.startsWith('tvdb://')) source = 'TVDB';
if (!source || out.some((s) => s.source === source && s.kind === kind)) return;
out.push({ source, value, kind, image });
};
for (const r of arr(j.Rating)) add(str(r.image), num(r.value), r.type === 'critic' ? 'critic' : 'audience');
if (j.audienceRatingImage) add(str(j.audienceRatingImage), num(j.audienceRating), 'audience');
if (j.ratingImage) add(str(j.ratingImage), num(j.rating), 'critic');
return out;
}
function parseUltraBlur(j: any): Item['ultraBlur'] {
const u = arr(j.UltraBlurColors)[0];
if (!u?.topLeft) return null;
return { topLeft: str(u.topLeft), topRight: str(u.topRight), bottomRight: str(u.bottomRight), bottomLeft: str(u.bottomLeft) };
}
export function parseItem(j: any): Item {
const images = arr(j.Image);
const image = (type: string) => str(images.find((i) => i.type === type)?.url);
const roles: Role[] = arr(j.Role)
.map((r) => ({
id: str(r.id) || str(r.filter).replace(/^actor=/, ''),
tag: str(r.tag),
filter: str(r.filter),
role: str(r.role),
thumb: str(r.thumb),
}))
.filter((r) => r.tag);
const type = str(j.type);
return {
id: str(j.ratingKey ?? j.key),
key: str(j.key),
guid: str(j.guid),
guids: arr(j.Guid).map((g) => str(g.id)),
type,
subtype: str(j.subtype),
title: str(j.title),
titleSort: str(j.titleSort),
originalTitle: str(j.originalTitle),
summary: str(j.summary),
tagline: str(j.tagline),
year: num(j.year ?? j.parentYear),
originallyAvailableAt: str(j.originallyAvailableAt),
duration: num(j.duration),
viewOffset: num(j.viewOffset),
viewCount: num(j.viewCount),
lastViewedAt: num(j.lastViewedAt),
addedAt: num(j.addedAt),
updatedAt: num(j.updatedAt),
thumb: str(j.thumb),
art: str(j.art ?? j.grandparentArt ?? j.parentArt),
logo: image('clearLogo'),
theme: str(j.theme ?? j.parentTheme ?? j.grandparentTheme),
contentRating: str(j.contentRating),
studio: str(j.studio),
parentId: str(j.parentRatingKey),
parentKey: str(j.parentKey),
parentTitle: str(j.parentTitle),
parentIndex: num(j.parentIndex),
parentThumb: str(j.parentThumb),
grandparentId: str(j.grandparentRatingKey),
grandparentKey: str(j.grandparentKey),
grandparentTitle: str(j.grandparentTitle),
grandparentThumb: str(j.grandparentThumb),
grandparentArt: str(j.grandparentArt),
index: num(j.index),
leafCount: num(j.leafCount),
viewedLeafCount: num(j.viewedLeafCount),
childCount: num(j.childCount),
genres: tags(j.Genre),
directors: tags(j.Director),
writers: tags(j.Writer),
producers: tags(j.Producer),
countries: tags(j.Country),
labels: tags(j.Label),
collections: tags(j.Collection),
roles,
scores: parseScores(j),
userRating: num(j.userRating),
media: arr(j.Media).map(parseMedia),
markers: arr(j.Marker).map(
(m): Marker => ({
id: str(m.id),
type: str(m.type),
start: num(m.startTimeOffset),
end: num(m.endTimeOffset),
final: bool(m.final),
}),
),
chapters: arr(j.Chapter).map(
(c, i): Chapter => ({
index: num(c.index) || i + 1,
title: str(c.tag ?? c.title) || `Chapter ${i + 1}`,
start: num(c.startTimeOffset),
end: num(c.endTimeOffset),
thumb: str(c.thumb),
}),
),
extras: arr(j.Extras?.Metadata).map(parseItem),
librarySectionId: str(j.librarySectionID),
librarySectionTitle: str(j.librarySectionTitle),
librarySectionKey: str(j.librarySectionKey),
smart: bool(j.smart),
editionTitle: str(j.editionTitle),
skipChildren: bool(j.skipChildren),
ultraBlur: parseUltraBlur(j),
raw: j,
};
}
export function parseHub(h: any): Hub {
return {
id: str(h.hubIdentifier ?? h.key ?? h.title),
key: str(h.key),
title: str(h.title),
type: str(h.type),
context: str(h.context),
size: num(h.size),
more: bool(h.more),
style: str(h.style),
items: arr(h.Metadata).map(parseItem),
};
}
export function parseSection(d: any): Section {
return {
id: str(d.key),
key: str(d.key),
title: str(d.title),
type: str(d.type),
agent: str(d.agent),
scanner: str(d.scanner),
language: str(d.language),
thumb: str(d.thumb),
art: str(d.art),
locations: arr(d.Location).map((l) => ({ id: str(l.id), path: str(l.path) })),
scannedAt: num(d.scannedAt),
updatedAt: num(d.updatedAt),
contentChangedAt: num(d.contentChangedAt),
refreshing: bool(d.refreshing),
hidden: num(d.hidden) > 0,
};
}
export { arr, str, num, bool };

109
src/plex/playback.ts Normal file
View file

@ -0,0 +1,109 @@
/** Delivery decisions, stream URLs and progress reporting for playback. */
import { plexQuery, type PlexServer } from './client';
import type { Item, Media, Part } from './types';
import { QUALITY_PROFILE, type Quality } from '../app/settings';
export interface Delivery {
url: string;
mode: 'direct' | 'transcode' | 'local';
/** Plex transcode session; stopped when playback ends. */
session?: string;
label: string;
/** Media timestamps are absolute (Plex HLS); don't rebase to zero. */
absoluteTime: boolean;
}
/** mpv EDL joins multi-part files (CD1/CD2) into one timeline. */
function edl(urls: string[]): string {
return 'edl://' + urls.map((u) => `%${new TextEncoder().encode(u).length}%${u}`).join(';');
}
export function directUrl(server: PlexServer, media: Media): string {
const urls = media.parts.map((p) => server.signed(p.key, plexQuery()));
return urls.length > 1 ? edl(urls) : urls[0];
}
export function transcodeUrl(
server: PlexServer,
item: Item,
opts: { mediaIndex: number; quality: Exclude<Quality, 'original'> | 'remux'; offsetMs: number; session: string; local: boolean; audioStreamID?: string; subtitleStreamID?: string },
): string {
const media = item.media[opts.mediaIndex];
const profile = opts.quality === 'remux' ? null : QUALITY_PROFILE[opts.quality];
const extra = [
'add-transcode-target(type=videoProfile&context=streaming&protocol=hls&container=mpegts&videoCodec=h264,hevc&audioCodec=aac,ac3,eac3,mp3,opus)',
'add-limitation(scope=videoCodec&scopeName=hevc&type=upperBound&name=video.bitDepth&value=10)',
].join('+');
return server.signed('/video/:/transcode/universal/start.m3u8', {
...plexQuery(),
path: `/library/metadata/${item.id}`,
mediaIndex: opts.mediaIndex,
partIndex: 0,
protocol: 'hls',
session: opts.session,
offset: (opts.offsetMs / 1000).toFixed(1),
fastSeek: 1,
directPlay: 0,
directStream: profile ? 1 : 1,
directStreamAudio: 1,
copyts: 1,
hasMDE: 1,
mediaBufferSize: 102400,
location: opts.local ? 'lan' : 'wan',
videoQuality: 100,
maxVideoBitrate: profile ? profile.kbps : Math.max(media?.bitrate ?? 0, 200000),
videoResolution: profile ? `${profile.width}x${profile.height}` : `${media?.width || 3840}x${media?.height || 2160}`,
subtitles: 'burn',
subtitleSize: 100,
audioBoost: 100,
autoAdjustQuality: 0,
'X-Plex-Session-Identifier': opts.session,
'X-Plex-Client-Profile-Extra': extra,
});
}
export function partAt(media: Media, timeMs: number): { part: Part; local: number } {
let start = 0;
for (const p of media.parts) {
if (!p.duration || timeMs < start + p.duration) return { part: p, local: timeMs - start };
start += p.duration;
}
const last = media.parts[media.parts.length - 1];
return { part: last, local: timeMs - (start - (last?.duration ?? 0)) };
}
/** Server-generated preview thumbnail for a position, if the part has an index. */
export function previewUrl(server: PlexServer, media: Media | undefined, timeMs: number): string {
if (!media) return '';
const { part, local } = partAt(media, timeMs);
if (!part?.indexes.split(',').includes('sd')) return '';
return server.signed(`/library/parts/${part.id}/indexes/sd/${Math.max(0, Math.floor(local / 5000) * 5000)}`);
}
export async function reportTimeline(
server: PlexServer,
item: Item,
state: 'playing' | 'paused' | 'buffering' | 'stopped',
timeMs: number,
session: string,
extra: Record<string, string | number> = {},
) {
await server.get(
'/:/timeline',
{
ratingKey: item.id,
key: item.key || `/library/metadata/${item.id}`,
state,
time: Math.max(0, Math.round(timeMs)),
duration: Math.round(item.duration),
identifier: 'com.plexapp.plugins.library',
hasMDE: 1,
...extra,
},
{ headers: { 'X-Plex-Session-Identifier': session }, timeout: 10000 },
);
}
export async function stopTranscode(server: PlexServer, session: string) {
await server.get('/video/:/transcode/universal/stop', { session }).catch(() => {});
}

114
src/plex/plex.test.ts Normal file
View file

@ -0,0 +1,114 @@
import { describe, expect, it } from 'vitest';
import { parseItem, parseScores } from './parse';
import { isLocalAddress } from './account';
import { partAt } from './playback';
import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format';
import { buildFeatures } from '../screens/discover';
import type { Hub } from './types';
const movie = (over: Record<string, unknown> = {}) =>
parseItem({
ratingKey: '9776',
key: '/library/metadata/9776',
type: 'movie',
title: '2 Fast 2 Furious',
summary: 'An ex-cop…',
art: '/art',
year: 2003,
duration: 6000000,
Image: [{ type: 'clearLogo', url: '/logo' }],
UltraBlurColors: [{ topLeft: '162e4f', topRight: '30618f', bottomRight: '345e96', bottomLeft: '1c2c56' }],
Media: [
{
id: '1',
videoResolution: '4k',
audioChannels: 8,
Part: [
{
id: '10',
key: '/library/parts/10/file.mkv',
duration: 3000000,
Stream: [
{ id: 's1', streamType: 1, codec: 'hevc', DOVIPresent: true, index: 0 },
{ id: 's2', streamType: 2, codec: 'truehd', displayTitle: 'English (TrueHD 7.1 Atmos)', index: 1 },
],
},
{ id: '11', key: '/library/parts/11/file.mkv', duration: 3000000 },
],
},
],
...over,
});
describe('parsing', () => {
it('reads logos, UltraBlur colors and format facts', () => {
const m = movie();
expect(m.logo).toBe('/logo');
expect(m.ultraBlur?.topRight).toBe('30618f');
expect(m.media[0].dynamicRange).toBe('Dolby Vision');
expect(m.media[0].atmos).toBe(true);
expect(formatBadges(m)).toEqual(['4K', 'DOLBY VISION', 'ATMOS']);
});
it('keeps audience scores and never substitutes critic ratings', () => {
const scores = parseScores({
Rating: [
{ image: 'rottentomatoes://image.rating.upright', value: 7.9, type: 'audience' },
{ image: 'rottentomatoes://image.rating.ripe', value: 9.1, type: 'critic' },
{ image: 'imdb://image.rating', value: 7.2, type: 'audience' },
],
});
expect(scores.filter((s) => s.kind === 'audience').map((s) => s.source)).toEqual(['Rotten Tomatoes', 'IMDb']);
expect(scores.find((s) => s.kind === 'critic')?.value).toBe(9.1);
});
});
describe('watched rules', () => {
it('treats a resumed title as watched only past the threshold', () => {
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false);
expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 90)).toBe(true);
expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true);
});
it('uses episode counts for shows', () => {
expect(isWatched(parseItem({ type: 'show', leafCount: 10, viewedLeafCount: 10 }))).toBe(true);
expect(isWatched(parseItem({ type: 'show', leafCount: 10, viewedLeafCount: 3 }))).toBe(false);
});
it('formats durations and time left', () => {
expect(duration(6000000)).toBe('1h 40m');
expect(duration(45 * 60000)).toBe('45m');
expect(remaining(movie({ viewOffset: 3000000 }))).toBe('50m left');
});
});
describe('connections', () => {
it('recognizes local plex.direct and private addresses', () => {
expect(isLocalAddress('https://192-168-50-81.abc.plex.direct:32400')).toBe(true);
expect(isLocalAddress('http://10.0.0.5:32400')).toBe(true);
expect(isLocalAddress('https://38-130-3-235.abc.plex.direct:27015')).toBe(false);
});
});
describe('playback', () => {
it('maps a position to the right part of a multi-part title', () => {
const m = movie().media[0];
expect(partAt(m, 1000).part.id).toBe('10');
expect(partAt(m, 4000000)).toMatchObject({ local: 1000000 });
});
});
describe('features', () => {
it('interleaves sources, skips in-progress titles and needs artwork', () => {
const hub = (id: string, items: Record<string, unknown>[]): Hub => ({ id, key: '', title: id, type: 'movie', context: '', size: items.length, more: false, style: '', items: items.map((i) => movie(i)) });
const features = buildFeatures([
hub('movie.recentlyreleased.1', [{ ratingKey: 'a' }, { ratingKey: 'b', viewOffset: 100 }]),
hub('movie.topunwatched.1', [{ ratingKey: 'c' }, { ratingKey: 'd', art: '' }]),
]);
expect(features.map((f) => f.item.id).sort()).toEqual(['a', 'c']);
});
it('builds an artwork wash from UltraBlur colors', () => {
expect(washGradient(movie().ultraBlur)).toContain('rgba(48, 97, 143');
});
});

277
src/plex/types.ts Normal file
View file

@ -0,0 +1,277 @@
/** Normalized Plex models. Parsing lives in parse.ts; raw JSON is kept for editors. */
export type ItemType =
| 'movie'
| 'show'
| 'season'
| 'episode'
| 'collection'
| 'clip'
| 'playlist'
| 'person'
| 'artist'
| 'album'
| 'track'
| 'photo'
| string;
export interface Stream {
id: string;
streamType: 1 | 2 | 3 | number; // video, audio, subtitle
codec: string;
index: number;
language: string;
languageCode: string;
displayTitle: string;
extendedDisplayTitle: string;
title: string;
selected: boolean;
default: boolean;
forced: boolean;
key: string; // external subtitle path
channels: number;
audioChannelLayout: string;
bitrate: number;
width: number;
height: number;
frameRate: number;
profile: string;
colorTrc: string;
colorPrimaries: string;
bitDepth: number;
doviPresent: boolean;
hearingImpaired: boolean;
samplingRate: number;
}
export interface Part {
id: string;
key: string;
file: string;
size: number;
duration: number;
container: string;
indexes: string;
streams: Stream[];
accessible: boolean;
exists: boolean;
}
export interface Media {
id: string;
container: string;
videoCodec: string;
audioCodec: string;
videoResolution: string;
width: number;
height: number;
bitrate: number;
duration: number;
audioChannels: number;
videoProfile: string;
videoFrameRate: string;
aspectRatio: number;
optimizedForStreaming: boolean;
title: string;
parts: Part[];
dynamicRange: string; // 'Dolby Vision' | 'HDR10' | 'HLG' | ''
atmos: boolean;
}
export interface Marker {
id: string;
type: 'intro' | 'credits' | 'commercial' | string;
start: number;
end: number;
final: boolean;
}
export interface Chapter {
index: number;
title: string;
start: number;
end: number;
thumb: string;
}
export interface Tag {
id: string;
tag: string;
filter: string;
}
export interface Role extends Tag {
role: string;
thumb: string;
}
export interface AudienceScore {
source: 'Rotten Tomatoes' | 'IMDb' | 'TMDB' | 'TVDB';
value: number; // 0–10
kind: 'audience' | 'critic';
image: string;
}
export interface Item {
id: string;
key: string;
guid: string;
guids: string[];
type: ItemType;
subtype: string;
title: string;
titleSort: string;
originalTitle: string;
summary: string;
tagline: string;
year: number;
originallyAvailableAt: string;
duration: number;
viewOffset: number;
viewCount: number;
lastViewedAt: number;
addedAt: number;
updatedAt: number;
thumb: string;
art: string;
logo: string;
theme: string;
contentRating: string;
studio: string;
parentId: string;
parentKey: string;
parentTitle: string;
parentIndex: number;
parentThumb: string;
grandparentId: string;
grandparentKey: string;
grandparentTitle: string;
grandparentThumb: string;
grandparentArt: string;
index: number;
leafCount: number;
viewedLeafCount: number;
childCount: number;
genres: Tag[];
directors: Tag[];
writers: Tag[];
producers: Tag[];
countries: Tag[];
labels: Tag[];
collections: Tag[];
roles: Role[];
scores: AudienceScore[];
userRating: number;
media: Media[];
markers: Marker[];
chapters: Chapter[];
extras: Item[];
librarySectionId: string;
librarySectionTitle: string;
librarySectionKey: string;
/** For collections: number of members. For people (search hubs): unused. */
smart: boolean;
editionTitle: string;
skipChildren: boolean;
/** Plex UltraBlur corner colors (hex without #), for artwork-led washes. */
ultraBlur: { topLeft: string; topRight: string; bottomRight: string; bottomLeft: string } | null;
raw: any;
}
export interface Hub {
id: string;
key: string;
title: string;
type: string;
context: string;
size: number;
more: boolean;
style: string;
items: Item[];
}
export interface Section {
id: string;
key: string;
title: string;
type: 'movie' | 'show' | 'artist' | 'photo' | string;
agent: string;
scanner: string;
language: string;
thumb: string;
art: string;
locations: { id: string; path: string }[];
scannedAt: number;
updatedAt: number;
contentChangedAt: number;
refreshing: boolean;
hidden: boolean;
}
export interface Page<T> {
items: T[];
total: number;
offset: number;
}
export interface PlexUser {
id: number;
uuid: string;
username: string;
title: string;
email: string;
thumb: string;
home: boolean;
homeAdmin: boolean;
protected: boolean;
subscription: boolean;
}
export interface HomeUser {
id: number;
uuid: string;
title: string;
username: string;
thumb: string;
admin: boolean;
protected: boolean;
restricted: boolean;
guest: boolean;
}
export interface ServerConnection {
uri: string;
local: boolean;
relay: boolean;
protocol: string;
address: string;
port: number;
IPv6: boolean;
}
export interface ServerResource {
id: string; // clientIdentifier / machineIdentifier
name: string;
owned: boolean;
accessToken: string;
productVersion: string;
platform: string;
presence: boolean;
publicAddress: string;
connections: ServerConnection[];
sourceTitle: string;
httpsRequired: boolean;
}
export interface FilterOption {
key: string;
title: string;
}
export interface LibraryQuery {
sectionId: string;
type?: number; // 1 movie, 2 show, 3 season, 4 episode
sort: string; // e.g. titleSort:asc
filters: Record<string, string>; // e.g. genre=12, unwatched=1
title?: string;
}