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 (
{series.map((s, i) => ( ))} {[0.25, 0.5, 0.75, 1].map((f) => ( ))} {series.map((s, i) => s.values.length > 1 ? ( ) : null, )}
{series.map((s) => ( {s.label} {s.values.length ? format(s.values[s.values.length - 1]) : ''} ))}
Peak {format(top)}
); } /** Seconds of bandwidth the chart shows. */ const BANDWIDTH_WINDOW = 120; /** * Plex's real-time bandwidth samples are bytes per second, and seconds with * no traffic are left out; lay them on a gap-free per-second axis in Mbps. */ function perSecond(points: admin.BandwidthPoint[]) { const latest = points.length ? points[points.length - 1].at : 0; // Ends at the newest sample, or now when nothing has been sent lately. const end = Math.max(latest, Math.floor(Date.now() / 1000) - 2); const lan = new Array(BANDWIDTH_WINDOW).fill(0); const wan = new Array(BANDWIDTH_WINDOW).fill(0); for (const p of points) { const i = BANDWIDTH_WINDOW - 1 - (end - p.at); if (i < 0 || i >= BANDWIDTH_WINDOW) continue; lan[i] = (p.lan * 8) / 1e6; wan[i] = (p.wan * 8) / 1e6; } return { lan, wan }; } 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 (

{item.type === 'episode' ? item.grandparentTitle : item.title}

{item.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : item.year || ''}

{session.user.title} · {session.player.title || session.player.product} ({session.player.platform}) · {session.player.local ? 'Local' : 'Remote'} {session.player.address}

{session.player.state === 'paused' ? 'Paused · ' : session.player.state === 'buffering' ? 'Buffering · ' : ''} {clock(session.viewOffset / 1000)} / {clock(item.duration / 1000)}
{mode} {d?.transcodeHw ? ' (hw)' : ''} {session.bandwidth > 0 && {bitrate(session.bandwidth)}} {d && d.speed > 0 && {d.speed.toFixed(1)}× {d.throttled ? 'throttled' : ''}}
); } 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: 1000, 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 { lan, wan } = perSecond(bw.data?.points ?? []); 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 ( <>
!s.player.local).length} remote`} /> 85 ? 'warn' : undefined} />
{list.length} active}> {sessions.isLoading && } {sessions.data && !list.length &&

No one is watching right now.

} {list.map((s) => ( stop(s)} /> ))}
Last 2 minutes · live}> `${v.toFixed(1)} Mbps`} /> Host CPU and memory}> p.hostCpu), color: '#8fc7a8', label: 'CPU' }, { values: r.map((p) => p.hostMemory), color: '#b49ae8', label: 'Memory' }, ]} max={100} format={(v) => `${Math.round(v)}%`} />
{[ ['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]) => (
{k} {(v as string) || '—'}
))}
); } 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 ( <> Scans, analysis and maintenance}> {activities.data && !activities.data.length &&

The server is idle.

} {activities.data?.map((a) => (
{a.title} {a.subtitle} {a.progress > 0 && ( )}
{a.cancellable && ( )}
))}
{history.isLoading && } {history.data && !history.data.length && }
{history.data?.map((h) => (
{h.title} {h.subtitle}
{accounts.data?.[h.accountId] ?? 'Owner'} {deviceName[h.deviceId] ?? ''} {relativeTime(h.viewedAt)}
))}
); } export default function ServerDashboard({ tab }: { tab: 'dashboard' | 'activity' }) { return tab === 'dashboard' ? : ; }