import { arr, bool, num, str } from './parse'; import { clientIdentifier, DEVICE, PLATFORM, 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 { 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 { 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]': PLATFORM, 'context[device][device]': DEVICE, }); return `https://app.plex.tv/auth#?${params.toString()}`; } export async function getUser(token: string): Promise { 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 { const list = await plexRequest(`${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 { 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 { 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 { 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 { 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 { 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 }; }