Kaleido-Desktop/src/screens/settings/ServerDashboard.tsx
Elijah 00d72e70f4 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>
2026-10-30 16:26:37 -07:00

255 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useMemo } from 'react';
import * as admin from '../../plex/admin';
import * as api from '../../plex/api';
import { useServerQuery } from '../../app/queries';
import { useServer } from '../../app/session';
import { bitrate, clock, episodeLabel, relativeTime } from '../../app/format';
import { Artwork, Button, EmptyState, PageLoader } from '../../ui/primitives';
import { promptDialog, toast, toastError } from '../../ui/overlays';
import { Icon } from '../../ui/Icon';
import { Card, StatTile } from './parts';
function AreaChart({ series, height = 150, max, format }: { series: { values: number[]; color: string; label: string }[]; height?: number; max?: number; format: (v: number) => string }) {
const n = Math.max(...series.map((s) => s.values.length), 2);
const top = Math.max(max ?? 0, ...series.flatMap((s) => s.values), 1);
const W = 920;
const path = (values: number[]) => values.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / (n - 1)) * W).toFixed(1)} ${(height - 6 - (v / top) * (height - 16)).toFixed(1)}`).join(' ');
return (
<div className="chart">
<svg viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="none" className="chart-svg" role="img">
<defs>
{series.map((s, i) => (
<linearGradient key={i} id={`g${i}${s.label}`} x1="0" x2="0" y1="0" y2="1">
<stop stopColor={s.color} stopOpacity=".28" />
<stop offset="1" stopColor={s.color} stopOpacity="0" />
</linearGradient>
))}
</defs>
{[0.25, 0.5, 0.75, 1].map((f) => (
<path key={f} d={`M0 ${(height - 6 - f * (height - 16)).toFixed(1)} H${W}`} stroke="rgba(255,255,255,.08)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
))}
{series.map((s, i) =>
s.values.length > 1 ? (
<g key={i}>
<path d={`${path(s.values)} L${(((s.values.length - 1) / (n - 1)) * W).toFixed(1)} ${height} L0 ${height} Z`} fill={`url(#g${i}${s.label})`} />
<path d={path(s.values)} stroke={s.color} strokeWidth="2" fill="none" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
</g>
) : null,
)}
</svg>
<div className="chart-footer">
<div className="legend">
{series.map((s) => (
<span key={s.label}>
<i style={{ background: s.color }} />
{s.label} {s.values.length ? format(s.values[s.values.length - 1]) : ''}
</span>
))}
</div>
<span>Peak {format(top)}</span>
</div>
</div>
);
}
function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () => void }) {
const server = useServer();
const item = session.item;
const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb;
const pct = item.duration ? (session.viewOffset / item.duration) * 100 : 0;
const d = session.decision;
const mode = !d ? 'Direct play' : d.video === 'transcode' ? 'Transcoding video' : d.audio === 'transcode' ? 'Transcoding audio' : 'Direct stream';
return (
<div className="now-playing">
<div className="np-poster">
<Artwork src={server.image(poster, 90, 135)} />
</div>
<div className="np-body">
<h3>{item.type === 'episode' ? item.grandparentTitle : item.title}</h3>
<p>{item.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : item.year || ''}</p>
<p className="dim">
{session.user.title} · {session.player.title || session.player.product} ({session.player.platform}) · {session.player.local ? 'Local' : 'Remote'} {session.player.address}
</p>
<div className="np-progress">
<span className="progress-bar">
<i style={{ width: `${pct}%` }} />
</span>
<span className="dim">
{session.player.state === 'paused' ? 'Paused · ' : session.player.state === 'buffering' ? 'Buffering · ' : ''}
{clock(session.viewOffset / 1000)} / {clock(item.duration / 1000)}
</span>
</div>
<div className="np-pills">
<span className={`stream-pill${d?.video === 'transcode' ? ' warn' : ''}`}>
<Icon name={d ? 'cpu' : 'check'} size={13} />
{mode}
{d?.transcodeHw ? ' (hw)' : ''}
</span>
{session.bandwidth > 0 && <span className="stream-pill neutral">{bitrate(session.bandwidth)}</span>}
{d && d.speed > 0 && <span className="stream-pill neutral">{d.speed.toFixed(1)}× {d.throttled ? 'throttled' : ''}</span>}
</div>
</div>
<Button variant="ghost" size="sm" icon="x" onClick={onStop}>
Stop
</Button>
</div>
);
}
function Dashboard() {
const server = useServer();
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 6000, staleTime: 0 });
const res = useServerQuery(['resources'], (s) => admin.resources(s, 6), { refetchInterval: 6000, staleTime: 0 });
const info = useServerQuery(['serverInfo'], (s) => api.serverInfo(s), { staleTime: 60_000 });
const sections = useServerQuery(['sections'], (s) => api.sections(s));
const remote = useServerQuery(['remoteAccess'], (s) => admin.remoteAccess(s), { staleTime: 60_000 });
const list = sessions.data ?? [];
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
const points = (bw.data?.points ?? []).slice(-40);
const toMbps = (bytes: number) => (bytes * 8) / 6 / 1e6;
const lan = points.map((p) => toMbps(p.lan));
const wan = points.map((p) => toMbps(p.wan));
const r = (res.data ?? []).slice(-40);
const cpu = r[r.length - 1];
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
const stop = async (s: admin.Session) => {
const reason = await promptDialog({
title: 'Stop this stream?',
message: `${s.user.title} will see this message on ${s.player.title || s.player.product}.`,
confirm: 'Stop stream',
danger: true,
input: { label: 'Message', value: 'The server owner has ended this stream.' },
});
if (reason === null) return;
try {
await admin.terminateSession(server, s.sessionId, reason);
toast('Stream stopped', 'success');
sessions.refetch();
} catch (e) {
toastError(e);
}
};
const mc = info.data ?? {};
return (
<>
<div className="stats-grid">
<StatTile label="Active streams" value={list.length} detail={list.length ? `${list.length - transcodes} direct · ${transcodes} transcoding` : 'Nothing playing'} />
<StatTile label="Streaming bandwidth" value={totalBandwidth ? bitrate(totalBandwidth) : '0 Mbps'} detail={`${list.filter((s) => !s.player.local).length} remote`} />
<StatTile label="Server CPU" value={cpu ? `${Math.round(cpu.hostCpu)}%` : '—'} detail={cpu ? `Plex ${cpu.processCpu.toFixed(1)}%` : ''} tone={cpu && cpu.hostCpu > 85 ? 'warn' : undefined} />
<StatTile label="Remote access" value={remote.data?.mappingState === 'mapped' ? 'Online' : 'Limited'} detail={remote.data?.publicAddress ?? ''} tone={remote.data?.mappingState === 'mapped' ? 'good' : 'warn'} />
</div>
<Card title="Now playing" actions={<span className="status-tag"><i className="dot" />{list.length} active</span>}>
{sessions.isLoading && <PageLoader />}
{sessions.data && !list.length && <p className="muted np-empty">No one is watching right now.</p>}
{list.map((s) => (
<NowPlaying key={s.sessionKey} session={s} onStop={() => stop(s)} />
))}
</Card>
<div className="admin-2-col">
<Card title="Bandwidth" actions={<span className="note">Last few minutes · live</span>}>
<AreaChart
series={[
{ values: wan, color: '#6797f5', label: 'Remote' },
{ values: lan, color: '#e0ad5d', label: 'Local' },
]}
format={(v) => `${v.toFixed(1)} Mbps`}
/>
</Card>
<Card title="Resources" actions={<span className="note">Host CPU and memory</span>}>
<AreaChart
series={[
{ values: r.map((p) => p.hostCpu), color: '#8fc7a8', label: 'CPU' },
{ values: r.map((p) => p.hostMemory), color: '#b49ae8', label: 'Memory' },
]}
max={100}
format={(v) => `${Math.round(v)}%`}
/>
</Card>
</div>
<Card title="Server">
<div className="server-info">
{[
['Name', mc.friendlyName],
['Version', String(mc.version ?? '').split('-')[0]],
['Platform', [mc.platform, mc.platformVersion].filter(Boolean).join(' ')],
['Libraries', (sections.data ?? []).map((s) => s.title).join(', ')],
['Plex Pass', mc.myPlexSubscription ? 'Active' : 'Not active'],
['Signed in as', mc.myPlexUsername],
['Transcoder', mc.transcoderVideo ? 'Video, audio' : 'Available'],
['Connection', server.uri.replace(/^https?:\/\//, '')],
].map(([k, v]) => (
<div key={k as string}>
<span>{k}</span>
<b>{(v as string) || '—'}</b>
</div>
))}
</div>
</Card>
</>
);
}
function Activity() {
const server = useServer();
const activities = useServerQuery(['activities'], (s) => admin.activities(s), { refetchInterval: 3000, staleTime: 0 });
const history = useServerQuery(['history'], (s) => admin.history(s, 40), { staleTime: 15_000 });
const accounts = useServerQuery(['accounts'], (s) => admin.accounts(s), { staleTime: 10 * 60_000 });
const devices = useServerQuery(['devices'], (s) => admin.devices(s), { staleTime: 10 * 60_000 });
const deviceName = useMemo(() => Object.fromEntries((devices.data ?? []).map((d) => [d.id, d.name])), [devices.data]);
return (
<>
<Card title="Running now" actions={<span className="note">Scans, analysis and maintenance</span>}>
{activities.data && !activities.data.length && <p className="muted np-empty">The server is idle.</p>}
{activities.data?.map((a) => (
<div key={a.uuid} className="activity-row">
<div className="lib-ico">
<Icon name={a.type.includes('library') ? 'refresh' : a.type.includes('media') ? 'film' : 'activity'} size={17} />
</div>
<div className="activity-text">
<strong>{a.title}</strong>
<small>{a.subtitle}</small>
{a.progress > 0 && (
<span className="progress-bar">
<i style={{ width: `${a.progress}%` }} />
</span>
)}
</div>
{a.cancellable && (
<Button variant="ghost" size="sm" onClick={() => admin.cancelActivity(server, a.uuid).then(() => activities.refetch(), toastError)}>
Cancel
</Button>
)}
</div>
))}
</Card>
<Card title="Watch history">
{history.isLoading && <PageLoader />}
{history.data && !history.data.length && <EmptyState icon="clock" title="No history yet" />}
<div className="history-list">
{history.data?.map((h) => (
<div key={h.id + h.viewedAt} className="history-row">
<div className="history-thumb">
<Artwork src={server.image(h.thumb, 60, 90)} />
</div>
<div>
<strong>{h.title}</strong>
<small>{h.subtitle}</small>
</div>
<span className="dim">{accounts.data?.[h.accountId] ?? 'Owner'}</span>
<span className="dim">{deviceName[h.deviceId] ?? ''}</span>
<span className="dim">{relativeTime(h.viewedAt)}</span>
</div>
))}
</div>
</Card>
</>
);
}
export default function ServerDashboard({ tab }: { tab: 'dashboard' | 'activity' }) {
return tab === 'dashboard' ? <Dashboard /> : <Activity />;
}