Kaleido-Desktop/src/plex/account.ts
Elijah Kuntz 7d0803481b Port Kaleido Desktop to macOS
macOS (Apple silicon) now plays, browses and updates like Windows:

- Video: libmpv's render API draws into a CAOpenGLLayer beneath the
  WKWebView, with the miniplayer rectangle, HDR passthrough through
  extended dynamic range (PQ/BT.2020) and display-sleep prevention.
- Window: native traffic lights on the top bar's centre line, hidden
  with the player's controls; the page's caption buttons are Windows-only.
- Interface: macOS shortcut labels (⌘K, ⌘[, ⌃⌘F), Plex identifies the
  player as a Mac, and header values are kept ASCII (Mac computer names
  usually contain a curly apostrophe).
- The window appears without waiting for an animation frame, which
  WKWebView doesn't run in a hidden window.
- Credentials: release builds use the Keychain and are signed with a
  lasting self-signed certificate so access survives updates; debug
  builds keep tokens in a private file to avoid prompts on every rebuild.
- Bundling: scripts/fetch-libmpv.sh makes Homebrew's libmpv and its
  libraries self-contained; scripts/build.sh builds the .app, .dmg and
  signed update archive.

Releases now carry both platforms: publish-release.mjs uploads each
machine's build into one release, and update-manifest.mjs writes the
feed from that release's assets, refusing while a platform is missing.

The updater uses a new signing key (public key in tauri.conf.json), so
existing installs must be reinstalled once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:14:40 -07:00

182 lines
6.6 KiB
TypeScript

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<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]': PLATFORM,
'context[device][device]': DEVICE,
});
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 };
}