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:
commit
00d72e70f4
121 changed files with 25315 additions and 0 deletions
222
src/screens/Downloads.tsx
Normal file
222
src/screens/Downloads.tsx
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useDownloads, type Download } from '../downloads/store';
|
||||
import { useSession } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { duration, episodeLabel, fileSize } from '../app/format';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { invoke, isNative, localFileUrl, revealPath } from '../platform/native';
|
||||
import { Button, EmptyState, IconButton } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { confirmDialog, openMenu } from '../ui/overlays';
|
||||
|
||||
function useLocalArt(d: Download, key: string) {
|
||||
const [url, setUrl] = useState('');
|
||||
const path = d.meta.localAssets?.[key];
|
||||
useEffect(() => {
|
||||
if (path) localFileUrl(path).then(setUrl);
|
||||
}, [path]);
|
||||
return url;
|
||||
}
|
||||
|
||||
function DownloadRow({ d }: { d: Download }) {
|
||||
const store = useDownloads();
|
||||
const server = useSession((s) => s.server);
|
||||
const item = store.itemOf(d);
|
||||
const still = useLocalArt(d, item.type === 'episode' ? 'still' : 'art');
|
||||
const poster = useLocalArt(d, 'poster');
|
||||
const pct = d.total ? Math.min(100, (d.received / d.total) * 100) : 0;
|
||||
const isEp = item.type === 'episode';
|
||||
const onServer = server?.machineId === d.meta.serverId;
|
||||
const play = () => usePlayer.getState().play(item, { localFile: d.filePath, resume: true });
|
||||
const remove = async () => {
|
||||
if (await confirmDialog({ title: 'Remove download?', message: `“${item.title}” will be deleted from this computer. It stays available on your Plex server.`, confirm: 'Remove', danger: true })) store.remove(d.id);
|
||||
};
|
||||
const status =
|
||||
d.status === 'completed'
|
||||
? fileSize(d.total || d.received)
|
||||
: d.status === 'downloading'
|
||||
? `${fileSize(d.received)} of ${fileSize(d.total)}${d.speed ? ` · ${fileSize(d.speed)}/s` : ''}`
|
||||
: d.status === 'queued'
|
||||
? 'Waiting…'
|
||||
: d.status === 'paused'
|
||||
? `Paused · ${fileSize(d.received)} of ${fileSize(d.total)}`
|
||||
: (d.error ?? 'Failed');
|
||||
return (
|
||||
<div className={`download-row ${d.status}`}>
|
||||
<button className="dl-thumb" onClick={d.status === 'completed' ? play : undefined} aria-label={`Play ${item.title}`}>
|
||||
{(still || poster) && <img src={still || poster} alt="" draggable={false} className={still ? '' : 'poster'} />}
|
||||
{d.status === 'completed' && (
|
||||
<span className="dl-play">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<div className="dl-details">
|
||||
<h3>{isEp ? item.grandparentTitle : item.title}</h3>
|
||||
<p>
|
||||
{isEp ? `${episodeLabel(item)} · ${item.title}` : [item.year, duration(item.duration)].filter(Boolean).join(' · ')}
|
||||
{d.meta.serverName && <span className="dim"> · {d.meta.serverName}</span>}
|
||||
</p>
|
||||
{d.status !== 'completed' ? (
|
||||
<div className="dl-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="dl-status">{status}</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="file-status">
|
||||
<Icon name="check" size={14} /> Ready offline · {status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="dl-actions">
|
||||
{d.status === 'completed' && (
|
||||
<Button variant="ghost" size="sm" icon="play" onClick={play}>
|
||||
Play
|
||||
</Button>
|
||||
)}
|
||||
{d.status === 'downloading' || d.status === 'queued' ? (
|
||||
<IconButton icon="pause" label="Pause" onClick={() => store.pause(d.id)} />
|
||||
) : d.status === 'paused' || d.status === 'failed' ? (
|
||||
<IconButton icon="refresh" label="Resume" onClick={() => store.resume(d.id)} />
|
||||
) : null}
|
||||
<IconButton
|
||||
icon="dots"
|
||||
label="More"
|
||||
onClick={(e) =>
|
||||
openMenu(
|
||||
[
|
||||
...(onServer ? [{ label: 'Details', icon: 'info', onSelect: () => navigate({ name: 'item', id: item.id }) }] : []),
|
||||
...(d.status === 'completed' ? [{ label: 'Show in folder', icon: 'folder', onSelect: () => revealPath(d.filePath) }] : []),
|
||||
{ divider: true },
|
||||
{ label: 'Remove download', icon: 'trash', danger: true, onSelect: remove },
|
||||
],
|
||||
e.currentTarget,
|
||||
{ align: 'end' },
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Downloads({ offline }: { offline?: boolean }) {
|
||||
const store = useDownloads();
|
||||
const [space, setSpace] = useState<{ free: number; total: number } | null>(null);
|
||||
useEffect(() => {
|
||||
store.init();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (isNative && store.dir) invoke<{ free: number; total: number }>('disk_space', { path: store.dir }).then(setSpace).catch(() => {});
|
||||
}, [store.dir, store.items.length]);
|
||||
|
||||
const active = store.items.filter((d) => d.status !== 'completed');
|
||||
const done = store.items.filter((d) => d.status === 'completed');
|
||||
const used = store.items.reduce((a, d) => a + (d.status === 'completed' ? d.total || d.received : d.received), 0);
|
||||
const movies = done.filter((d) => d.meta.raw?.type !== 'episode');
|
||||
const episodes = done.filter((d) => d.meta.raw?.type === 'episode');
|
||||
const shows = new Map<string, Download[]>();
|
||||
for (const e of episodes) {
|
||||
const k = e.meta.raw?.grandparentTitle ?? 'Episodes';
|
||||
shows.set(k, [...(shows.get(k) ?? []), e]);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`downloads-page page-pad${offline ? '' : ' top'}`}>
|
||||
<div className="download-intro">
|
||||
<div>
|
||||
<div className="micro">Offline · This computer</div>
|
||||
<h1 className="page-title">Downloads</h1>
|
||||
<p className="page-subtitle">Movies and episodes saved to this computer play without a connection. Progress syncs to Plex when you’re back online.</p>
|
||||
</div>
|
||||
{isNative && (
|
||||
<div className="storage-card">
|
||||
<div className="storage-head">
|
||||
<b>Storage</b>
|
||||
<span>{space ? `${fileSize(space.free)} free` : ''}</span>
|
||||
</div>
|
||||
<div className="storage-bar">
|
||||
{space && (
|
||||
<>
|
||||
<span className="other" style={{ width: `${Math.max(0, ((space.total - space.free - used) / space.total) * 100)}%` }} />
|
||||
<span className="mine" style={{ width: `${(used / space.total) * 100}%` }} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="storage-caption">
|
||||
{fileSize(used) || '0 MB'} used by Kaleido
|
||||
{store.dir && (
|
||||
<button className="inline-link" onClick={() => revealPath(store.dir)} title={store.dir}>
|
||||
Open folder
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isNative && (
|
||||
<EmptyState icon="download" title="Downloads need the desktop app">
|
||||
Install Kaleido for Windows to save movies and episodes for offline viewing.
|
||||
</EmptyState>
|
||||
)}
|
||||
{isNative && !store.items.length && (
|
||||
<EmptyState icon="download" title="Nothing downloaded yet" action={!offline && <Button variant="ghost" icon="film" onClick={() => navigate({ name: 'section', kind: 'movie', tab: 'library' })}>Browse movies</Button>}>
|
||||
Choose Download on a movie or episode, or download a whole season from its page.
|
||||
</EmptyState>
|
||||
)}
|
||||
|
||||
{active.length > 0 && (
|
||||
<section className="dl-section">
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
In progress <small>{active.length}</small>
|
||||
</h2>
|
||||
<div className="actions">
|
||||
{active.some((d) => d.status === 'downloading' || d.status === 'queued') ? (
|
||||
<Button variant="text" onClick={() => active.forEach((d) => (d.status === 'downloading' || d.status === 'queued') && store.pause(d.id))}>
|
||||
Pause all
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="text" onClick={() => active.forEach((d) => store.resume(d.id))}>
|
||||
Resume all
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{active.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{movies.length > 0 && (
|
||||
<section className="dl-section">
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
Movies <small>{movies.length}</small>
|
||||
</h2>
|
||||
</div>
|
||||
{movies.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{[...shows.entries()].map(([show, list]) => (
|
||||
<section className="dl-section" key={show}>
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
{show} <small>{list.length} episode{list.length === 1 ? '' : 's'}</small>
|
||||
</h2>
|
||||
</div>
|
||||
{list
|
||||
.sort((a, b) => (a.meta.raw.parentIndex - b.meta.raw.parentIndex) * 1000 + (a.meta.raw.index - b.meta.raw.index))
|
||||
.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
53
src/screens/Home.tsx
Normal file
53
src/screens/Home.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import * as api from '../plex/api';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { Hero } from '../ui/Hero';
|
||||
import { HubShelf } from '../ui/media';
|
||||
import { ErrorState, PageLoader } from '../ui/primitives';
|
||||
import { buildFeatures, HIDDEN_HUBS } from './discover';
|
||||
|
||||
export function Home() {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden);
|
||||
|
||||
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s));
|
||||
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), { staleTime: 15_000 });
|
||||
// Section hubs feed the hero and the release shelves; shared with Discover.
|
||||
const sectionHubs = useQuery({
|
||||
queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')],
|
||||
queryFn: async () => (await Promise.all(video.map((s) => api.sectionHubs(server, s.id).catch(() => [])))).flat(),
|
||||
enabled: video.length > 0,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const features = useMemo(() => buildFeatures(sectionHubs.data ?? [], 8), [sectionHubs.data]);
|
||||
const extra = (sectionHubs.data ?? []).filter((h) => /recentlyreleased|recentlyaired|topunwatched|toprated/.test(h.id));
|
||||
|
||||
if (home.isError && !home.data) return <ErrorState error={home.error} onRetry={() => home.refetch()} />;
|
||||
if (!home.data || sections.isLoading) return <PageLoader />;
|
||||
|
||||
const hubs = home.data.filter((h) => !HIDDEN_HUBS.test(h.id));
|
||||
const cw = continueWatching.data ?? [];
|
||||
const homeIds = new Set(hubs.map((h) => h.title));
|
||||
|
||||
return (
|
||||
<div className="home">
|
||||
<Hero features={features} variant="home" />
|
||||
<div className="shelves over-hero">
|
||||
<HubShelf title="Continue Watching" items={cw} continueWatching />
|
||||
{hubs.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} onViewAll={h.more ? () => navigate({ name: 'hub', key: h.key, title: h.title }) : undefined} />
|
||||
))}
|
||||
{extra
|
||||
.filter((h) => !homeIds.has(h.title))
|
||||
.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} onViewAll={() => navigate({ name: 'hub', key: h.key, title: h.title })} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
src/screens/HubScreen.tsx
Normal file
43
src/screens/HubScreen.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useServer } from '../app/session';
|
||||
import { LandscapeCard, PosterCard } from '../ui/media';
|
||||
import { EmptyState, ErrorState, PageLoader, Spinner } from '../ui/primitives';
|
||||
|
||||
/** "View all" for a hub, paged as it scrolls. */
|
||||
export default function HubScreen({ hubKey, title }: { hubKey: string; title: string }) {
|
||||
const server = useServer();
|
||||
const q = useInfiniteQuery({
|
||||
queryKey: [server.machineId, 'hubAll', hubKey],
|
||||
queryFn: ({ pageParam }) => api.hubItems(server, hubKey, pageParam, 72),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (last, pages) => {
|
||||
const loaded = pages.reduce((a, p) => a + p.items.length, 0);
|
||||
return last.items.length && loaded < last.total ? loaded : undefined;
|
||||
},
|
||||
});
|
||||
const sentinel = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = sentinel.current;
|
||||
if (!el) return;
|
||||
const io = new IntersectionObserver(([e]) => e.isIntersecting && q.hasNextPage && !q.isFetchingNextPage && q.fetchNextPage(), { rootMargin: '800px' });
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, [q.hasNextPage, q.isFetchingNextPage]);
|
||||
|
||||
const items = q.data?.pages.flatMap((p) => p.items) ?? [];
|
||||
const wide = items.length > 0 && items.every((i) => i.type === 'episode');
|
||||
return (
|
||||
<div className="page-pad top hub-page">
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{q.isError && <ErrorState error={q.error} onRetry={() => q.refetch()} />}
|
||||
{q.isLoading && <PageLoader />}
|
||||
{q.data && !items.length && <EmptyState title="Nothing here yet" />}
|
||||
<div className={`poster-grid auto${wide ? ' wide' : ''}`}>{items.map((i) => (wide ? <LandscapeCard key={i.id} item={i} /> : <PosterCard key={i.id} item={i} />))}</div>
|
||||
<div ref={sentinel} className="grid-sentinel">
|
||||
{q.isFetchingNextPage && <Spinner />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
616
src/screens/Item.tsx
Normal file
616
src/screens/Item.tsx
Normal file
|
|
@ -0,0 +1,616 @@
|
|||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { invalidateLibrary, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { goBack, navigate, useRouter } from '../app/router';
|
||||
import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
|
||||
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format';
|
||||
import { Backdrop } from '../ui/Backdrop';
|
||||
import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
|
||||
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { openMenu, toastError } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { playThemeMusic, stopThemeMusic } from '../player/theme';
|
||||
|
||||
export function ItemScreen({ id }: { id: string }) {
|
||||
const q = useItem(id);
|
||||
const item = q.data;
|
||||
useEffect(() => {
|
||||
if (item?.theme && item.type !== 'collection') playThemeMusic(item.theme);
|
||||
}, [item?.theme]);
|
||||
useEffect(() => () => stopThemeMusic(), []);
|
||||
if (q.isError) return <div className="page-pad top"><ErrorState error={q.error} onRetry={() => q.refetch()} /></div>;
|
||||
if (!item) return <PageLoader />;
|
||||
switch (item.type) {
|
||||
case 'show':
|
||||
return <ShowDetail item={item} />;
|
||||
case 'season':
|
||||
return <SeasonDetail item={item} />;
|
||||
case 'episode':
|
||||
return <EpisodeDetail item={item} />;
|
||||
case 'collection':
|
||||
return <CollectionDetail item={item} />;
|
||||
default:
|
||||
return <MovieDetail item={item} />;
|
||||
}
|
||||
}
|
||||
|
||||
// —— Shared pieces ————————————————————————————————————————————————
|
||||
|
||||
function Synopsis({ item, text }: { item: Item; text: string }) {
|
||||
const [clamped, setClamped] = useState(false);
|
||||
if (!text) return null;
|
||||
return (
|
||||
<div className="synopsis-wrap">
|
||||
<p
|
||||
className="synopsis"
|
||||
ref={(el) => {
|
||||
if (el) setClamped(el.scrollHeight > el.clientHeight + 2);
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</p>
|
||||
{clamped && (
|
||||
<button className="btn text synopsis-more" onClick={() => openDialog({ kind: 'synopsis', item })}>
|
||||
More
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WatchedButton({ item }: { item: Item }) {
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(item, percent);
|
||||
return (
|
||||
<Button variant="ghost" icon={watched ? 'check' : 'plus'} onClick={() => setWatched(item, !watched)} className={watched ? 'is-on' : ''}>
|
||||
{watched ? 'Watched' : 'Mark watched'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadButton({ item }: { item: Item }) {
|
||||
const downloads = useDownloads();
|
||||
const isSeries = item.type === 'show' || item.type === 'season';
|
||||
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
|
||||
if (isSeries) return <IconButton round icon="download" label={item.type === 'show' ? 'Download unwatched episodes' : 'Download season'} onClick={() => downloads.startAll(item)} />;
|
||||
if (dl?.status === 'completed') return <IconButton round icon="downloaded" label="Downloaded" className="on" onClick={() => navigate({ name: 'downloads' })} />;
|
||||
if (dl) {
|
||||
const pct = dl.total ? Math.round((dl.received / dl.total) * 100) : 0;
|
||||
return (
|
||||
<button className="circle-btn download-progress" aria-label={`Downloading ${pct}%`} title={`Downloading ${pct}%`} onClick={() => navigate({ name: 'downloads' })}>
|
||||
<svg viewBox="0 0 36 36" width="42" height="42">
|
||||
<circle cx="18" cy="18" r="15" fill="none" stroke="rgba(255,255,255,.2)" strokeWidth="2.4" />
|
||||
<circle cx="18" cy="18" r="15" fill="none" stroke="currentColor" strokeWidth="2.4" strokeDasharray={`${pct * 0.94} 100`} transform="rotate(-90 18 18)" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return <IconButton round icon="download" label="Download" onClick={() => downloads.start(item)} />;
|
||||
}
|
||||
|
||||
function MoreButton({ item, onDeleted }: { item: Item; onDeleted?: () => void }) {
|
||||
return <IconButton round icon="dots" label="More actions" onClick={(e) => openMenu(itemMenu(item, { detail: true, onDeleted }), e.currentTarget)} />;
|
||||
}
|
||||
|
||||
function TrailerButton({ item }: { item: Item }) {
|
||||
const trailer = item.extras.find((e) => e.subtype === 'trailer' && e.media.length);
|
||||
if (!trailer) return null;
|
||||
return (
|
||||
<Button variant="ghost" icon="film" onClick={() => playItem(trailer, { resume: false })}>
|
||||
Trailer
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailHero({ item, backdropItem, children, title, below }: { item: Item; backdropItem?: Item; children: ReactNode; title?: ReactNode; below?: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<Backdrop item={backdropItem ?? item} className="detail-backdrop" />
|
||||
<header className="detail-hero">
|
||||
<div className="detail-head">
|
||||
{title ?? <TitleArt item={item} maxWidth={440} maxHeight={140} />}
|
||||
{children}
|
||||
</div>
|
||||
{below}
|
||||
</header>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CastRow({ item, title = 'Cast & Crew' }: { item: Item; title?: string }) {
|
||||
const people = [
|
||||
...item.roles.map((r) => ({ id: r.id, name: r.tag, role: r.role, thumb: r.thumb })),
|
||||
...item.directors.map((d) => ({ id: d.id, name: d.tag, role: 'Director', thumb: (d as any).thumb ?? item.raw?.Director?.find((x: any) => x.tag === d.tag)?.thumb })),
|
||||
...item.writers.slice(0, 3).map((d) => ({ id: d.id, name: d.tag, role: 'Writer', thumb: item.raw?.Writer?.find((x: any) => x.tag === d.tag)?.thumb })),
|
||||
];
|
||||
if (!people.length) return null;
|
||||
return (
|
||||
<Shelf title={title} kind="people">
|
||||
{people.map((p, i) => (
|
||||
<PersonCard key={`${p.id}-${i}`} name={p.name} role={p.role} thumb={p.thumb} onClick={p.id ? () => navigate({ name: 'person', id: p.id, title: p.name, thumb: p.thumb }) : undefined} />
|
||||
))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtrasRow({ item }: { item: Item }) {
|
||||
const extras = item.extras.filter((e) => e.media.length);
|
||||
if (!extras.length) return null;
|
||||
return (
|
||||
<Shelf title="Trailers & Extras" kind="landscape">
|
||||
{extras.map((e) => (
|
||||
<article key={e.id} className="card landscape extra" role="button" tabIndex={0} onClick={() => playItem(e, { resume: false })} onKeyDown={(ev) => ev.key === 'Enter' && playItem(e, { resume: false })}>
|
||||
<ExtraCover item={e} />
|
||||
<div className="card-caption">
|
||||
<div className="card-title">{e.title}</div>
|
||||
<div className="card-meta">{[extraLabel(e), duration(e.duration)].filter(Boolean).join(' · ')}</div>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtraCover({ item }: { item: Item }) {
|
||||
const server = useServer();
|
||||
return (
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(item.thumb, 400, 225)} />
|
||||
<div className="card-hover" />
|
||||
<span className="extra-play">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RelatedRows({ item }: { item: Item }) {
|
||||
const related = useRelated(item.id);
|
||||
const hubs = (related.data ?? []).map((h) => ({ ...h, items: h.items.filter((i) => i.id !== item.id && ['movie', 'show'].includes(i.type)) })).filter((h) => h.items.length);
|
||||
return (
|
||||
<>
|
||||
{hubs.slice(0, 3).map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} landscape={false} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function StarRating({ item }: { item: Item }) {
|
||||
const server = useServer();
|
||||
const [value, setValue] = useState(item.userRating);
|
||||
const [hover, setHover] = useState(0);
|
||||
useEffect(() => setValue(item.userRating), [item.userRating]);
|
||||
const set = async (stars: number) => {
|
||||
const rating = stars * 2 === value ? -1 : stars * 2;
|
||||
setValue(Math.max(0, rating));
|
||||
try {
|
||||
await api.rate(server, item.id, rating);
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
const shown = hover || value / 2;
|
||||
return (
|
||||
<span className="star-rating" onMouseLeave={() => setHover(0)} aria-label="Your rating">
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button key={n} onMouseEnter={() => setHover(n)} onClick={() => set(n)} aria-label={`${n} star${n > 1 ? 's' : ''}`}>
|
||||
<Icon name={n <= shown ? 'starFill' : 'star'} size={15} />
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function AboutPanel({ item }: { item: Item }) {
|
||||
const m = item.media[0];
|
||||
const rows: [string, ReactNode][] = [];
|
||||
const tags = (list: { tag: string; id: string }[], filter: string, limit = 3) =>
|
||||
list.slice(0, limit).map((t, i) => (
|
||||
<span key={t.tag}>
|
||||
{i > 0 && ', '}
|
||||
{filter === 'person' ? (
|
||||
<button className="inline-link" onClick={() => t.id && navigate({ name: 'person', id: t.id, title: t.tag })}>
|
||||
{t.tag}
|
||||
</button>
|
||||
) : (
|
||||
t.tag
|
||||
)}
|
||||
</span>
|
||||
));
|
||||
if (item.directors.length) rows.push([item.directors.length > 1 ? 'Directors' : 'Director', tags(item.directors, 'person')]);
|
||||
if (item.writers.length) rows.push(['Writers', tags(item.writers, 'person')]);
|
||||
if (item.studio) rows.push([item.type === 'show' || item.type === 'episode' ? 'Network' : 'Studio', item.studio]);
|
||||
if (item.originallyAvailableAt) rows.push([item.type === 'show' ? 'Premiered' : 'Released', date(item.originallyAvailableAt)]);
|
||||
if (item.genres.length) rows.push(['Genres', item.genres.map((g) => g.tag).join(', ')]);
|
||||
if (item.countries.length) rows.push(['Country', item.countries.map((c) => c.tag).join(', ')]);
|
||||
if (item.contentRating) rows.push(['Rated', item.contentRating]);
|
||||
if (item.duration && item.type !== 'show') rows.push(['Runtime', duration(item.duration)]);
|
||||
for (const s of item.scores) rows.push([`${s.source}${s.kind === 'critic' ? ' critics' : ''}`, s.source === 'Rotten Tomatoes' ? `${Math.round(s.value * 10)}%` : `${s.value.toFixed(1)} / 10`]);
|
||||
if (item.collections.length) rows.push(['Collections', item.collections.map((c) => c.tag).join(', ')]);
|
||||
if (item.labels.length) rows.push(['Labels', item.labels.map((c) => c.tag).join(', ')]);
|
||||
if (item.editionTitle) rows.push(['Edition', item.editionTitle]);
|
||||
if (m) {
|
||||
rows.push(['Video', [resolutionLabel(m), m.dynamicRange, m.videoCodec.toUpperCase(), m.videoFrameRate].filter(Boolean).join(' · ')]);
|
||||
rows.push(['Audio', [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels), m.atmos ? 'Atmos' : ''].filter(Boolean).join(' · ')]);
|
||||
if (m.bitrate) rows.push(['Bitrate', bitrate(m.bitrate)]);
|
||||
const size = m.parts.reduce((a, p) => a + p.size, 0);
|
||||
if (size) rows.push(['File size', fileSize(size)]);
|
||||
if (item.media.length > 1) rows.push(['Versions', `${item.media.length} available`]);
|
||||
}
|
||||
if (item.addedAt) rows.push(['Added', date(item.addedAt)]);
|
||||
return (
|
||||
<aside className="about-panel">
|
||||
<div className="about-head">
|
||||
<h3>About</h3>
|
||||
{['movie', 'show', 'episode', 'season'].includes(item.type) && <StarRating item={item} />}
|
||||
</div>
|
||||
{item.tagline && <p className="about-tagline">“{item.tagline}”</p>}
|
||||
{rows.map(([k, v]) => (
|
||||
<div className="about-line" key={k}>
|
||||
<span>{k}</span>
|
||||
<strong>{v}</strong>
|
||||
</div>
|
||||
))}
|
||||
{(m || canManage()) && (
|
||||
<div className="about-actions">
|
||||
{m && (
|
||||
<Button variant="outline" size="sm" icon="info" onClick={() => openDialog({ kind: 'info', item })}>
|
||||
Media info
|
||||
</Button>
|
||||
)}
|
||||
{canManage() && (
|
||||
<Button variant="outline" size="sm" icon="edit" onClick={() => openDialog({ kind: 'edit', item })}>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Movie ——————————————————————————————————————————————————————————
|
||||
|
||||
function MovieDetail({ item }: { item: Item }) {
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
return (
|
||||
<div className="detail movie">
|
||||
<DetailHero item={item}>
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? `Resume · ${remaining(item)}` : 'Play'}
|
||||
</Button>
|
||||
{resume && (
|
||||
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
|
||||
From beginning
|
||||
</Button>
|
||||
)}
|
||||
<TrailerButton item={item} />
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{resume && (
|
||||
<div className="detail-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${(item.viewOffset / item.duration) * 100}%` }} />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="detail-tech">{technicalLine(item.media[0])}</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Shows and seasons ————————————————————————————————————————————
|
||||
|
||||
function EpisodeRow({ ep }: { ep: Item }) {
|
||||
const server = useServer();
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(ep, percent);
|
||||
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
|
||||
return (
|
||||
<div
|
||||
className="episode-row"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => openItem(ep)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && openItem(ep)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY });
|
||||
}}
|
||||
>
|
||||
<div className="episode-index">{ep.index || '–'}</div>
|
||||
<div className="episode-pic">
|
||||
<Artwork src={server.image(ep.thumb, 320, 180)} />
|
||||
<button
|
||||
className="episode-play"
|
||||
aria-label={`Play ${ep.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
playWithVersion(ep);
|
||||
}}
|
||||
>
|
||||
<Icon name="play" size={18} />
|
||||
</button>
|
||||
{p > 0 && !watched && (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${p * 100}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="episode-text">
|
||||
<h3>
|
||||
{ep.title}
|
||||
{watched && <Icon name="check" size={15} className="episode-watched" />}
|
||||
</h3>
|
||||
<div className="episode-meta">
|
||||
{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
{ep.summary && <p>{ep.summary}</p>}
|
||||
</div>
|
||||
<button
|
||||
className="icon-btn episode-more"
|
||||
aria-label="More"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openMenu(itemMenu(ep), e.currentTarget);
|
||||
}}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) {
|
||||
const saved = useRouter((s) => s.current.state.season as string | undefined);
|
||||
const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id);
|
||||
useEffect(() => {
|
||||
if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id);
|
||||
}, [seasons, initialSeason]);
|
||||
const episodes = useChildren(seasonId);
|
||||
const season = seasons.find((s) => s.id === seasonId);
|
||||
if (!seasons.length) return null;
|
||||
return (
|
||||
<section className="episodes">
|
||||
<div className="episodes-head">
|
||||
<h2>Episodes</h2>
|
||||
{showPicker && seasons.length > 1 && (
|
||||
<Select
|
||||
value={seasonId!}
|
||||
label="Season"
|
||||
options={seasons.map((s) => ({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
|
||||
onChange={(v) => {
|
||||
setSeasonId(v);
|
||||
useRouter.getState().setState({ season: v });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{season && (
|
||||
<span className="episodes-sub">
|
||||
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{season?.summary && <p className="season-summary">{season.summary}</p>}
|
||||
<div className="episode-list">
|
||||
{episodes.isLoading && <PageLoader />}
|
||||
{episodes.data?.map((ep) => <EpisodeRow key={ep.id} ep={ep} />)}
|
||||
{episodes.data && !episodes.data.length && <EmptyState icon="tv" title="No episodes" />}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ShowDetail({ item }: { item: Item }) {
|
||||
const seasons = useChildren(item.id);
|
||||
const server = useServer();
|
||||
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), { staleTime: 15_000 });
|
||||
const nextEp = next.data;
|
||||
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
||||
void server;
|
||||
return (
|
||||
<div className="detail show">
|
||||
<DetailHero item={item}>
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => (nextEp ? playWithVersion(nextEp) : playItem(item))}>
|
||||
{playLabel}
|
||||
</Button>
|
||||
<Button variant="ghost" icon="shuffle" onClick={() => shuffleItem(item)}>
|
||||
Shuffle
|
||||
</Button>
|
||||
<TrailerButton item={item} />
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{nextEp && (
|
||||
<div className="detail-tech">
|
||||
Up next: {episodeLabel(nextEp)} · {nextEp.title}
|
||||
</div>
|
||||
)}
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{seasonList.length > 1 && (
|
||||
<Shelf title="Seasons">
|
||||
{seasonList.map((s) => (
|
||||
<PosterCard key={s.id} item={s} caption="episodes" />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeasonDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.parentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
|
||||
const episodes = useChildren(item.id);
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
|
||||
const showItem = show.data;
|
||||
return (
|
||||
<div className="detail season">
|
||||
<DetailHero
|
||||
item={item}
|
||||
backdropItem={showItem ?? item}
|
||||
title={
|
||||
<>
|
||||
{showItem ? (
|
||||
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
|
||||
<TitleArt item={showItem} maxWidth={340} maxHeight={96} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<h2 className="title-text small">{item.parentTitle}</h2>
|
||||
)}
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
||||
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
|
||||
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
|
||||
</Button>
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
|
||||
{showItem && <CastRow item={showItem} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EpisodeDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.grandparentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
const showItem = show.data;
|
||||
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
|
||||
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
|
||||
const ordered = useMemo(() => [...others.slice(startIndex), ...others.slice(0, startIndex)], [siblings.data, item.id]);
|
||||
return (
|
||||
<div className="detail episode">
|
||||
<DetailHero
|
||||
item={item}
|
||||
backdropItem={{ ...item, art: item.thumb, grandparentArt: item.thumb, ultraBlur: showItem?.ultraBlur ?? item.ultraBlur }}
|
||||
title={
|
||||
<>
|
||||
{showItem ? (
|
||||
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
|
||||
<TitleArt item={showItem} maxWidth={300} maxHeight={84} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<h2 className="title-text small">{item.grandparentTitle}</h2>
|
||||
)}
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? `Resume · ${remaining(item)}` : 'Play'}
|
||||
</Button>
|
||||
{resume && (
|
||||
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
|
||||
From beginning
|
||||
</Button>
|
||||
)}
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
<div className="detail-tech">{technicalLine(item.media[0])}</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{ordered.length > 0 && (
|
||||
<Shelf title={`More from ${item.parentTitle || `Season ${item.parentIndex}`}`} kind="landscape" onViewAll={() => navigate({ name: 'item', id: item.parentId })}>
|
||||
{ordered.map((e) => (
|
||||
<LandscapeCard key={e.id} item={e} episodeStyle />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
<CastRow item={item.roles.length ? item : (showItem ?? item)} title={item.roles.length ? 'Cast & Guest Stars' : 'Cast & Crew'} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Collections ——————————————————————————————————————————————————
|
||||
|
||||
function CollectionDetail({ item }: { item: Item }) {
|
||||
const members = useServerQuery(['collectionItems', item.id], (s) => api.collectionItems(s, item.id));
|
||||
const list = members.data ?? [];
|
||||
const backdropItem = item.art ? item : list.find((m) => m.art);
|
||||
return (
|
||||
<div className="detail collection">
|
||||
<DetailHero item={item} backdropItem={backdropItem} title={<h1 className="title-text">{item.title}</h1>}>
|
||||
<div className="facts">
|
||||
<span className="fact">{list.length ? `${list.length} titles` : 'Collection'}</span>
|
||||
{item.contentRating && <span className="badge">{item.contentRating}</span>}
|
||||
</div>
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!list.length} onClick={() => list[0] && playWithVersion(list.find((m) => !isWatched(m)) ?? list[0])}>
|
||||
Play
|
||||
</Button>
|
||||
<MoreButton item={item} />
|
||||
</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
{members.isLoading && <PageLoader />}
|
||||
<div className="poster-grid auto">
|
||||
{list.map((m) => (
|
||||
<PosterCard key={m.id} item={m} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
328
src/screens/LibraryBrowser.tsx
Normal file
328
src/screens/LibraryBrowser.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item, Section } from '../plex/types';
|
||||
import { queryClient, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { SectionKind } from '../app/router';
|
||||
import { PosterCard } from '../ui/media';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { EmptyState, ErrorState, IconButton, PageLoader, Select, Spinner } from '../ui/primitives';
|
||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||
|
||||
const PAGE = 120;
|
||||
const CARD_WIDTH = { compact: 148, comfortable: 182, large: 228 } as const;
|
||||
const BOOLEAN_LABELS: Record<string, string> = {
|
||||
unwatched: 'Unwatched',
|
||||
inProgress: 'In progress',
|
||||
hdr: 'HDR',
|
||||
dovi: 'Dolby Vision',
|
||||
hdr10plus: 'HDR10+',
|
||||
atmos: 'Dolby Atmos',
|
||||
unmatched: 'Unmatched',
|
||||
};
|
||||
const QUICK_FILTERS = ['genre', 'year', 'decade', 'contentRating', 'resolution', 'collection', 'studio', 'country', 'audioLanguage', 'subtitleLanguage', 'label', 'editionTitle', 'network'];
|
||||
|
||||
function useDebounced<T>(value: T, ms: number) {
|
||||
const [v, setV] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setV(value), ms);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, ms]);
|
||||
return v;
|
||||
}
|
||||
|
||||
export function LibraryBrowser({ section, kind }: { section: Section; kind: SectionKind }) {
|
||||
const server = useServer();
|
||||
const type = kind === 'movie' ? 1 : 2;
|
||||
const views = useSettings((s) => s.libraryViews);
|
||||
const setSetting = useSettings((s) => s.set);
|
||||
const posterSize = useSettings((s) => s.posterSize);
|
||||
const view = views[section.id] ?? { sort: 'titleSort:asc', filters: {} };
|
||||
const [query, setQuery] = useState('');
|
||||
const title = useDebounced(query.trim(), 300);
|
||||
const meta = useServerQuery(['libraryMeta', section.id, type], (s) => api.libraryMeta(s, section.id, type), { staleTime: 30 * 60_000 });
|
||||
|
||||
const saveView = (next: Partial<typeof view>) => setSetting('libraryViews', { ...views, [section.id]: { ...view, ...next } });
|
||||
const [sortKey, sortDir] = view.sort.split(':') as [string, 'asc' | 'desc'];
|
||||
const sortTitle = meta.data?.sorts.find((s) => s.key === sortKey)?.title ?? 'Title';
|
||||
|
||||
const filterLabel = (filter: string) => meta.data?.filters.find((f) => f.filter === filter)?.title ?? BOOLEAN_LABELS[filter] ?? filter;
|
||||
|
||||
// Option titles for active filter chips (values are Plex keys).
|
||||
const [chipTitles, setChipTitles] = useState<Record<string, string>>({});
|
||||
|
||||
const loadOptions = async (f: { filter: string; key: string }) =>
|
||||
queryClient.fetchQuery({
|
||||
queryKey: [server.machineId, 'filterOptions', f.key, type],
|
||||
queryFn: () => api.filterOptions(server, f.key, type),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
|
||||
const openFilters = async (anchor: HTMLElement) => {
|
||||
const filters = meta.data?.filters ?? [];
|
||||
const bools = filters.filter((f) => f.type === 'boolean');
|
||||
const strings = filters.filter((f) => f.type !== 'boolean' && QUICK_FILTERS.includes(f.filter));
|
||||
const options = await Promise.all(strings.map((f) => loadOptions(f).catch(() => [])));
|
||||
const items: MenuItem[] = [
|
||||
...bools.map((f) => ({
|
||||
label: BOOLEAN_LABELS[f.filter] ?? f.title,
|
||||
checked: view.filters[f.filter] === '1',
|
||||
onSelect: () => {
|
||||
const next = { ...view.filters };
|
||||
if (next[f.filter] === '1') delete next[f.filter];
|
||||
else next[f.filter] = '1';
|
||||
saveView({ filters: next });
|
||||
},
|
||||
})),
|
||||
{ divider: true },
|
||||
...strings
|
||||
.map((f, i): MenuItem => ({
|
||||
label: f.title,
|
||||
hint: view.filters[f.filter] ? chipTitles[`${f.filter}=${view.filters[f.filter]}`] ?? '1 selected' : undefined,
|
||||
submenu: options[i].length
|
||||
? options[i].slice(0, 400).map((o) => ({
|
||||
label: o.title,
|
||||
checked: view.filters[f.filter] === o.key,
|
||||
onSelect: () => {
|
||||
const next = { ...view.filters };
|
||||
if (next[f.filter] === o.key) delete next[f.filter];
|
||||
else next[f.filter] = o.key;
|
||||
setChipTitles((c) => ({ ...c, [`${f.filter}=${o.key}`]: o.title }));
|
||||
saveView({ filters: next });
|
||||
},
|
||||
}))
|
||||
: [{ label: 'No options', disabled: true }],
|
||||
}))
|
||||
.filter((m) => m.submenu!.length),
|
||||
];
|
||||
openMenu(items, anchor, { minWidth: 230 });
|
||||
};
|
||||
|
||||
// Resolve chip titles for remembered filters.
|
||||
useEffect(() => {
|
||||
const filters = meta.data?.filters ?? [];
|
||||
for (const [k, v] of Object.entries(view.filters)) {
|
||||
const f = filters.find((x) => x.filter === k);
|
||||
if (!f || f.type === 'boolean' || chipTitles[`${k}=${v}`]) continue;
|
||||
loadOptions(f)
|
||||
.then((opts) => {
|
||||
const o = opts.find((x) => x.key === v);
|
||||
if (o) setChipTitles((c) => ({ ...c, [`${k}=${v}`]: o.title }));
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}, [meta.data, view.filters]);
|
||||
|
||||
if (meta.isError && !meta.data) return <ErrorState error={meta.error} onRetry={() => meta.refetch()} />;
|
||||
|
||||
const activeFilters = Object.entries(view.filters);
|
||||
return (
|
||||
<div className="library">
|
||||
<div className="lib-toolbar">
|
||||
<div className="lib-search">
|
||||
<Icon name="search" size={16} />
|
||||
<input value={query} placeholder={`Search ${section.title}`} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === 'Escape' && (e.stopPropagation(), setQuery(''))} />
|
||||
{query && (
|
||||
<button aria-label="Clear" onClick={() => setQuery('')}>
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button className="select" onClick={(e) => openFilters(e.currentTarget)} disabled={!meta.data}>
|
||||
<Icon name="sliders" size={15} />
|
||||
<span className="select-value">Filter{activeFilters.length ? ` · ${activeFilters.length}` : ''}</span>
|
||||
</button>
|
||||
<div className="sort-group">
|
||||
<Select
|
||||
value={sortKey}
|
||||
prefix="Sort"
|
||||
label="Sort by"
|
||||
options={(meta.data?.sorts ?? [{ key: 'titleSort', title: 'Title', defaultDirection: 'asc' }]).map((s) => ({ value: s.key, label: s.title }))}
|
||||
onChange={(k) => {
|
||||
const s = meta.data?.sorts.find((x) => x.key === k);
|
||||
saveView({ sort: `${k}:${s?.defaultDirection ?? 'asc'}` });
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon={sortDir === 'asc' ? 'chevronUp' : 'chevronDown'}
|
||||
label={sortDir === 'asc' ? 'Ascending' : 'Descending'}
|
||||
className="sort-dir"
|
||||
onClick={() => saveView({ sort: `${sortKey}:${sortDir === 'asc' ? 'desc' : 'asc'}` })}
|
||||
/>
|
||||
</div>
|
||||
<div className="toolbar-spacer" />
|
||||
<div className="density" role="group" aria-label="Poster size">
|
||||
{(['compact', 'comfortable', 'large'] as const).map((s, i) => (
|
||||
<button key={s} className={posterSize === s ? 'on' : ''} aria-label={`${s} posters`} title={`${s[0].toUpperCase()}${s.slice(1)} posters`} onClick={() => setSetting('posterSize', s)}>
|
||||
<span style={{ width: 8 + i * 3, height: 11 + i * 4 }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{activeFilters.length > 0 && (
|
||||
<div className="filter-chips">
|
||||
{activeFilters.map(([k, v]) => (
|
||||
<button
|
||||
key={k}
|
||||
className="chip"
|
||||
onClick={() => {
|
||||
const next = { ...view.filters };
|
||||
delete next[k];
|
||||
saveView({ filters: next });
|
||||
}}
|
||||
>
|
||||
{v === '1' && BOOLEAN_LABELS[k] ? BOOLEAN_LABELS[k] : `${filterLabel(k)}: ${chipTitles[`${k}=${v}`] ?? v}`}
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
))}
|
||||
<button className="btn text" onClick={() => saveView({ filters: {} })}>
|
||||
Clear all
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<LibraryGrid key={`${section.id}|${view.sort}|${JSON.stringify(view.filters)}|${title}`} section={section} type={type} sort={view.sort} filters={view.filters} title={title} sortTitle={sortTitle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { section: Section; type: number; sort: string; filters: Record<string, string>; title: string; sortTitle: string }) {
|
||||
const server = useServer();
|
||||
const posterSize = useSettings((s) => s.posterSize);
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(0);
|
||||
const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);
|
||||
const [pages, setPages] = useState<Record<number, Item[]>>({});
|
||||
const [total, setTotal] = useState<number | null>(null);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const inflight = useRef(new Set<number>());
|
||||
const params = { type, sort, filters, title };
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = gridRef.current;
|
||||
if (!el) return;
|
||||
setScrollEl(el.closest('.main-scroll') as HTMLElement);
|
||||
const ro = new ResizeObserver(() => setWidth(el.clientWidth));
|
||||
ro.observe(el);
|
||||
setWidth(el.clientWidth);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const loadPage = useCallback(
|
||||
async (p: number) => {
|
||||
if (inflight.current.has(p)) return;
|
||||
inflight.current.add(p);
|
||||
try {
|
||||
const page = await queryClient.fetchQuery({
|
||||
queryKey: [server.machineId, 'libraryPage', section.id, params, p],
|
||||
queryFn: () => api.libraryPage(server, section.id, { ...params, start: p * PAGE, size: PAGE }),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
setPages((prev) => ({ ...prev, [p]: page.items }));
|
||||
setTotal(page.total);
|
||||
} catch (e) {
|
||||
setError(e);
|
||||
} finally {
|
||||
inflight.current.delete(p);
|
||||
}
|
||||
},
|
||||
[server, section.id, JSON.stringify(params)],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loadPage(0);
|
||||
}, [loadPage]);
|
||||
|
||||
const gap = 16;
|
||||
const target = CARD_WIDTH[posterSize];
|
||||
const cols = Math.max(2, Math.floor((width + gap) / (target + gap)));
|
||||
const cardW = width ? (width - gap * (cols - 1)) / cols : target;
|
||||
const rowH = cardW * 1.5 + 52 + 22;
|
||||
const rows = total === null ? 0 : Math.ceil(total / cols);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows,
|
||||
getScrollElement: () => scrollEl,
|
||||
estimateSize: () => rowH,
|
||||
overscan: 3,
|
||||
scrollMargin: gridRef.current?.offsetTop ?? 0,
|
||||
// Keep jump targets clear of the sticky top bar and toolbar.
|
||||
scrollPaddingStart: 150,
|
||||
});
|
||||
useEffect(() => virtualizer.measure(), [rowH, cols]);
|
||||
|
||||
const vrows = virtualizer.getVirtualItems();
|
||||
useEffect(() => {
|
||||
if (!vrows.length) return;
|
||||
const first = vrows[0].index * cols;
|
||||
const last = (vrows[vrows.length - 1].index + 1) * cols;
|
||||
for (let p = Math.floor(first / PAGE); p <= Math.floor(Math.min(last, (total ?? 1) - 1) / PAGE); p++) if (!pages[p]) loadPage(p);
|
||||
}, [vrows.map((r) => r.index).join(','), cols, total]);
|
||||
|
||||
const itemAt = (i: number) => pages[Math.floor(i / PAGE)]?.[i % PAGE];
|
||||
|
||||
// A–Z jumps for title order.
|
||||
const alpha = sort.startsWith('titleSort') && !title;
|
||||
const letters = useServerQuery(['firstCharacter', section.id, type, filters], (s) => api.firstCharacters(s, section.id, { type, ...filters }), { enabled: alpha, staleTime: 120_000 });
|
||||
const jump = (char: string) => {
|
||||
if (!letters.data) return;
|
||||
const list = sort.endsWith(':desc') ? [...letters.data].reverse() : letters.data;
|
||||
let offset = 0;
|
||||
for (const l of list) {
|
||||
if (l.title === char) break;
|
||||
offset += l.size;
|
||||
}
|
||||
virtualizer.scrollToIndex(Math.floor(offset / cols), { align: 'start' });
|
||||
};
|
||||
|
||||
if (error && total === null) return <ErrorState error={error} onRetry={() => (setError(null), loadPage(0))} />;
|
||||
return (
|
||||
<div className="library-body">
|
||||
<div className="grid-count">
|
||||
{total === null ? <Spinner size={14} /> : `${total.toLocaleString()} ${total === 1 ? 'title' : 'titles'}`}
|
||||
{total !== null && sortTitle && <span className="dim"> · by {sortTitle.toLowerCase()}</span>}
|
||||
</div>
|
||||
<div className="lib-grid-wrap">
|
||||
<div ref={gridRef} className="lib-grid" style={{ height: virtualizer.getTotalSize() }}>
|
||||
{total === 0 && (
|
||||
<EmptyState icon="search" title="Nothing matches">
|
||||
Try a different search or remove a filter.
|
||||
</EmptyState>
|
||||
)}
|
||||
{vrows.map((row) => (
|
||||
<div
|
||||
key={row.key}
|
||||
className="lib-row"
|
||||
style={{ transform: `translateY(${row.start - virtualizer.options.scrollMargin}px)`, gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap }}
|
||||
>
|
||||
{Array.from({ length: cols }, (_, c) => {
|
||||
const i = row.index * cols + c;
|
||||
if (total !== null && i >= total) return <div key={c} />;
|
||||
const item = itemAt(i);
|
||||
return item ? (
|
||||
<PosterCard key={item.id} item={item} />
|
||||
) : (
|
||||
<div key={c} className="card poster placeholder">
|
||||
<div className="card-cover skeleton" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{alpha && letters.data && letters.data.length > 3 && (
|
||||
<div className="alpha-rail" aria-label="Jump to letter">
|
||||
{letters.data.map((l) => (
|
||||
<button key={l.title} onClick={() => jump(l.title)} title={`${l.title} · ${l.size}`}>
|
||||
{l.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{total === null && <PageLoader />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
61
src/screens/Person.tsx
Normal file
61
src/screens/Person.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import * as api from '../plex/api';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { PosterCard } from '../ui/media';
|
||||
import { Artwork, EmptyState, ErrorState, PageLoader } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
export default function Person({ id, title, thumb }: { id: string; title: string; thumb?: string }) {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const titles = useServerQuery(['person', id], (s) => api.personTitles(s, id, sections.data ?? []), { enabled: !!sections.data });
|
||||
const list = titles.data ?? [];
|
||||
const movies = list.filter((i) => i.type === 'movie');
|
||||
const shows = list.filter((i) => i.type === 'show');
|
||||
const years = list.map((i) => i.year).filter(Boolean);
|
||||
return (
|
||||
<div className="person-page page-pad top">
|
||||
<header className="person-header">
|
||||
<div className="person-portrait">{thumb ? <Artwork src={server.image(thumb, 240, 240)} /> : <Icon name="person" size={52} />}</div>
|
||||
<div>
|
||||
<div className="micro">Filmography in your library</div>
|
||||
<h1>{title}</h1>
|
||||
{titles.data && (
|
||||
<p className="muted">
|
||||
{[movies.length ? `${movies.length} movie${movies.length === 1 ? '' : 's'}` : '', shows.length ? `${shows.length} show${shows.length === 1 ? '' : 's'}` : '', years.length ? `${Math.min(...years)}–${Math.max(...years)}` : '']
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{titles.isError && <ErrorState error={titles.error} onRetry={() => titles.refetch()} />}
|
||||
{titles.isLoading && <PageLoader />}
|
||||
{titles.data && !list.length && (
|
||||
<EmptyState icon="person" title="Nothing in your library">
|
||||
{title} doesn’t appear in any movie or show on this server.
|
||||
</EmptyState>
|
||||
)}
|
||||
{movies.length > 0 && (
|
||||
<section className="person-section">
|
||||
<h2>Movies</h2>
|
||||
<div className="poster-grid auto">
|
||||
{movies.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{shows.length > 0 && (
|
||||
<section className="person-section">
|
||||
<h2>TV Shows</h2>
|
||||
<div className="poster-grid auto">
|
||||
{shows.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
191
src/screens/Search.tsx
Normal file
191
src/screens/Search.tsx
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useServerQuery } from '../app/queries';
|
||||
import { navigate, useRouter } from '../app/router';
|
||||
import type { Item } from '../plex/types';
|
||||
import { LandscapeCard, PersonCard, PosterCard, Shelf } from '../ui/media';
|
||||
import { EmptyState, ErrorState, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
const RECENT_KEY = 'kaleido.recentSearches';
|
||||
const loadRecent = (): string[] => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
/** Plex search ranks per hub; float exact and prefix title matches to the top. */
|
||||
function rank(query: string, items: Item[]): Item[] {
|
||||
const q = query.toLowerCase();
|
||||
const score = (i: Item) => {
|
||||
const t = (i.type === 'episode' ? i.title : i.title).toLowerCase();
|
||||
if (t === q) return 0;
|
||||
if (t.startsWith(q)) return 1;
|
||||
if (t.split(/\W+/).some((w) => w.startsWith(q))) return 2;
|
||||
return 3;
|
||||
};
|
||||
return [...items].sort((a, b) => score(a) - score(b));
|
||||
}
|
||||
|
||||
export default function Search({ initial }: { initial?: string }) {
|
||||
const saved = useRouter((s) => s.current.state.query as string | undefined);
|
||||
const [query, setQuery] = useState(saved ?? initial ?? '');
|
||||
const [debounced, setDebounced] = useState(query);
|
||||
const [recent, setRecent] = useState(loadRecent);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
input.current?.focus();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebounced(query.trim()), 250);
|
||||
useRouter.getState().setState({ query });
|
||||
return () => clearTimeout(t);
|
||||
}, [query]);
|
||||
|
||||
const results = useServerQuery(['search', debounced], (s) => api.search(s, debounced), { enabled: debounced.length > 0, staleTime: 60_000 });
|
||||
const recentlyAdded = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), { enabled: !debounced });
|
||||
|
||||
const remember = (q: string) => {
|
||||
const next = [q, ...recent.filter((r) => r.toLowerCase() !== q.toLowerCase())].slice(0, 8);
|
||||
setRecent(next);
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify(next));
|
||||
};
|
||||
|
||||
const hubs = results.data?.hubs ?? [];
|
||||
const all = hubs.flatMap((h) => h.items);
|
||||
const movies = rank(debounced, all.filter((i) => i.type === 'movie'));
|
||||
const shows = rank(debounced, all.filter((i) => i.type === 'show'));
|
||||
const episodes = rank(debounced, all.filter((i) => i.type === 'episode'));
|
||||
const collections = all.filter((i) => i.type === 'collection');
|
||||
const people = results.data?.people ?? [];
|
||||
const top = rank(debounced, [...movies, ...shows]).slice(0, 6);
|
||||
const inTop = new Set(top.map((i) => i.id));
|
||||
const moreMovies = movies.filter((i) => !inTop.has(i.id));
|
||||
const moreShows = shows.filter((i) => !inTop.has(i.id));
|
||||
|
||||
return (
|
||||
<div className="search-page page-pad top">
|
||||
<div className="search-hero">
|
||||
<div className="search-field">
|
||||
<Icon name="search" size={22} />
|
||||
<input
|
||||
ref={input}
|
||||
value={query}
|
||||
placeholder="Search movies, shows, episodes and people"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && query.trim()) remember(query.trim());
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
if (query) setQuery('');
|
||||
else useRouter.getState().back();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{results.isFetching && <Spinner size={18} />}
|
||||
{query && (
|
||||
<button className="icon-btn" aria-label="Clear search" onClick={() => (setQuery(''), input.current?.focus())}>
|
||||
<Icon name="x" size={17} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!debounced && (
|
||||
<div className="search-idle">
|
||||
{recent.length > 0 && (
|
||||
<div className="recent-searches">
|
||||
<h3>Recent searches</h3>
|
||||
<div className="chips">
|
||||
{recent.map((r) => (
|
||||
<button key={r} className="chip" onClick={() => setQuery(r)}>
|
||||
<Icon name="clock" size={13} />
|
||||
{r}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="btn text"
|
||||
onClick={() => {
|
||||
setRecent([]);
|
||||
localStorage.removeItem(RECENT_KEY);
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{recentlyAdded.data
|
||||
?.filter((h) => /recent/.test(h.id))
|
||||
.slice(0, 2)
|
||||
.map((h) => (
|
||||
<Shelf key={h.id} title={h.title} className="flush">
|
||||
{h.items.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{debounced && results.isError && <ErrorState error={results.error} onRetry={() => results.refetch()} />}
|
||||
{debounced && results.data && !all.length && !people.length && (
|
||||
<EmptyState icon="search" title={`No results for “${debounced}”`}>
|
||||
Check the spelling, or search for an actor, director or episode title.
|
||||
</EmptyState>
|
||||
)}
|
||||
{debounced && results.data && (
|
||||
<div className="search-results" onClick={() => remember(debounced)}>
|
||||
{top.length > 0 && (
|
||||
<section className="search-top">
|
||||
<h3>Top results</h3>
|
||||
<div className="poster-grid auto">
|
||||
{top.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{moreMovies.length > 0 && (
|
||||
<Shelf title="More movies" className="flush">
|
||||
{moreMovies.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{moreShows.length > 0 && (
|
||||
<Shelf title="More TV shows" className="flush">
|
||||
{moreShows.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{episodes.length > 0 && (
|
||||
<Shelf title="Episodes" kind="landscape" className="flush">
|
||||
{episodes.map((i) => (
|
||||
<LandscapeCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{people.length > 0 && (
|
||||
<Shelf title="People" kind="people" className="flush">
|
||||
{people.map((p) => (
|
||||
<PersonCard key={p.id} name={p.tag} thumb={p.thumb} onClick={() => navigate({ name: 'person', id: p.id, title: p.tag, thumb: p.thumb })} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{collections.length > 0 && (
|
||||
<Shelf title="Collections" className="flush">
|
||||
{collections.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
111
src/screens/Section.tsx
Normal file
111
src/screens/Section.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { useMemo } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useSectionFor, useServerQuery } from '../app/queries';
|
||||
import { navigate, type SectionKind, type SectionTab } from '../app/router';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { Section } from '../plex/types';
|
||||
import { Hero } from '../ui/Hero';
|
||||
import { HubShelf, PosterCard } from '../ui/media';
|
||||
import { EmptyState, ErrorState, PageLoader, Select } from '../ui/primitives';
|
||||
import { buildFeatures, HIDDEN_HUBS, recentSeasons } from './discover';
|
||||
import { LibraryBrowser } from './LibraryBrowser';
|
||||
|
||||
const TABS: { id: SectionTab; label: string }[] = [
|
||||
{ id: 'discover', label: 'Discover' },
|
||||
{ id: 'library', label: 'Library' },
|
||||
{ id: 'collections', label: 'Collections' },
|
||||
];
|
||||
|
||||
function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind; tab: SectionTab; section: Section; all: Section[]; overlay: boolean }) {
|
||||
const set = useSettings((s) => s.set);
|
||||
return (
|
||||
<div className={`section-header${overlay ? ' overlay' : ''}`}>
|
||||
<h1>{kind === 'movie' ? 'Movies' : 'TV Shows'}</h1>
|
||||
<nav className="section-tabs" role="tablist">
|
||||
{TABS.map((t) => (
|
||||
<button key={t.id} role="tab" aria-selected={t.id === tab} className={t.id === tab ? 'active' : ''} onClick={() => navigate({ name: 'section', kind, tab: t.id }, { replace: true })}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
{all.length > 1 && (
|
||||
<Select
|
||||
className="section-picker"
|
||||
value={section.id}
|
||||
label="Library"
|
||||
options={all.map((s) => ({ value: s.id, label: s.title }))}
|
||||
onChange={(v) => set(kind === 'movie' ? 'movieSection' : 'showSection', v)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
|
||||
const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id));
|
||||
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), { staleTime: 15_000 });
|
||||
const seasons = useServerQuery(['recentSeasons', section.id], (s) => recentSeasons(s, section.id), { enabled: kind === 'show', staleTime: 120_000 });
|
||||
const features = useMemo(() => buildFeatures(hubs.data ?? [], 7, kind === 'movie' ? 1 : 2), [hubs.data, kind]);
|
||||
|
||||
if (hubs.isError && !hubs.data) return <ErrorState error={hubs.error} onRetry={() => hubs.refetch()} />;
|
||||
if (!hubs.data) return <PageLoader />;
|
||||
const rest = hubs.data.filter((h) => !HIDDEN_HUBS.test(h.id));
|
||||
// TV: episodes lead; redundant episode hubs are skipped when they repeat Continue Watching.
|
||||
const cwIds = new Set((cw.data ?? []).map((i) => i.id));
|
||||
const shelves = rest.filter((h) => !(h.items.length && h.items.every((i) => cwIds.has(i.id))));
|
||||
return (
|
||||
<>
|
||||
<Hero features={features} variant="section" />
|
||||
<div className="shelves over-hero">
|
||||
<HubShelf title={kind === 'show' ? 'Next Episodes' : 'Continue Watching'} items={cw.data ?? []} continueWatching />
|
||||
{kind === 'show' && <HubShelf title="New Seasons" items={seasons.data ?? []} landscape={false} />}
|
||||
{shelves.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title.replace(/ in (Movies|TV Shows)$/, '')} items={h.items} onViewAll={h.more || h.key.includes('/all') ? () => navigate({ name: 'hub', key: h.key, title: h.title }) : undefined} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Collections({ section }: { section: Section }) {
|
||||
const q = useServerQuery(['collections', section.id], (s) => api.collections(s, section.id));
|
||||
if (q.isError) return <ErrorState error={q.error} onRetry={() => q.refetch()} />;
|
||||
if (!q.data) return <PageLoader />;
|
||||
if (!q.data.length)
|
||||
return (
|
||||
<EmptyState icon="collection" title="No collections yet">
|
||||
Collections created in Plex for {section.title} appear here.
|
||||
</EmptyState>
|
||||
);
|
||||
return (
|
||||
<div className="page-pad">
|
||||
<div className="grid-count">{q.data.length.toLocaleString()} collections</div>
|
||||
<div className="poster-grid auto">
|
||||
{q.data.map((c) => (
|
||||
<PosterCard key={c.id} item={c} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SectionScreen({ kind, tab }: { kind: SectionKind; tab: SectionTab }) {
|
||||
const { section, all, loading } = useSectionFor(kind);
|
||||
if (loading) return <PageLoader />;
|
||||
if (!section)
|
||||
return (
|
||||
<div className="page-pad top">
|
||||
<EmptyState icon={kind === 'movie' ? 'film' : 'tv'} title={`No ${kind === 'movie' ? 'movie' : 'TV'} libraries`}>
|
||||
This server has no {kind === 'movie' ? 'movie' : 'TV show'} libraries you can access.
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={`section-screen tab-${tab}`} key={section.id}>
|
||||
<SectionHeader kind={kind} tab={tab} section={section} all={all} overlay={tab === 'discover'} />
|
||||
{tab === 'discover' && <Discover kind={kind} section={section} />}
|
||||
{tab === 'library' && <LibraryBrowser section={section} kind={kind} />}
|
||||
{tab === 'collections' && <Collections section={section} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
src/screens/ServerPicker.tsx
Normal file
102
src/screens/ServerPicker.tsx
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSession } from '../app/session';
|
||||
import type { ServerResource } from '../plex/types';
|
||||
import { Button, KaleidoMark, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowDrag } from './WindowDrag';
|
||||
import { useRouter } from '../app/router';
|
||||
|
||||
export function ServerPicker() {
|
||||
const resources = useSession((s) => s.resources);
|
||||
const status = useSession((s) => s.status);
|
||||
const error = useSession((s) => s.error);
|
||||
const user = useSession((s) => s.user);
|
||||
const current = useSession((s) => s.server);
|
||||
const choose = useSession((s) => s.chooseServer);
|
||||
const refresh = useSession((s) => s.refreshResources);
|
||||
const signOut = useSession((s) => s.signOut);
|
||||
const [pending, setPending] = useState('');
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!resources.length) {
|
||||
setRefreshing(true);
|
||||
refresh()
|
||||
.catch(() => {})
|
||||
.finally(() => setRefreshing(false));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const pick = async (r: ServerResource) => {
|
||||
setPending(r.id);
|
||||
await choose(r);
|
||||
setPending('');
|
||||
useRouter.getState().reset({ name: 'home' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<WindowDrag />
|
||||
<div className="auth-backdrop" />
|
||||
<div className="auth-card wide">
|
||||
<div className="auth-brand">
|
||||
<KaleidoMark size={40} />
|
||||
<span>KALEIDO</span>
|
||||
</div>
|
||||
<h1>Choose a server</h1>
|
||||
<p className="auth-lede">{user ? `Signed in as ${user.title}.` : 'Pick the Plex Media Server to browse.'}</p>
|
||||
<div className="server-list">
|
||||
{refreshing && !resources.length && (
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Finding your servers…
|
||||
</div>
|
||||
)}
|
||||
{resources.map((r) => (
|
||||
<button key={r.id} className={`server-row${current?.machineId === r.id ? ' current' : ''}`} onClick={() => pick(r)} disabled={!!pending}>
|
||||
<div className="server-glyph">
|
||||
<Icon name="server" size={20} />
|
||||
</div>
|
||||
<div className="server-text">
|
||||
<strong>{r.name}</strong>
|
||||
<small>
|
||||
{r.owned ? 'Your server' : `Shared by ${r.sourceTitle || 'a friend'}`} · {r.platform || 'Plex Media Server'}
|
||||
{r.productVersion ? ` · ${r.productVersion.split('-')[0]}` : ''}
|
||||
</small>
|
||||
</div>
|
||||
<span className={`presence${r.presence ? ' on' : ''}`}>{r.presence ? 'Online' : 'Offline'}</span>
|
||||
{pending === r.id && status === 'connecting' ? <Spinner size={18} /> : <Icon name="next" size={18} className="dim" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="auth-error">
|
||||
<Icon name="alert" size={16} /> {error}
|
||||
</div>
|
||||
)}
|
||||
<div className="auth-actions spread">
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="refresh"
|
||||
busy={refreshing}
|
||||
onClick={() => {
|
||||
setRefreshing(true);
|
||||
refresh()
|
||||
.catch(() => {})
|
||||
.finally(() => setRefreshing(false));
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</Button>
|
||||
{current && (
|
||||
<Button variant="ghost" onClick={() => useSession.setState({ status: 'ready', error: '' })}>
|
||||
Keep {current.name}
|
||||
</Button>
|
||||
)}
|
||||
<button className="auth-link" onClick={signOut}>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
193
src/screens/SignIn.tsx
Normal file
193
src/screens/SignIn.tsx
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { authUrl, checkPin, createPin, type Pin } from '../plex/account';
|
||||
import { useSession } from '../app/session';
|
||||
import { openExternal } from '../platform/native';
|
||||
import { Button, KaleidoMark, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowDrag } from './WindowDrag';
|
||||
|
||||
type Mode = 'start' | 'browser' | 'code' | 'manual';
|
||||
|
||||
export function SignIn() {
|
||||
const completeSignIn = useSession((s) => s.completeSignIn);
|
||||
const connectManual = useSession((s) => s.connectManual);
|
||||
const sessionError = useSession((s) => s.error);
|
||||
const [mode, setMode] = useState<Mode>('start');
|
||||
const [pin, setPin] = useState<Pin | null>(null);
|
||||
const [error, setError] = useState(sessionError);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [url, setUrl] = useState('');
|
||||
const [token, setToken] = useState('');
|
||||
const poll = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const stopPolling = () => {
|
||||
if (poll.current) clearInterval(poll.current);
|
||||
poll.current = null;
|
||||
};
|
||||
useEffect(() => stopPolling, []);
|
||||
|
||||
const begin = async (strong: boolean) => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
stopPolling();
|
||||
try {
|
||||
const p = await createPin(strong);
|
||||
setPin(p);
|
||||
setMode(strong ? 'browser' : 'code');
|
||||
if (strong) await openExternal(authUrl(p));
|
||||
const started = Date.now();
|
||||
poll.current = setInterval(async () => {
|
||||
if (Date.now() - started > 15 * 60_000) {
|
||||
stopPolling();
|
||||
setError('The sign-in request expired. Try again.');
|
||||
setMode('start');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const t = await checkPin(p);
|
||||
if (t) {
|
||||
stopPolling();
|
||||
await completeSignIn(t);
|
||||
}
|
||||
} catch {
|
||||
/* keep polling */
|
||||
}
|
||||
}, 1500);
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const manual = async () => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
try {
|
||||
let u = url.trim();
|
||||
if (!/^https?:\/\//.test(u)) u = `http://${u}`;
|
||||
if (!/:\d+/.test(u.replace(/^https?:\/\//, ''))) u = `${u.replace(/\/$/, '')}:32400`;
|
||||
await connectManual(u, token.trim());
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<WindowDrag />
|
||||
<div className="auth-backdrop" />
|
||||
<div className="auth-card">
|
||||
<div className="auth-brand">
|
||||
<KaleidoMark size={46} />
|
||||
<span>KALEIDO</span>
|
||||
</div>
|
||||
{mode === 'start' && (
|
||||
<>
|
||||
<h1>Your Plex library, front and center.</h1>
|
||||
<p className="auth-lede">Sign in with your Plex account to browse and play everything on your servers.</p>
|
||||
<div className="auth-actions">
|
||||
<Button variant="primary" size="lg" icon="external" busy={busy} onClick={() => begin(true)}>
|
||||
Sign in with Plex
|
||||
</Button>
|
||||
<button className="auth-link" onClick={() => begin(false)}>
|
||||
Use a code at plex.tv/link instead
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'browser' && (
|
||||
<>
|
||||
<h1>Continue in your browser</h1>
|
||||
<p className="auth-lede">We opened Plex’s sign-in page. Kaleido continues automatically once you approve it.</p>
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Waiting for Plex…
|
||||
</div>
|
||||
<div className="auth-actions">
|
||||
<Button variant="ghost" icon="external" onClick={() => pin && openExternal(authUrl(pin))}>
|
||||
Open the page again
|
||||
</Button>
|
||||
<button
|
||||
className="auth-link"
|
||||
onClick={() => {
|
||||
stopPolling();
|
||||
setMode('start');
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'code' && pin && (
|
||||
<>
|
||||
<h1>Link Kaleido</h1>
|
||||
<p className="auth-lede">
|
||||
On any device, go to <b>plex.tv/link</b> and enter this code.
|
||||
</p>
|
||||
<div className="auth-code selectable">{pin.code}</div>
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Waiting for Plex…
|
||||
</div>
|
||||
<div className="auth-actions">
|
||||
<Button variant="ghost" icon="external" onClick={() => openExternal('https://plex.tv/link')}>
|
||||
Open plex.tv/link
|
||||
</Button>
|
||||
<button
|
||||
className="auth-link"
|
||||
onClick={() => {
|
||||
stopPolling();
|
||||
setMode('start');
|
||||
}}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'manual' && (
|
||||
<>
|
||||
<h1>Connect to a server</h1>
|
||||
<p className="auth-lede">Enter a Plex Media Server address and an access token. Account features such as profiles need a full sign-in.</p>
|
||||
<form
|
||||
className="auth-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
manual();
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
<span>Server address</span>
|
||||
<input autoFocus value={url} placeholder="192.168.1.20:32400" onChange={(e) => setUrl(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Access token</span>
|
||||
<input type="password" value={token} onChange={(e) => setToken(e.target.value)} />
|
||||
</label>
|
||||
<div className="auth-actions">
|
||||
<Button variant="primary" busy={busy} disabled={!url || !token} type="submit">
|
||||
Connect
|
||||
</Button>
|
||||
<button type="button" className="auth-link" onClick={() => setMode('start')}>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{error && (
|
||||
<div className="auth-error">
|
||||
<Icon name="alert" size={16} /> {error}
|
||||
</div>
|
||||
)}
|
||||
{mode === 'start' && (
|
||||
<button className="auth-manual" onClick={() => setMode('manual')}>
|
||||
Connect to a server manually
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
src/screens/Splash.tsx
Normal file
44
src/screens/Splash.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSettings } from '../app/settings';
|
||||
|
||||
const FACETS = [
|
||||
{ fill: '#C3E8D3', d: 'M33,4 L55.5,17 L42.5,24.5 L33,19 Z' },
|
||||
{ fill: '#71B9B0', d: 'M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z' },
|
||||
{ fill: '#3D7C7B', d: 'M55.5,47 L33,60 L33,45 L42.5,39.5 Z' },
|
||||
{ fill: '#D0A977', d: 'M31,60 L8.5,47 L21.5,39.5 L31,45 Z' },
|
||||
{ fill: '#E9D8AE', d: 'M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z' },
|
||||
{ fill: '#EEF2DD', d: 'M8.5,17 L31,4 L31,19 L21.5,24.5 Z' },
|
||||
];
|
||||
|
||||
/**
|
||||
* The cold-start aperture: the six facets twist open around the dark center,
|
||||
* hold until startup data is ready, then the view flies through the aperture.
|
||||
*/
|
||||
export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }) {
|
||||
const reduced = useSettings((s) => s.reducedMotion);
|
||||
const [phase, setPhase] = useState<'opening' | 'held' | 'leaving'>('opening');
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setPhase('held'), reduced ? 0 : 1100);
|
||||
return () => clearTimeout(t);
|
||||
}, [reduced]);
|
||||
useEffect(() => {
|
||||
if (phase === 'held' && ready) setPhase('leaving');
|
||||
}, [phase, ready]);
|
||||
useEffect(() => {
|
||||
if (phase !== 'leaving') return;
|
||||
const t = setTimeout(onDone, reduced ? 0 : 620);
|
||||
return () => clearTimeout(t);
|
||||
}, [phase]);
|
||||
return (
|
||||
<div className={`splash ${phase}`} data-tauri-drag-region>
|
||||
<div className="splash-mark">
|
||||
<svg viewBox="0 0 64 64" width="92" height="92" aria-hidden="true">
|
||||
{FACETS.map((f, i) => (
|
||||
<path key={i} d={f.d} fill={f.fill} style={{ ['--i' as string]: i }} />
|
||||
))}
|
||||
</svg>
|
||||
<span className="splash-word">KALEIDO</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
22
src/screens/WindowDrag.tsx
Normal file
22
src/screens/WindowDrag.tsx
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { isNative, win } from '../platform/native';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
/** A draggable strip with window controls for full-screen states without the top bar. */
|
||||
export function WindowDrag() {
|
||||
if (!isNative) return null;
|
||||
return (
|
||||
<div className="window-drag" data-tauri-drag-region>
|
||||
<div className="window-controls">
|
||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Maximize" onClick={() => win.toggleMaximize()}>
|
||||
<Icon name="maximize" size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
96
src/screens/dialogs/Artwork.tsx
Normal file
96
src/screens/dialogs/Artwork.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useServerQuery } from '../../app/queries';
|
||||
import { Dialog, promptDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
const KIND = { poster: 'posters', art: 'arts', clearLogo: 'clearLogos' } as const;
|
||||
const LABEL = { poster: 'poster', art: 'background', clearLogo: 'logo' } as const;
|
||||
|
||||
export function ArtworkDialog({ item, type, onClose }: { item: Item; type: 'poster' | 'art' | 'clearLogo'; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const options = useServerQuery(['artwork', item.id, type], (s) => api.artworkOptions(s, item.id, KIND[type]), { staleTime: 0 });
|
||||
const [busy, setBusy] = useState('');
|
||||
|
||||
const choose = async (key: string) => {
|
||||
setBusy(key);
|
||||
try {
|
||||
await api.selectArtwork(server, item.id, type, key);
|
||||
toast(`Updated the ${LABEL[type]}`, 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
|
||||
const upload = () => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/webp';
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
setBusy('upload');
|
||||
try {
|
||||
await api.uploadArtwork(server, item.id, KIND[type], file);
|
||||
toast(`Uploaded a new ${LABEL[type]}`, 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
const fromUrl = async () => {
|
||||
const url = await promptDialog({ title: `Use an image from the web`, message: `Plex downloads the image and uses it as the ${LABEL[type]}.`, confirm: 'Use image', input: { label: 'Image URL', placeholder: 'https://…' } });
|
||||
if (url) choose(url);
|
||||
};
|
||||
|
||||
const shape = type === 'poster' ? 'poster' : type === 'art' ? 'landscape' : 'logo';
|
||||
return (
|
||||
<Dialog
|
||||
title={`Choose ${LABEL[type]}`}
|
||||
subtitle={item.title}
|
||||
onClose={onClose}
|
||||
width={880}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" icon="link" onClick={fromUrl}>
|
||||
From URL
|
||||
</Button>
|
||||
<Button variant="ghost" icon="upload" busy={busy === 'upload'} onClick={upload}>
|
||||
Upload image
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{options.isLoading && <PageLoader />}
|
||||
{options.data && !options.data.length && <EmptyState icon="image" title="No alternatives">Upload an image or use one from the web.</EmptyState>}
|
||||
<div className={`artwork-grid ${shape}`}>
|
||||
{options.data?.map((o) => (
|
||||
<button key={o.key} className={`artwork-option${o.selected ? ' selected' : ''}`} onClick={() => choose(o.key)} disabled={!!busy}>
|
||||
<img src={server.image(o.thumb, shape === 'poster' ? 180 : 320, shape === 'poster' ? 270 : 180, { format: shape === 'logo' ? 'png' : 'jpeg' })} alt="" loading="lazy" />
|
||||
{o.selected && (
|
||||
<span className="artwork-selected">
|
||||
<Icon name="check" size={14} strokeWidth={2.4} />
|
||||
</span>
|
||||
)}
|
||||
{o.provider && <span className="artwork-provider">{o.provider.replace(/^com\.plexapp\.agents\.|^tv\.plex\.agents\./, '')}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
60
src/screens/dialogs/DialogHost.tsx
Normal file
60
src/screens/dialogs/DialogHost.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { useDialogs } from '../../app/actions';
|
||||
import { useSession } from '../../app/session';
|
||||
import { Dialog } from '../../ui/overlays';
|
||||
import { EditMetadataDialog } from './EditMetadata';
|
||||
import { FixMatchDialog } from './FixMatch';
|
||||
import { ArtworkDialog } from './Artwork';
|
||||
import { MediaInfoDialog } from './MediaInfo';
|
||||
import { CollectionDialog, PlaylistDialog } from './Lists';
|
||||
import { channelLabel, resolutionLabel } from '../../app/format';
|
||||
|
||||
export function DialogHost() {
|
||||
const dialog = useDialogs((s) => s.dialog);
|
||||
const close = useDialogs((s) => s.close);
|
||||
const server = useSession((s) => s.server);
|
||||
if (!dialog || !server) return null;
|
||||
switch (dialog.kind) {
|
||||
case 'edit':
|
||||
return <EditMetadataDialog item={dialog.item} onClose={close} />;
|
||||
case 'match':
|
||||
return <FixMatchDialog item={dialog.item} onClose={close} />;
|
||||
case 'artwork':
|
||||
return <ArtworkDialog item={dialog.item} type={dialog.type} onClose={close} />;
|
||||
case 'info':
|
||||
return <MediaInfoDialog item={dialog.item} onClose={close} />;
|
||||
case 'collection':
|
||||
return <CollectionDialog item={dialog.item} onClose={close} />;
|
||||
case 'playlist':
|
||||
return <PlaylistDialog item={dialog.item} onClose={close} />;
|
||||
case 'synopsis':
|
||||
return (
|
||||
<Dialog title={dialog.item.title} subtitle={[dialog.item.year, dialog.item.tagline].filter(Boolean).join(' · ')} onClose={close} width={620}>
|
||||
<p className="synopsis-full selectable">{dialog.item.summary}</p>
|
||||
</Dialog>
|
||||
);
|
||||
case 'versions':
|
||||
return (
|
||||
<Dialog title="Choose a version" subtitle={dialog.item.title} onClose={close} width={520}>
|
||||
<div className="version-list">
|
||||
{dialog.item.media.map((m, i) => (
|
||||
<button
|
||||
key={m.id}
|
||||
className="version-row"
|
||||
onClick={() => {
|
||||
close();
|
||||
dialog.onPick(i);
|
||||
}}
|
||||
>
|
||||
<b>{m.title || [resolutionLabel(m), m.dynamicRange].filter(Boolean).join(' ')}</b>
|
||||
<span>
|
||||
{[m.videoCodec.toUpperCase(), `${m.audioCodec.toUpperCase()} ${channelLabel(m.audioChannels)}`, m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : '', m.container.toUpperCase()].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
208
src/screens/dialogs/EditMetadata.tsx
Normal file
208
src/screens/dialogs/EditMetadata.tsx
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useItem } from '../../app/queries';
|
||||
import { openDialog } from '../../app/actions';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, PageLoader, Segmented } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
type Tab = 'general' | 'tags' | 'artwork';
|
||||
|
||||
const FIELDS: { key: string; label: string; types: string[]; multiline?: boolean; type?: string }[] = [
|
||||
{ key: 'title', label: 'Title', types: ['movie', 'show', 'season', 'episode', 'collection'] },
|
||||
{ key: 'titleSort', label: 'Sort title', types: ['movie', 'show', 'collection'] },
|
||||
{ key: 'originalTitle', label: 'Original title', types: ['movie', 'show'] },
|
||||
{ key: 'originallyAvailableAt', label: 'Release date', types: ['movie', 'show', 'episode'], type: 'date' },
|
||||
{ key: 'contentRating', label: 'Content rating', types: ['movie', 'show', 'collection'] },
|
||||
{ key: 'studio', label: 'Studio', types: ['movie', 'show'] },
|
||||
{ key: 'tagline', label: 'Tagline', types: ['movie', 'show'] },
|
||||
{ key: 'summary', label: 'Summary', types: ['movie', 'show', 'season', 'episode', 'collection'], multiline: true },
|
||||
];
|
||||
|
||||
const TAGS: { key: string; label: string; source: keyof Item; types: string[] }[] = [
|
||||
{ key: 'genre', label: 'Genres', source: 'genres', types: ['movie', 'show'] },
|
||||
{ key: 'collection', label: 'Collections', source: 'collections', types: ['movie', 'show'] },
|
||||
{ key: 'label', label: 'Labels', source: 'labels', types: ['movie', 'show', 'episode', 'season', 'collection'] },
|
||||
{ key: 'director', label: 'Directors', source: 'directors', types: ['movie', 'episode'] },
|
||||
{ key: 'writer', label: 'Writers', source: 'writers', types: ['movie', 'episode'] },
|
||||
{ key: 'country', label: 'Countries', source: 'countries', types: ['movie', 'show'] },
|
||||
];
|
||||
|
||||
function TagEditor({ label, values, onChange, locked, onLock }: { label: string; values: string[]; onChange: (v: string[]) => void; locked: boolean; onLock: () => void }) {
|
||||
const [draft, setDraft] = useState('');
|
||||
const add = () => {
|
||||
const v = draft.trim();
|
||||
if (v && !values.includes(v)) onChange([...values, v]);
|
||||
setDraft('');
|
||||
};
|
||||
return (
|
||||
<div className="field">
|
||||
<span>
|
||||
{label}
|
||||
<LockToggle locked={locked} onClick={onLock} />
|
||||
</span>
|
||||
<div className="tag-editor">
|
||||
{values.map((v) => (
|
||||
<span key={v} className="chip">
|
||||
{v}
|
||||
<button aria-label={`Remove ${v}`} onClick={() => onChange(values.filter((x) => x !== v))}>
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
<input
|
||||
value={draft}
|
||||
placeholder="Add…"
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault();
|
||||
add();
|
||||
} else if (e.key === 'Backspace' && !draft && values.length) onChange(values.slice(0, -1));
|
||||
}}
|
||||
onBlur={add}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LockToggle({ locked, onClick }: { locked: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button type="button" className={`lock-toggle${locked ? ' on' : ''}`} onClick={onClick} title={locked ? 'Locked: refreshes keep this value' : 'Unlocked: refreshes may replace this value'}>
|
||||
<Icon name={locked ? 'lock' : 'unlock'} size={12} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function EditMetadataDialog({ item: initial, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const full = useItem(initial.id);
|
||||
const item = full.data ?? initial;
|
||||
const [tab, setTab] = useState<Tab>('general');
|
||||
const [values, setValues] = useState<Record<string, string> | null>(null);
|
||||
const [tags, setTags] = useState<Record<string, string[]> | null>(null);
|
||||
const [locks, setLocks] = useState<Record<string, boolean>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const fields = FIELDS.filter((f) => f.types.includes(item.type));
|
||||
const tagFields = TAGS.filter((t) => t.types.includes(item.type));
|
||||
const lockedFields: Record<string, boolean> = Object.fromEntries((item.raw?.Field ?? []).map((f: any) => [f.name, !!f.locked]));
|
||||
|
||||
if (full.data && !values) {
|
||||
setValues(Object.fromEntries(fields.map((f) => [f.key, String(item.raw?.[f.key] ?? '')])));
|
||||
setTags(Object.fromEntries(tagFields.map((t) => [t.key, ((item[t.source] as { tag: string }[]) ?? []).map((x) => x.tag)])));
|
||||
setLocks(lockedFields);
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (!values || !tags) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const changed: Record<string, string> = {};
|
||||
for (const f of fields) if ((values[f.key] ?? '') !== String(item.raw?.[f.key] ?? '')) changed[f.key] = values[f.key];
|
||||
const tagChanges: Record<string, { add: string[]; remove: string[] }> = {};
|
||||
for (const t of tagFields) {
|
||||
const before = ((item[t.source] as { tag: string }[]) ?? []).map((x) => x.tag);
|
||||
const after = tags[t.key];
|
||||
if (before.join('\u0000') !== after.join('\u0000')) tagChanges[t.key] = { add: after, remove: before.filter((b) => !after.includes(b)) };
|
||||
}
|
||||
const lockChanges: Record<string, boolean> = {};
|
||||
for (const [k, v] of Object.entries(locks)) if (!!lockedFields[k] !== v) lockChanges[k] = v;
|
||||
for (const k of [...Object.keys(changed), ...Object.keys(tagChanges)]) if (!(k in lockChanges)) lockChanges[k] = true;
|
||||
if (!Object.keys(changed).length && !Object.keys(tagChanges).length && !Object.keys(lockChanges).length) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
await api.editMetadata(server, item, changed, tagChanges, lockChanges);
|
||||
toast('Metadata saved', 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
title="Edit metadata"
|
||||
subtitle={`${item.title}${item.librarySectionTitle ? ` · ${item.librarySectionTitle}` : ''}`}
|
||||
onClose={onClose}
|
||||
width={760}
|
||||
className="edit-dialog"
|
||||
footer={
|
||||
<>
|
||||
<span className="dialog-note">
|
||||
<Icon name="lock" size={13} /> Edited fields are locked so metadata refreshes keep them.
|
||||
</span>
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" icon="check" busy={busy} onClick={save} disabled={!values}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Segmented
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
options={[
|
||||
{ value: 'general', label: 'General' },
|
||||
...(tagFields.length ? [{ value: 'tags' as Tab, label: 'Tags' }] : []),
|
||||
{ value: 'artwork', label: 'Artwork' },
|
||||
]}
|
||||
className="dialog-tabs"
|
||||
/>
|
||||
{!values || !tags ? (
|
||||
<PageLoader />
|
||||
) : tab === 'general' ? (
|
||||
<div className="field-grid">
|
||||
{fields.map((f) => (
|
||||
<label key={f.key} className="field" style={f.multiline || f.key === 'title' || f.key === 'tagline' ? { gridColumn: '1 / -1' } : undefined}>
|
||||
<span>
|
||||
{f.label}
|
||||
<LockToggle locked={!!locks[f.key]} onClick={() => setLocks((l) => ({ ...l, [f.key]: !l[f.key] }))} />
|
||||
</span>
|
||||
{f.multiline ? (
|
||||
<textarea value={values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} rows={6} />
|
||||
) : (
|
||||
<input type={f.type ?? 'text'} value={values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} />
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : tab === 'tags' ? (
|
||||
<div>
|
||||
{tagFields.map((t) => (
|
||||
<TagEditor key={t.key} label={t.label} values={tags[t.key]} onChange={(v) => setTags({ ...tags, [t.key]: v })} locked={!!locks[t.key]} onLock={() => setLocks((l) => ({ ...l, [t.key]: !l[t.key] }))} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="artwork-tab">
|
||||
{(
|
||||
[
|
||||
['poster', 'Poster', item.thumb, 'poster'],
|
||||
['art', 'Background', item.art, 'landscape'],
|
||||
['clearLogo', 'Logo', item.logo, 'logo'],
|
||||
] as const
|
||||
).map(([type, label, path, shape]) => (
|
||||
<button key={type} className={`artwork-choice ${shape}`} onClick={() => openDialog({ kind: 'artwork', item, type })}>
|
||||
<div className="artwork-choice-img">{path ? <img src={server.image(path, shape === 'poster' ? 200 : 360, shape === 'poster' ? 300 : 200, { format: shape === 'logo' ? 'png' : 'jpeg' })} alt="" /> : <Icon name="image" size={24} />}</div>
|
||||
<span>
|
||||
{label} <Icon name="next" size={13} />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
91
src/screens/dialogs/FixMatch.tsx
Normal file
91
src/screens/dialogs/FixMatch.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useSections } from '../../app/queries';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, EmptyState, Spinner } from '../../ui/primitives';
|
||||
|
||||
export function FixMatchDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const section = sections.data?.find((s) => s.id === item.librarySectionId);
|
||||
const [title, setTitle] = useState(item.title);
|
||||
const [year, setYear] = useState(item.year ? String(item.year) : '');
|
||||
const [results, setResults] = useState<api.MatchCandidate[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [applying, setApplying] = useState('');
|
||||
|
||||
const search = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setResults(await api.matches(server, item.id, { title, year, agent: section?.agent, language: section?.language }));
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
search();
|
||||
}, [section?.agent]);
|
||||
|
||||
const apply = async (m: api.MatchCandidate) => {
|
||||
setApplying(m.guid);
|
||||
try {
|
||||
await api.applyMatch(server, item.id, m.guid, m.name, m.year);
|
||||
toast(`Matched to “${m.name}”. Plex is updating its metadata.`, 'success');
|
||||
setTimeout(() => {
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
}, 2500);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setApplying('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog title="Fix match" subtitle={`Choose the correct ${item.type === 'show' ? 'series' : 'movie'} for ${item.raw?.Media?.[0]?.Part?.[0]?.file?.split(/[\\/]/).pop() ?? item.title}`} onClose={onClose} width={720}>
|
||||
<form
|
||||
className="match-search"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
search();
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
|
||||
<input className="text-input year" value={year} onChange={(e) => setYear(e.target.value.replace(/\D/g, '').slice(0, 4))} placeholder="Year" />
|
||||
<Button variant="ghost" icon="search" busy={busy} type="submit">
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
<div className="match-results">
|
||||
{busy && !results && (
|
||||
<div className="center-pad">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{results && !results.length && <EmptyState icon="search" title="No matches found">Try a different title or year.</EmptyState>}
|
||||
{results?.map((m) => (
|
||||
<button key={m.guid} className="match-row" onClick={() => apply(m)} disabled={!!applying}>
|
||||
<div className="match-thumb">{m.thumb && <img src={m.thumb.startsWith('http') ? m.thumb : server.image(m.thumb, 80, 120)} alt="" />}</div>
|
||||
<div className="match-text">
|
||||
<b>
|
||||
{m.name} {m.year ? <span className="dim">({m.year})</span> : null}
|
||||
</b>
|
||||
{m.summary && <p>{m.summary}</p>}
|
||||
<small>
|
||||
{m.matched ? 'Current match · ' : ''}
|
||||
{m.score}% confidence
|
||||
</small>
|
||||
</div>
|
||||
{applying === m.guid && <Spinner size={18} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
101
src/screens/dialogs/Lists.tsx
Normal file
101
src/screens/dialogs/Lists.tsx
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateLibrary, useServerQuery } from '../../app/queries';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, PageLoader } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
export function CollectionDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const collections = useServerQuery(['collections', item.librarySectionId], (s) => api.collections(s, item.librarySectionId), { enabled: !!item.librarySectionId });
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const current = new Set(item.collections.map((c) => c.tag));
|
||||
const add = async (title: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.addToCollection(server, item, title);
|
||||
toast(`Added to “${title}”`, 'success');
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog title="Add to collection" subtitle={item.title} onClose={onClose} width={480}>
|
||||
<form
|
||||
className="inline-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) add(name.trim());
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="New collection name" />
|
||||
<Button variant="ghost" icon="plus" type="submit" disabled={!name.trim() || busy}>
|
||||
Create
|
||||
</Button>
|
||||
</form>
|
||||
{collections.isLoading && <PageLoader />}
|
||||
<div className="list-pick">
|
||||
{collections.data?.map((c) => (
|
||||
<button key={c.id} className="list-pick-row" disabled={busy || current.has(c.title)} onClick={() => add(c.title)}>
|
||||
<Icon name="collection" size={17} />
|
||||
<span>{c.title}</span>
|
||||
{current.has(c.title) && <Icon name="check" size={15} className="dim" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlaylistDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const playlists = useServerQuery(['playlists'], (s) => api.playlists(s));
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog title="Add to playlist" subtitle={item.title} onClose={onClose} width={480}>
|
||||
<form
|
||||
className="inline-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) run(() => api.createPlaylist(server, name.trim(), server.machineId, item.id), `Created “${name.trim()}”`);
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="New playlist name" />
|
||||
<Button variant="ghost" icon="plus" type="submit" disabled={!name.trim() || busy}>
|
||||
Create
|
||||
</Button>
|
||||
</form>
|
||||
{playlists.isLoading && <PageLoader />}
|
||||
<div className="list-pick">
|
||||
{playlists.data?.map((p) => (
|
||||
<button key={p.id} className="list-pick-row" disabled={busy} onClick={() => run(() => api.addToPlaylist(server, p.id, server.machineId, item.id), `Added to “${p.title}”`)}>
|
||||
<Icon name="queue" size={17} />
|
||||
<span>{p.title}</span>
|
||||
<small className="dim">{p.leafCount ? `${p.leafCount} items` : ''}</small>
|
||||
</button>
|
||||
))}
|
||||
{playlists.data && !playlists.data.length && <p className="muted">No video playlists yet. Create one above.</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
109
src/screens/dialogs/MediaInfo.tsx
Normal file
109
src/screens/dialogs/MediaInfo.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import type { Item, Stream } from '../../plex/types';
|
||||
import { useItem } from '../../app/queries';
|
||||
import { bitrate, channelLabel, date, duration, fileSize, resolutionLabel } from '../../app/format';
|
||||
import { Dialog } from '../../ui/overlays';
|
||||
import { PageLoader } from '../../ui/primitives';
|
||||
|
||||
function streamLine(s: Stream): string {
|
||||
if (s.streamType === 1)
|
||||
return [s.codec.toUpperCase(), s.profile, s.width && s.height ? `${s.width}×${s.height}` : '', s.frameRate ? `${s.frameRate} fps` : '', s.bitDepth ? `${s.bitDepth}-bit` : '', s.doviPresent ? 'Dolby Vision' : s.colorTrc === 'smpte2084' ? 'HDR10' : '', bitrate(s.bitrate)]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
if (s.streamType === 2) return [s.extendedDisplayTitle || s.displayTitle, s.samplingRate ? `${(s.samplingRate / 1000).toFixed(1)} kHz` : '', bitrate(s.bitrate)].filter(Boolean).join(' · ');
|
||||
return [s.extendedDisplayTitle || s.displayTitle, s.key ? 'External file' : 'Embedded'].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
export function MediaInfoDialog({ item: initial, onClose }: { item: Item; onClose: () => void }) {
|
||||
const q = useItem(initial.id);
|
||||
const item = q.data ?? initial;
|
||||
return (
|
||||
<Dialog title="Media info" subtitle={item.type === 'episode' ? `${item.grandparentTitle} · ${item.title}` : item.title} onClose={onClose} width={760}>
|
||||
{q.isLoading && <PageLoader />}
|
||||
<div className="media-info selectable">
|
||||
{item.media.map((m, mi) => (
|
||||
<section key={m.id} className="media-version">
|
||||
<h3>
|
||||
{item.media.length > 1 ? `Version ${mi + 1} · ` : ''}
|
||||
{[resolutionLabel(m), m.dynamicRange, m.container.toUpperCase()].filter(Boolean).join(' · ')}
|
||||
</h3>
|
||||
<div className="info-grid">
|
||||
<div>
|
||||
<span>Duration</span>
|
||||
<b>{duration(m.duration || item.duration)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Bitrate</span>
|
||||
<b>{bitrate(m.bitrate) || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Video</span>
|
||||
<b>{[m.videoCodec.toUpperCase(), m.videoProfile, m.videoFrameRate].filter(Boolean).join(' · ')}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Audio</span>
|
||||
<b>{[m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' · ')}</b>
|
||||
</div>
|
||||
</div>
|
||||
{m.parts.map((p) => (
|
||||
<div key={p.id} className="media-part">
|
||||
<div className="media-file">
|
||||
<span>File</span>
|
||||
<code>{p.file || p.key}</code>
|
||||
</div>
|
||||
<div className="info-grid">
|
||||
<div>
|
||||
<span>Size</span>
|
||||
<b>{fileSize(p.size) || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Availability</span>
|
||||
<b>{p.exists === false ? 'Missing' : p.accessible === false ? 'Not accessible' : 'Available'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Previews</span>
|
||||
<b>{p.indexes.includes('sd') ? 'Generated' : 'Not generated'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<table className="stream-table">
|
||||
<tbody>
|
||||
{p.streams.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.streamType === 1 ? 'Video' : s.streamType === 2 ? 'Audio' : s.streamType === 3 ? 'Subtitle' : 'Other'}</td>
|
||||
<td>{streamLine(s)}</td>
|
||||
<td>{s.selected ? 'Selected' : s.default ? 'Default' : ''}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
<div className="info-grid footer">
|
||||
<div>
|
||||
<span>Library</span>
|
||||
<b>{item.librarySectionTitle || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Added</span>
|
||||
<b>{date(item.addedAt)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Updated</span>
|
||||
<b>{date(item.updatedAt)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Plex ID</span>
|
||||
<b>{item.id}</b>
|
||||
</div>
|
||||
{item.guids.length > 0 && (
|
||||
<div style={{ gridColumn: '1 / -1' }}>
|
||||
<span>External IDs</span>
|
||||
<b>{item.guids.join(' · ')}</b>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
81
src/screens/discover.ts
Normal file
81
src/screens/discover.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import * as api from '../plex/api';
|
||||
import type { Hub, Item } from '../plex/types';
|
||||
import type { Feature } from '../ui/Hero';
|
||||
import type { PlexServer } from '../plex/client';
|
||||
|
||||
/** One shuffle per app session keeps features stable while browsing. */
|
||||
const seed = Math.floor(Math.random() * 1e9);
|
||||
function shuffled<T>(list: T[], salt = 0): T[] {
|
||||
const out = [...list];
|
||||
let s = (seed + salt) % 2147483647 || 1;
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
s = (s * 48271) % 2147483647;
|
||||
const j = s % (i + 1);
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const FEATURE_SOURCES: [RegExp, string][] = [
|
||||
[/recentlyreleased|recentlyaired/, 'Recently released'],
|
||||
[/topunwatched|toprated/, 'Highly rated'],
|
||||
[/recentlyadded/, 'Recently added'],
|
||||
[/startwatching/, 'Start watching'],
|
||||
[/curated|genre|by\.actor|moreingenre/, 'Recommended'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Features interleave recently released, highly rated unwatched and
|
||||
* Plex-recommended titles; they need artwork and skip in-progress titles.
|
||||
*/
|
||||
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
|
||||
const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) =>
|
||||
shuffled(
|
||||
hubs
|
||||
.filter((h) => re.test(h.id))
|
||||
.flatMap((h) => h.items)
|
||||
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
|
||||
.map((item) => ({ item, eyebrow })),
|
||||
salt,
|
||||
),
|
||||
);
|
||||
const out: Feature[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (let round = 0; out.length < limit && round < 20; round++) {
|
||||
for (const pool of pools) {
|
||||
const f = pool[round];
|
||||
if (f && !seen.has(f.item.id) && out.length < limit) {
|
||||
seen.add(f.item.id);
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* New seasons, one card per show. Samples many seasons so a single series
|
||||
* import cannot fill the row.
|
||||
*/
|
||||
export async function recentSeasons(s: PlexServer, sectionId: string): Promise<Item[]> {
|
||||
const page = await api.libraryPage(s, sectionId, { type: 3, sort: 'addedAt:desc', start: 0, size: 100 });
|
||||
const byShow = new Map<string, Item[]>();
|
||||
for (const season of page.items) {
|
||||
if (!season.parentId) continue;
|
||||
const list = byShow.get(season.parentId) ?? [];
|
||||
list.push(season);
|
||||
byShow.set(season.parentId, list);
|
||||
}
|
||||
const out: Item[] = [];
|
||||
for (const [, seasons] of byShow) {
|
||||
if (out.length >= 18) break;
|
||||
// Several new seasons: show the series; one: the season itself.
|
||||
if (seasons.length > 1) {
|
||||
const first = seasons[0];
|
||||
out.push({ ...first, id: first.parentId, type: 'show', title: first.parentTitle, thumb: first.parentThumb || first.thumb, key: `/library/metadata/${first.parentId}/children` });
|
||||
} else out.push(seasons[0]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const HIDDEN_HUBS = /continue|ondeck|inprogress|playlists|music|photos|videos\.recent/;
|
||||
331
src/screens/settings/AppSettings.tsx
Normal file
331
src/screens/settings/AppSettings.tsx
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSettings, QUALITY_LABEL, type Quality, type SkipMode, type SubtitleMode } from '../../app/settings';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useSections } from '../../app/queries';
|
||||
import { useDownloads } from '../../downloads/store';
|
||||
import { appInfo, isNative, openExternal, pickFolder, revealPath, type AppInfo } from '../../platform/native';
|
||||
import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater';
|
||||
import { Button, Select, Switch } from '../../ui/primitives';
|
||||
import { confirmDialog } from '../../ui/overlays';
|
||||
import { Pref, SettingsSection } from './parts';
|
||||
import { KaleidoMark } from '../../ui/primitives';
|
||||
|
||||
const LANGUAGES: [string, string][] = [
|
||||
['', 'Automatic'],
|
||||
['eng', 'English'],
|
||||
['spa', 'Spanish'],
|
||||
['fre', 'French'],
|
||||
['ger', 'German'],
|
||||
['ita', 'Italian'],
|
||||
['por', 'Portuguese'],
|
||||
['jpn', 'Japanese'],
|
||||
['kor', 'Korean'],
|
||||
['chi', 'Chinese'],
|
||||
['rus', 'Russian'],
|
||||
['hin', 'Hindi'],
|
||||
['ara', 'Arabic'],
|
||||
['dut', 'Dutch'],
|
||||
['swe', 'Swedish'],
|
||||
['nor', 'Norwegian'],
|
||||
['dan', 'Danish'],
|
||||
['fin', 'Finnish'],
|
||||
['pol', 'Polish'],
|
||||
['tur', 'Turkish'],
|
||||
];
|
||||
|
||||
const qualityOptions = (Object.keys(QUALITY_LABEL) as Quality[]).map((q) => ({ value: q, label: QUALITY_LABEL[q] }));
|
||||
const skipOptions: { value: SkipMode; label: string }[] = [
|
||||
{ value: 'button', label: 'Show a button' },
|
||||
{ value: 'auto', label: 'Skip automatically' },
|
||||
{ value: 'off', label: 'Off' },
|
||||
];
|
||||
|
||||
const SHORTCUTS: [string, string][][] = [
|
||||
[
|
||||
['Ctrl + K', 'Search'],
|
||||
['Alt + ← / Mouse back', 'Go back'],
|
||||
['Alt + → / Mouse forward', 'Go forward'],
|
||||
['Esc', 'Go back or close a dialog'],
|
||||
['F11', 'Full screen'],
|
||||
['Ctrl + ,', 'Settings'],
|
||||
['Right-click a title', 'Title actions'],
|
||||
],
|
||||
[
|
||||
['Space or K', 'Play / pause'],
|
||||
['← / →', 'Seek back / forward'],
|
||||
['Shift + ← / →', 'Seek one minute'],
|
||||
['J / L', 'Seek 10 seconds'],
|
||||
['↑ / ↓ or scroll', 'Volume'],
|
||||
['M', 'Mute'],
|
||||
['F or double-click', 'Full screen'],
|
||||
['C', 'Next subtitle track'],
|
||||
['Shift + N', 'Next episode'],
|
||||
['0–9', 'Jump to 0–90%'],
|
||||
['Esc', 'Exit full screen, then the player'],
|
||||
],
|
||||
];
|
||||
|
||||
export function AppSettings({ tab }: { tab: string }) {
|
||||
const s = useSettings();
|
||||
const set = s.set;
|
||||
const session = useSession();
|
||||
const sections = useSections();
|
||||
const downloads = useDownloads();
|
||||
const [info, setInfo] = useState<AppInfo | null>(null);
|
||||
const updater = useUpdater();
|
||||
useEffect(() => {
|
||||
appInfo().then(setInfo);
|
||||
}, []);
|
||||
const movieLibs = (sections.data ?? []).filter((x) => x.type === 'movie');
|
||||
const showLibs = (sections.data ?? []).filter((x) => x.type === 'show');
|
||||
|
||||
switch (tab) {
|
||||
case 'general':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Account" description="Your Plex account and the server Kaleido is browsing.">
|
||||
<Pref label={session.user?.title ?? 'Signed in with a server token'} description={session.user?.email || 'Manual connection'}>
|
||||
<Button variant="ghost" size="sm" icon="logout" onClick={() => confirmDialog({ title: 'Sign out of Plex?', message: 'Downloads stay on this computer. You can sign in again at any time.', confirm: 'Sign out' }).then((ok) => void (ok && session.signOut()))}>
|
||||
Sign out
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref
|
||||
label="Server"
|
||||
description={
|
||||
session.server
|
||||
? `${session.server.name} · ${session.connection?.relay ? 'Plex Relay' : session.connection?.local ? 'Local network' : 'Remote'} · ${session.server.uri.replace(/X-Plex-Token=[^&]+/, '')}`
|
||||
: ''
|
||||
}
|
||||
>
|
||||
<Button variant="ghost" size="sm" icon="swap" onClick={session.showServerPicker} disabled={!session.accountToken}>
|
||||
Change
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Browsing">
|
||||
<Pref label="Start on" description="The page Kaleido opens to.">
|
||||
<Select
|
||||
value={s.startPage}
|
||||
onChange={(v) => set('startPage', v)}
|
||||
options={[
|
||||
{ value: 'home', label: 'Home' },
|
||||
{ value: 'movies', label: 'Movies' },
|
||||
{ value: 'shows', label: 'TV Shows' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
{movieLibs.length > 1 && (
|
||||
<Pref label="Movies library" description="The library shown in Movies.">
|
||||
<Select value={s.movieSection || movieLibs[0].id} onChange={(v) => set('movieSection', v)} options={movieLibs.map((l) => ({ value: l.id, label: l.title }))} />
|
||||
</Pref>
|
||||
)}
|
||||
{showLibs.length > 1 && (
|
||||
<Pref label="TV Shows library" description="The library shown in TV Shows.">
|
||||
<Select value={s.showSection || showLibs[0].id} onChange={(v) => set('showSection', v)} options={showLibs.map((l) => ({ value: l.id, label: l.title }))} />
|
||||
</Pref>
|
||||
)}
|
||||
<Pref label="Mark as watched at" description="How far into a title playback counts as watched. This belongs to Kaleido and doesn’t change your server.">
|
||||
<Select value={s.watchedPercent} onChange={(v) => set('watchedPercent', v)} options={[70, 75, 80, 85, 90, 95].map((v) => ({ value: v, label: `${v}%` }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'playback':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Quality" description="Original quality plays the source file directly; Kaleido decodes nearly every format, so Plex rarely needs to convert.">
|
||||
<Pref label="On your local network">
|
||||
<Select value={s.quality} onChange={(v) => set('quality', v)} options={qualityOptions} />
|
||||
</Pref>
|
||||
<Pref label="Away from home" description="Used when the server is reached remotely or through Plex Relay.">
|
||||
<Select value={s.remoteQuality} onChange={(v) => set('remoteQuality', v)} options={qualityOptions} />
|
||||
</Pref>
|
||||
<Pref label="Hardware decoding" description="Uses your graphics card to decode video. Turn off only if you see artifacts. Applies after restarting Kaleido.">
|
||||
<Switch checked={s.hwdec} onChange={(v) => set('hwdec', v)} />
|
||||
</Pref>
|
||||
<Pref label="HDR passthrough" description="Sends HDR video to HDR-capable displays when Windows HDR is on. Applies after restarting Kaleido.">
|
||||
<Switch checked={s.hdrPassthrough} onChange={(v) => set('hdrPassthrough', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Episodes and markers" description="Intro and credits markers come from your Plex server’s analysis.">
|
||||
<Pref label="Skip intros">
|
||||
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Skip credits">
|
||||
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Play the next episode automatically">
|
||||
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
|
||||
</Pref>
|
||||
<Pref label="Countdown" description="Seconds before the next episode starts.">
|
||||
<Select value={s.countdownSeconds} disabled={!s.autoplayNext} onChange={(v) => set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
<Pref label="Arrow-key seek">
|
||||
<Select value={s.seekStep} onChange={(v) => set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'subtitles':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Audio">
|
||||
<Pref label="Preferred audio language" description="Automatic follows the track Plex selects for each title.">
|
||||
<Select value={s.audioLanguage} onChange={(v) => set('audioLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Subtitles">
|
||||
<Pref label="Show subtitles">
|
||||
<Select<SubtitleMode>
|
||||
value={s.subtitleMode}
|
||||
onChange={(v) => set('subtitleMode', v)}
|
||||
options={[
|
||||
{ value: 'auto', label: 'As chosen in Plex' },
|
||||
{ value: 'forced', label: 'Forced subtitles only' },
|
||||
{ value: 'always', label: 'Always' },
|
||||
{ value: 'off', label: 'Never' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Subtitle language" description="Automatic uses the language of the audio track.">
|
||||
<Select value={s.subtitleLanguage} onChange={(v) => set('subtitleLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||
</Pref>
|
||||
<Pref label="Size">
|
||||
<Select
|
||||
value={s.subtitleScale}
|
||||
onChange={(v) => set('subtitleScale', v)}
|
||||
options={[
|
||||
{ value: 0.8, label: 'Small' },
|
||||
{ value: 1, label: 'Normal' },
|
||||
{ value: 1.25, label: 'Large' },
|
||||
{ value: 1.5, label: 'Extra large' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Background box" description="Draws text subtitles on a dark box for contrast.">
|
||||
<Switch checked={s.subtitleBackground} onChange={(v) => set('subtitleBackground', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'interface':
|
||||
return (
|
||||
<SettingsSection title="Interface" description="Kaleido keeps the same artwork-led look as its TV app.">
|
||||
<Pref label="Artwork colour wash" description="Tints pages with colors from the title’s artwork.">
|
||||
<Switch checked={s.colorWash} onChange={(v) => set('colorWash', v)} />
|
||||
</Pref>
|
||||
<Pref label="Rotate featured titles" description="Cycles the featured title on Home and Discover every 12 seconds.">
|
||||
<Switch checked={s.heroRotation} onChange={(v) => set('heroRotation', v)} />
|
||||
</Pref>
|
||||
<Pref label="Poster size" description="Card size in library grids.">
|
||||
<Select
|
||||
value={s.posterSize}
|
||||
onChange={(v) => set('posterSize', v)}
|
||||
options={[
|
||||
{ value: 'compact', label: 'Compact' },
|
||||
{ value: 'comfortable', label: 'Comfortable' },
|
||||
{ value: 'large', label: 'Large' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Theme music" description="Plays a show or movie’s theme on its page.">
|
||||
<Switch checked={s.themeMusic} onChange={(v) => set('themeMusic', v)} />
|
||||
</Pref>
|
||||
<Pref label="Theme music volume">
|
||||
<Select value={s.themeVolume} disabled={!s.themeMusic} onChange={(v) => set('themeVolume', v)} options={[15, 30, 50, 75, 100].map((v) => ({ value: v, label: `${v}%` }))} />
|
||||
</Pref>
|
||||
<Pref label="Reduce motion" description="Turns off transitions and animations.">
|
||||
<Switch checked={s.reducedMotion} onChange={(v) => set('reducedMotion', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
);
|
||||
case 'downloads':
|
||||
return (
|
||||
<SettingsSection title="Offline media" description="Downloads keep the original file, so they play exactly as on your server.">
|
||||
<Pref label="Download folder" description={downloads.dir || info?.defaultDownloadDir || 'Not set'}>
|
||||
<Button variant="ghost" size="sm" icon="folder" disabled={!isNative} onClick={async () => {
|
||||
const dir = await pickFolder(downloads.dir);
|
||||
if (dir) await downloads.setDir(dir);
|
||||
}}>
|
||||
Change
|
||||
</Button>
|
||||
{downloads.dir && (
|
||||
<Button variant="ghost" size="sm" onClick={() => revealPath(downloads.dir)}>
|
||||
Open
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
<Pref label="Resume interrupted downloads" description="Downloads in progress when Kaleido closed continue automatically when it reconnects.">
|
||||
<span className="muted">Always</span>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
);
|
||||
case 'shortcuts':
|
||||
return (
|
||||
<div className="shortcut-columns">
|
||||
{SHORTCUTS.map((group, i) => (
|
||||
<SettingsSection key={i} title={i === 0 ? 'Browsing' : 'Player'}>
|
||||
{group.map(([k, label]) => (
|
||||
<Pref key={label} label={label}>
|
||||
<span className="kbd">{k}</span>
|
||||
</Pref>
|
||||
))}
|
||||
</SettingsSection>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
case 'about':
|
||||
return (
|
||||
<>
|
||||
<div className="about-app">
|
||||
<KaleidoMark size={56} />
|
||||
<div>
|
||||
<h2>Kaleido</h2>
|
||||
<p className="muted">
|
||||
Version {info?.version ?? '—'} · {info?.platform === 'windows' ? 'Windows' : info?.platform}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<SettingsSection title="Updates" description="Kaleido checks for new versions when it starts and installs them with your permission.">
|
||||
<Pref
|
||||
label={updater.available ? `Kaleido ${updater.available.version} is available` : updater.checking ? 'Checking…' : 'You’re up to date'}
|
||||
description={updater.error || (updater.available?.notes ? updater.available.notes : updater.checkedAt ? `Last checked ${new Date(updater.checkedAt).toLocaleTimeString()}` : '')}
|
||||
>
|
||||
{updater.available ? (
|
||||
<Button variant="primary" size="sm" icon="download" busy={updater.installing} onClick={installUpdate}>
|
||||
{updater.installing ? `Installing ${Math.round(updater.progress * 100)}%` : 'Install and restart'}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={updater.checking} disabled={!isNative} onClick={() => checkForUpdate(true)}>
|
||||
Check now
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Information">
|
||||
<Pref label="Plex client identifier" description={localStorage.getItem('kaleido.clientId') ?? ''} />
|
||||
{info?.dataDir && (
|
||||
<Pref label="App data" description={info.dataDir}>
|
||||
<Button variant="ghost" size="sm" onClick={() => revealPath(info.dataDir)}>
|
||||
Open
|
||||
</Button>
|
||||
</Pref>
|
||||
)}
|
||||
<Pref label="Source code" description="git.elijahkuntz.com/Elijah/Kaleido-Desktop">
|
||||
<Button variant="ghost" size="sm" icon="external" onClick={() => openExternal('https://git.elijahkuntz.com/Elijah/Kaleido-Desktop')}>
|
||||
Open
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Reset preferences" description="Restores Kaleido’s settings. Your sign-in and downloads are kept.">
|
||||
<Button variant="ghost" size="sm" onClick={() => confirmDialog({ title: 'Reset preferences?', message: 'Playback, subtitle and interface settings return to their defaults.', confirm: 'Reset' }).then((ok) => ok && s.reset())}>
|
||||
Reset
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<p className="legal">Kaleido is an independent project and is not affiliated with Plex. Video playback uses mpv (libmpv), licensed under the LGPL.</p>
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
255
src/screens/settings/ServerDashboard.tsx
Normal file
255
src/screens/settings/ServerDashboard.tsx
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
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 />;
|
||||
}
|
||||
258
src/screens/settings/ServerLibraries.tsx
Normal file
258
src/screens/settings/ServerLibraries.tsx
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import type { Section } from '../../plex/types';
|
||||
import { invalidateLibrary, queryClient, useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { relativeTime } from '../../app/format';
|
||||
import { Button, PageLoader, Segmented, Select, Spinner } from '../../ui/primitives';
|
||||
import { confirmDialog, Dialog, openMenu, toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card } from './parts';
|
||||
|
||||
function FolderPicker({ onPick, onClose }: { onPick: (path: string) => void; onClose: () => void }) {
|
||||
const [stack, setStack] = useState<{ key?: string; title: string; path: string }[]>([{ title: 'Computer', path: '' }]);
|
||||
const current = stack[stack.length - 1];
|
||||
const q = useServerQuery(['browse', current.key ?? 'root'], (s) => admin.browse(s, current.key), { staleTime: 30_000 });
|
||||
return (
|
||||
<Dialog
|
||||
title="Choose a folder"
|
||||
subtitle={current.path || 'Folders on the server'}
|
||||
onClose={onClose}
|
||||
width={560}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" disabled={!current.path} onClick={() => (onPick(current.path), onClose())}>
|
||||
Use this folder
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="folder-crumbs">
|
||||
{stack.map((c, i) => (
|
||||
<button key={i} onClick={() => setStack(stack.slice(0, i + 1))}>
|
||||
{c.title}
|
||||
{i < stack.length - 1 && <Icon name="next" size={12} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="folder-list">
|
||||
{q.isLoading && <Spinner />}
|
||||
{q.data?.map((p) => (
|
||||
<button key={p.key} className="list-pick-row" onClick={() => setStack([...stack, { key: p.key, title: p.title, path: p.path }])}>
|
||||
<Icon name="folder" size={17} />
|
||||
<span>{p.title}</span>
|
||||
<Icon name="next" size={14} className="dim" />
|
||||
</button>
|
||||
))}
|
||||
{q.data && !q.data.length && <p className="muted">No subfolders.</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryDialog({ section, onClose }: { section?: Section; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const [type, setType] = useState<'movie' | 'show'>(section?.type === 'show' ? 'show' : 'movie');
|
||||
const [name, setName] = useState(section?.title ?? 'Movies');
|
||||
const [locations, setLocations] = useState<string[]>(section?.locations.map((l) => l.path) ?? []);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const agents = useServerQuery(['agents', type], (s) => admin.agents(s, type === 'movie' ? 1 : 2), { enabled: !section });
|
||||
const scanners = useServerQuery(['scanners', type], (s) => admin.scanners(s, type === 'movie' ? 1 : 2), { enabled: !section });
|
||||
const [agent, setAgent] = useState('');
|
||||
const [scanner, setScanner] = useState('');
|
||||
useEffect(() => {
|
||||
if (section) return;
|
||||
setName(type === 'movie' ? 'Movies' : 'TV Shows');
|
||||
setAgent('');
|
||||
setScanner('');
|
||||
}, [type]);
|
||||
const agentValue = agent || agents.data?.find((a) => a.identifier.startsWith('tv.plex.agents'))?.identifier || agents.data?.[0]?.identifier || '';
|
||||
const scannerValue = scanner || scanners.data?.find((s) => s.startsWith('Plex'))?.toString() || scanners.data?.[0] || '';
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
if (section) await admin.updateLibrary(server, section, { name, locations });
|
||||
else await admin.createLibrary(server, { name, type, agent: agentValue, scanner: scannerValue, language: navigator.language || 'en-US', locations });
|
||||
toast(section ? 'Library updated' : `Created “${name}”. Plex is scanning it now.`, 'success');
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'sections'] });
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
title={section ? `Edit ${section.title}` : 'Add a library'}
|
||||
onClose={onClose}
|
||||
width={600}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" busy={busy} disabled={!name.trim() || !locations.length} onClick={save}>
|
||||
{section ? 'Save' : 'Add library'}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{!section && (
|
||||
<Segmented
|
||||
className="dialog-tabs"
|
||||
value={type}
|
||||
onChange={setType}
|
||||
options={[
|
||||
{ value: 'movie', label: 'Movies' },
|
||||
{ value: 'show', label: 'TV Shows' },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<label className="field">
|
||||
<span>Name</span>
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
{!section && (
|
||||
<div className="field-grid">
|
||||
<div className="field">
|
||||
<span>Metadata agent</span>
|
||||
<Select value={agentValue} options={(agents.data ?? []).map((a) => ({ value: a.identifier, label: a.name }))} onChange={setAgent} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<span>Scanner</span>
|
||||
<Select value={scannerValue} options={(scanners.data ?? []).map((s) => ({ value: s, label: s }))} onChange={setScanner} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="field">
|
||||
<span>Folders</span>
|
||||
<div className="folder-chosen">
|
||||
{locations.map((l) => (
|
||||
<div key={l} className="folder-row">
|
||||
<Icon name="folder" size={16} />
|
||||
<code>{l}</code>
|
||||
<button aria-label="Remove folder" onClick={() => setLocations(locations.filter((x) => x !== l))}>
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="ghost" size="sm" icon="plus" onClick={() => setPicking(true)}>
|
||||
Add folder
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
{picking && <FolderPicker onClose={() => setPicking(false)} onPick={(p) => setLocations((l) => (l.includes(p) ? l : [...l, p]))} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryRow({ section }: { section: Section }) {
|
||||
const server = useServer();
|
||||
const size = useServerQuery(['librarySize', section.id], (s) => admin.librarySize(s, section), { staleTime: 60_000 });
|
||||
const [editing, setEditing] = useState(false);
|
||||
const act = async (fn: () => Promise<unknown>, done: string) => {
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
setTimeout(() => queryClient.invalidateQueries({ queryKey: [server.machineId, 'sections'] }), 1500);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
const icon = section.type === 'movie' ? 'film' : section.type === 'show' ? 'tv' : section.type === 'artist' ? 'audio' : 'image';
|
||||
const unit = section.type === 'movie' ? 'movies' : section.type === 'show' ? 'shows' : section.type === 'artist' ? 'artists' : 'items';
|
||||
return (
|
||||
<div className="library-manage-row">
|
||||
<div className="lib-ico">
|
||||
<Icon name={icon} size={18} />
|
||||
</div>
|
||||
<div className="library-manage-text">
|
||||
<strong>
|
||||
{section.title}
|
||||
{section.refreshing && (
|
||||
<span className="scanning">
|
||||
<Spinner size={12} /> Scanning
|
||||
</span>
|
||||
)}
|
||||
</strong>
|
||||
<small>
|
||||
{size.data !== undefined ? `${size.data.toLocaleString()} ${unit}` : '…'} · Scanned {relativeTime(section.scannedAt) || 'never'}
|
||||
</small>
|
||||
<small className="dim">{section.locations.map((l) => l.path).join(' · ')}</small>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon="refresh" onClick={() => act(() => admin.scanLibrary(server, section.id), `Scanning ${section.title}`)}>
|
||||
Scan
|
||||
</Button>
|
||||
<button
|
||||
className="icon-btn"
|
||||
aria-label="More"
|
||||
onClick={(e) =>
|
||||
openMenu(
|
||||
[
|
||||
{ label: 'Scan library files', icon: 'scan', onSelect: () => act(() => admin.scanLibrary(server, section.id), `Scanning ${section.title}`) },
|
||||
{ label: 'Refresh all metadata', icon: 'refresh', onSelect: () => act(() => admin.scanLibrary(server, section.id, true), `Refreshing metadata for ${section.title}`) },
|
||||
{ label: 'Analyze', icon: 'activity', onSelect: () => act(() => admin.analyzeLibrary(server, section.id), `Analyzing ${section.title}`) },
|
||||
{ label: 'Empty trash', icon: 'trash', onSelect: () => act(() => admin.emptyTrash(server, section.id), 'Trash emptied') },
|
||||
...(section.refreshing ? [{ label: 'Cancel scan', icon: 'x', onSelect: () => act(() => admin.cancelScan(server, section.id), 'Scan cancelled') }] : []),
|
||||
{ divider: true },
|
||||
...(section.type === 'movie' || section.type === 'show' ? [{ label: 'Edit…', icon: 'edit', onSelect: () => setEditing(true) }] : []),
|
||||
{
|
||||
label: 'Delete library…',
|
||||
icon: 'trash',
|
||||
danger: true,
|
||||
onSelect: async () => {
|
||||
if (await confirmDialog({ title: `Delete “${section.title}”?`, message: 'The library and its metadata are removed from Plex. Your media files are not deleted.', confirm: 'Delete library', danger: true }))
|
||||
act(() => admin.deleteLibrary(server, section.id), 'Library deleted');
|
||||
},
|
||||
},
|
||||
],
|
||||
e.currentTarget,
|
||||
{ align: 'end' },
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
{editing && <LibraryDialog section={section} onClose={() => setEditing(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerLibraries() {
|
||||
const server = useServer();
|
||||
const sections = useServerQuery(['sections'], (s) => import('../../plex/api').then((m) => m.sections(s)), { refetchInterval: 5000, staleTime: 0 });
|
||||
const [adding, setAdding] = useState(false);
|
||||
if (!sections.data) return <PageLoader />;
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
title="Libraries"
|
||||
actions={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" size="sm" icon="refresh" onClick={() => admin.scanAll(server).then(() => toast('Scanning all libraries', 'success'), toastError)}>
|
||||
Scan all
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" icon="plus" onClick={() => setAdding(true)}>
|
||||
Add library
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{sections.data.map((s) => (
|
||||
<LibraryRow key={s.id} section={s} />
|
||||
))}
|
||||
</Card>
|
||||
{adding && <LibraryDialog onClose={() => setAdding(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
218
src/screens/settings/ServerManage.tsx
Normal file
218
src/screens/settings/ServerManage.tsx
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import { useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { date } from '../../app/format';
|
||||
import { invoke, isNative, saveFile } from '../../platform/native';
|
||||
import { Button, PageLoader, Switch } from '../../ui/primitives';
|
||||
import { confirmDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card, Pref, SettingsSection } from './parts';
|
||||
|
||||
function Devices() {
|
||||
const server = useServer();
|
||||
const q = useServerQuery(['devices'], (s) => admin.devices(s), { staleTime: 0 });
|
||||
const [filter, setFilter] = useState('');
|
||||
if (!q.data) return <PageLoader />;
|
||||
const list = q.data.filter((d) => !filter || `${d.name} ${d.platform}`.toLowerCase().includes(filter.toLowerCase())).sort((a, b) => b.createdAt - a.createdAt);
|
||||
return (
|
||||
<Card
|
||||
title={`Devices · ${q.data.length}`}
|
||||
actions={<input className="text-input compact" placeholder="Filter devices" value={filter} onChange={(e) => setFilter(e.target.value)} />}
|
||||
>
|
||||
<p className="muted card-lede">Apps and devices that have connected to this server. Removing one signs it out of this server.</p>
|
||||
{list.map((d) => (
|
||||
<div key={d.id} className="library-manage-row">
|
||||
<div className="lib-ico">
|
||||
<Icon name="monitor" size={17} />
|
||||
</div>
|
||||
<div className="library-manage-text">
|
||||
<strong>{d.name || 'Unnamed device'}</strong>
|
||||
<small>
|
||||
{d.platform || 'Unknown platform'} · First seen {date(d.createdAt)}
|
||||
</small>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (!(await confirmDialog({ title: `Remove ${d.name || 'this device'}?`, message: 'It will need to sign in again to use this server.', confirm: 'Remove', danger: true }))) return;
|
||||
admin.removeDevice(server, d.id).then(() => (toast('Device removed', 'success'), q.refetch()), toastError);
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function Troubleshooting() {
|
||||
const server = useServer();
|
||||
const [busy, setBusy] = useState('');
|
||||
const run = async (key: string, fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(key);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
const download = async (key: string, path: string, name: string) => {
|
||||
if (!isNative) return toast('Saving files needs the desktop app.', 'error');
|
||||
const target = await saveFile(name);
|
||||
if (!target) return;
|
||||
await run(key, async () => {
|
||||
const bytes = await invoke<number>('save_url', { url: server.signed(path), path: target });
|
||||
return bytes;
|
||||
}, `Saved ${name}`);
|
||||
};
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Diagnostics" description="Share these with Plex support or keep them for your records.">
|
||||
<Pref label="Download logs" description="A zip of the server’s recent log files.">
|
||||
<Button variant="ghost" size="sm" icon="download" busy={busy === 'logs'} onClick={() => download('logs', '/diagnostics/logs', `Plex Media Server Logs ${stamp}.zip`)}>
|
||||
Download
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Download database" description="A copy of the library database (it can be large).">
|
||||
<Button variant="ghost" size="sm" icon="download" busy={busy === 'db'} onClick={() => download('db', '/diagnostics/databases', `Plex Media Server Databases ${stamp}.zip`)}>
|
||||
Download
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Maintenance">
|
||||
<Pref label="Clean bundles" description="Removes leftover metadata for media that no longer exists.">
|
||||
<Button variant="ghost" size="sm" busy={busy === 'bundles'} onClick={() => run('bundles', () => admin.cleanBundles(server), 'Cleaning bundles')}>
|
||||
Run
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Optimize database" description="Compacts the database. Plex may be slow while this runs.">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
busy={busy === 'optimize'}
|
||||
onClick={async () =>
|
||||
(await confirmDialog({ title: 'Optimize the database?', message: 'Browsing may be slow until it finishes.', confirm: 'Optimize' })) && run('optimize', () => admin.optimizeDatabase(server), 'Optimizing the database')
|
||||
}
|
||||
>
|
||||
Run
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Empty trash in every library" description="Removes items whose files are gone.">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
busy={busy === 'trash'}
|
||||
onClick={() =>
|
||||
run(
|
||||
'trash',
|
||||
async () => {
|
||||
const secs = await import('../../plex/api').then((m) => m.sections(server));
|
||||
await Promise.all(secs.map((s) => admin.emptyTrash(server, s.id)));
|
||||
},
|
||||
'Emptied trash',
|
||||
)
|
||||
}
|
||||
>
|
||||
Run
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface LogLine {
|
||||
level: number;
|
||||
message: string;
|
||||
at: number;
|
||||
}
|
||||
|
||||
const LEVELS = ['Error', 'Warning', 'Info', 'Debug', 'Verbose'];
|
||||
|
||||
function Console() {
|
||||
const server = useServer();
|
||||
const [lines, setLines] = useState<LogLine[]>([]);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [state, setState] = useState<'connecting' | 'live' | 'closed'>('connecting');
|
||||
const [verbose, setVerbose] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const pausedRef = useRef(paused);
|
||||
pausedRef.current = paused;
|
||||
|
||||
useEffect(() => {
|
||||
const url = server.signed('/:/websockets/notifications', { filters: 'log' }).replace(/^http/, 'ws');
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => setState('live');
|
||||
ws.onclose = () => setState('closed');
|
||||
ws.onerror = () => setState('closed');
|
||||
ws.onmessage = (e) => {
|
||||
if (pausedRef.current) return;
|
||||
try {
|
||||
const c = JSON.parse(e.data)?.NotificationContainer;
|
||||
const logs = (c?.LogSentNotification ?? c?.Log ?? []) as any[];
|
||||
if (!logs.length) return;
|
||||
setLines((prev) =>
|
||||
[...prev, ...logs.map((l) => ({ level: Number(l.level ?? 2), message: String(l.message ?? ''), at: Date.parse(l.time) || Date.now() }))].slice(-1500),
|
||||
);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
return () => ws.close();
|
||||
}, [server]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = box.current;
|
||||
if (el && !paused) el.scrollTop = el.scrollHeight;
|
||||
}, [lines, paused]);
|
||||
|
||||
const shown = lines.filter((l) => verbose || l.level <= 2);
|
||||
return (
|
||||
<Card
|
||||
title="Server console"
|
||||
actions={
|
||||
<div className="actions">
|
||||
<span className={`status-tag${state === 'live' ? '' : ' off'}`}>
|
||||
<i className="dot" />
|
||||
{state === 'live' ? 'Live' : state === 'connecting' ? 'Connecting' : 'Disconnected'}
|
||||
</span>
|
||||
<label className="inline-toggle">
|
||||
Debug
|
||||
<Switch checked={verbose} onChange={setVerbose} />
|
||||
</label>
|
||||
<Button variant="ghost" size="sm" icon={paused ? 'play' : 'pause'} onClick={() => setPaused(!paused)}>
|
||||
{paused ? 'Resume' : 'Pause'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setLines([])}>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="console selectable" ref={box}>
|
||||
{!shown.length && <div className="dim">Waiting for server log messages…</div>}
|
||||
{shown.map((l, i) => (
|
||||
<div key={i} className={`console-line l${l.level}`}>
|
||||
<span className="console-time">{new Date(l.at).toLocaleTimeString()}</span>
|
||||
<span className="console-level">{LEVELS[l.level] ?? l.level}</span>
|
||||
<span>{l.message}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="note">Shows messages as the server writes them.</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerManage({ tab }: { tab: 'devices' | 'troubleshooting' | 'console' }) {
|
||||
if (tab === 'devices') return <Devices />;
|
||||
if (tab === 'troubleshooting') return <Troubleshooting />;
|
||||
return <Console />;
|
||||
}
|
||||
287
src/screens/settings/ServerPrefs.tsx
Normal file
287
src/screens/settings/ServerPrefs.tsx
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
import { useMemo, useState } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import { queryClient, useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { relativeTime } from '../../app/format';
|
||||
import { Button, ErrorState, PageLoader, Select, Switch } from '../../ui/primitives';
|
||||
import { toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card, Pref, SettingsSection } from './parts';
|
||||
|
||||
/** Which Plex preference groups each page shows; Live TV/DVR and online sources are excluded. */
|
||||
const GROUPS: Record<string, { groups: string[]; title: string; description: string; exclude?: RegExp; include?: RegExp }> = {
|
||||
general: { groups: ['general'], title: 'Server identity', description: 'How this server identifies itself and reports problems.' },
|
||||
remote: { groups: [], title: 'Remote access', description: '' },
|
||||
library: { groups: ['library'], title: 'Library', description: 'How Plex watches folders, scans media and generates previews and markers.', exclude: /^Music|Photo|Camera/ },
|
||||
network: { groups: ['network'], title: 'Network', description: 'Connections, security and the networks treated as local.', exclude: /RemoteAccess|PublishServer|ManualPortMapping/ },
|
||||
transcoder: { groups: ['transcoder'], title: 'Transcoder', description: 'How the server converts video for devices that can’t play it directly.' },
|
||||
extras: { groups: ['extras'], title: 'Extras', description: 'Trailers and extras before movies, for clients that support cinema trailers.' },
|
||||
scheduled: { groups: ['butler'], title: 'Maintenance window', description: 'Plex runs background maintenance during these hours.' },
|
||||
dlna: { groups: ['dlna'], title: 'DLNA', description: 'Lets DLNA devices on your network browse and play this server’s media.' },
|
||||
};
|
||||
|
||||
function hourLabel(h: number) {
|
||||
const d = new Date();
|
||||
d.setHours(h, 0, 0, 0);
|
||||
return d.toLocaleTimeString([], { hour: 'numeric' });
|
||||
}
|
||||
|
||||
function SettingControl({ setting, value, onChange }: { setting: admin.ServerSetting; value: unknown; onChange: (v: string | number | boolean) => void }) {
|
||||
if (setting.type === 'bool') return <Switch checked={value === true || value === 'true' || value === 1} onChange={onChange} label={setting.label} />;
|
||||
if (setting.options) {
|
||||
return (
|
||||
<Select
|
||||
value={String(value)}
|
||||
options={setting.options.map((o) => ({ value: o.value, label: o.label }))}
|
||||
onChange={(v) => onChange(setting.type === 'int' ? Number(v) : v)}
|
||||
minWidth={200}
|
||||
className="pref-select"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (/StartHour|EndHour/.test(setting.id)) {
|
||||
return <Select value={Number(value)} options={Array.from({ length: 24 }, (_, h) => ({ value: h, label: hourLabel(h) }))} onChange={onChange} />;
|
||||
}
|
||||
return (
|
||||
<input
|
||||
className="text-input pref-input"
|
||||
type={setting.type === 'int' || setting.type === 'double' ? 'number' : setting.id.toLowerCase().includes('password') ? 'password' : 'text'}
|
||||
value={String(value ?? '')}
|
||||
placeholder={setting.default !== undefined && setting.default !== '' ? String(setting.default) : ''}
|
||||
onChange={(e) => onChange(setting.type === 'int' || setting.type === 'double' ? (e.target.value === '' ? '' : Number(e.target.value)) as number : e.target.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PrefsEditor({ tab }: { tab: string }) {
|
||||
const server = useServer();
|
||||
const cfg = GROUPS[tab];
|
||||
const q = useServerQuery(['serverPrefs'], (s) => admin.prefs(s), { staleTime: 0 });
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
const [edits, setEdits] = useState<Record<string, string | number | boolean>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const settings = useMemo(
|
||||
() => (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && (advanced || !x.advanced) && !(cfg.exclude && cfg.exclude.test(x.id))),
|
||||
[q.data, tab, advanced],
|
||||
);
|
||||
const advancedCount = (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && x.advanced).length;
|
||||
const dirty = Object.keys(edits).length > 0;
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await admin.setPrefs(server, edits);
|
||||
toast('Server settings saved', 'success');
|
||||
setEdits({});
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'serverPrefs'] });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (q.isError) return <ErrorState error={q.error} onRetry={() => q.refetch()} />;
|
||||
if (!q.data) return <PageLoader />;
|
||||
return (
|
||||
<>
|
||||
<SettingsSection
|
||||
title={cfg.title}
|
||||
description={cfg.description}
|
||||
actions={
|
||||
advancedCount > 0 && (
|
||||
<label className="inline-toggle">
|
||||
Show advanced
|
||||
<Switch checked={advanced} onChange={setAdvanced} />
|
||||
</label>
|
||||
)
|
||||
}
|
||||
>
|
||||
{settings.map((s) => (
|
||||
<Pref key={s.id} label={s.label} description={s.summary}>
|
||||
<SettingControl setting={s} value={s.id in edits ? edits[s.id] : s.value} onChange={(v) => setEdits((e) => (v === s.value ? (({ [s.id]: _, ...rest }) => rest)(e) : { ...e, [s.id]: v }))} />
|
||||
</Pref>
|
||||
))}
|
||||
{!settings.length && <p className="muted">No settings in this group.</p>}
|
||||
</SettingsSection>
|
||||
<div className={`save-bar${dirty ? ' show' : ''}`}>
|
||||
<span>
|
||||
{Object.keys(edits).length} unsaved change{Object.keys(edits).length === 1 ? '' : 's'}
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEdits({})}>
|
||||
Discard
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" icon="check" busy={busy} onClick={save}>
|
||||
Save changes
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoteAccess() {
|
||||
const server = useServer();
|
||||
const status = useServerQuery(['remoteAccess'], (s) => admin.remoteAccess(s), { refetchInterval: 10000, staleTime: 0 });
|
||||
const prefs = useServerQuery(['serverPrefs'], (s) => admin.prefs(s), { staleTime: 0 });
|
||||
const get = (id: string) => prefs.data?.find((p) => p.id === id);
|
||||
const enabled = get('PublishServerOnPlexOnlineKey')?.value === true;
|
||||
const manual = get('ManualPortMappingMode')?.value === true || get('ManualPortMappingMode')?.value === 1;
|
||||
const [port, setPort] = useState<string>('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const r = status.data;
|
||||
const mapped = r?.mappingState === 'mapped';
|
||||
|
||||
const run = async (fn: () => Promise<unknown>, done?: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
if (done) toast(done, 'success');
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'serverPrefs'] });
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'remoteAccess'] });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!r || !prefs.data) return <PageLoader />;
|
||||
return (
|
||||
<>
|
||||
<Card className={`remote-status ${mapped && enabled ? 'good' : 'warn'}`}>
|
||||
<div className="remote-status-row">
|
||||
<div className="remote-icon">
|
||||
<Icon name={mapped && enabled ? 'globe' : 'alert'} size={22} />
|
||||
</div>
|
||||
<div>
|
||||
<h2>{!enabled ? 'Remote access is off' : mapped ? 'Fully accessible outside your network' : r.reachabilityPending ? 'Checking reachability…' : 'Not reachable outside your network'}</h2>
|
||||
<p className="muted">
|
||||
{enabled
|
||||
? `Public ${r.publicAddress || '—'}:${r.publicPort || '—'} → private ${r.privateAddress || '—'}:${r.privatePort || '—'}`
|
||||
: 'Turn on remote access to stream away from home without Plex Relay limits.'}
|
||||
{r.mappingError && ` · ${r.mappingError}`}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={busy} disabled={!enabled} onClick={() => run(() => admin.refreshReachability(server), 'Retrying remote access')}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
<SettingsSection title="Remote access">
|
||||
<Pref label="Enable remote access" description="Publishes this server to plex.tv so your devices can reach it from anywhere.">
|
||||
<Switch checked={enabled} disabled={busy} onChange={(v) => run(() => admin.setPrefs(server, { PublishServerOnPlexOnlineKey: v }), v ? 'Remote access enabled' : 'Remote access disabled')} />
|
||||
</Pref>
|
||||
<Pref label="Manually specify public port" description="Use when your router doesn’t support UPnP/NAT-PMP; forward this port to the server.">
|
||||
<Switch checked={!!manual} disabled={busy || !enabled} onChange={(v) => run(() => admin.setPrefs(server, { ManualPortMappingMode: v }))} />
|
||||
</Pref>
|
||||
{manual && (
|
||||
<Pref label="Public port">
|
||||
<input className="text-input pref-input" type="number" value={port || String(get('ManualPortMappingPort')?.value ?? '')} onChange={(e) => setPort(e.target.value)} />
|
||||
<Button variant="ghost" size="sm" disabled={!port} onClick={() => run(() => admin.setPrefs(server, { ManualPortMappingPort: Number(port) }), 'Port saved')}>
|
||||
Apply
|
||||
</Button>
|
||||
</Pref>
|
||||
)}
|
||||
{get('WanPerStreamMaxUploadRate') && (
|
||||
<Pref label={get('WanPerStreamMaxUploadRate')!.label} description={get('WanPerStreamMaxUploadRate')!.summary}>
|
||||
<SettingControl setting={get('WanPerStreamMaxUploadRate')!} value={get('WanPerStreamMaxUploadRate')!.value} onChange={(v) => run(() => admin.setPrefs(server, { WanPerStreamMaxUploadRate: v }), 'Saved')} />
|
||||
</Pref>
|
||||
)}
|
||||
{get('WanTotalMaxUploadRate') && (
|
||||
<Pref label={get('WanTotalMaxUploadRate')!.label} description={get('WanTotalMaxUploadRate')!.summary}>
|
||||
<input className="text-input pref-input" type="number" defaultValue={String(get('WanTotalMaxUploadRate')!.value ?? '')} onBlur={(e) => run(() => admin.setPrefs(server, { WanTotalMaxUploadRate: Number(e.target.value) }), 'Saved')} />
|
||||
</Pref>
|
||||
)}
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ScheduledTasks() {
|
||||
const server = useServer();
|
||||
const tasks = useServerQuery(['butlerTasks'], (s) => admin.butlerTasks(s));
|
||||
const [running, setRunning] = useState('');
|
||||
const run = async (t: admin.ButlerTask) => {
|
||||
setRunning(t.name);
|
||||
try {
|
||||
await admin.runButlerTask(server, t.name);
|
||||
toast(`Started “${t.title}”`, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setRunning('');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<PrefsEditor tab="scheduled" />
|
||||
<SettingsSection
|
||||
title="Tasks"
|
||||
description="Run maintenance now instead of waiting for the window."
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" icon="x" onClick={() => admin.stopButlerTasks(server).then(() => toast('Stopped running tasks', 'success'), toastError)}>
|
||||
Stop all
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{tasks.data?.map((t) => (
|
||||
<Pref key={t.name} label={t.title} description={[t.description, `Every ${t.interval} day${t.interval === 1 ? '' : 's'}`, t.enabled ? '' : 'Disabled'].filter(Boolean).join(' · ')}>
|
||||
<Button variant="ghost" size="sm" icon="play" busy={running === t.name} onClick={() => run(t)}>
|
||||
Run now
|
||||
</Button>
|
||||
</Pref>
|
||||
))}
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ServerUpdates() {
|
||||
const server = useServer();
|
||||
const status = useServerQuery(['serverUpdate'], (s) => admin.updateStatus(s), { staleTime: 0 });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const u = status.data;
|
||||
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
setTimeout(() => status.refetch(), 3000);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<SettingsSection title="Plex Media Server updates">
|
||||
<Pref
|
||||
label={u?.version ? `Version ${u.version} is ${u.state === 'downloaded' ? 'ready to install' : 'available'}` : 'No update pending'}
|
||||
description={u?.checkedAt ? `Checked ${relativeTime(u.checkedAt)}` : 'Plex checks for updates automatically.'}
|
||||
>
|
||||
{u?.version && u.canInstall ? (
|
||||
<Button variant="primary" size="sm" busy={busy} onClick={() => run(() => admin.applyUpdate(server), 'Installing the update; the server will restart')}>
|
||||
Install now
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={busy} onClick={() => run(() => admin.checkForUpdates(server), 'Checking for server updates')}>
|
||||
Check now
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
{u?.added && <p className="release-notes selectable">{u.added}</p>}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerPrefs({ tab }: { tab: string }) {
|
||||
if (tab === 'remote') return <RemoteAccess />;
|
||||
if (tab === 'scheduled') return <ScheduledTasks />;
|
||||
if (!GROUPS[tab]) return null;
|
||||
return (
|
||||
<>
|
||||
<PrefsEditor tab={tab} />
|
||||
{tab === 'general' && <ServerUpdates />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
140
src/screens/settings/Settings.tsx
Normal file
140
src/screens/settings/Settings.tsx
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import { lazy, Suspense, type ReactNode } from 'react';
|
||||
import { navigate } from '../../app/router';
|
||||
import { useSession } from '../../app/session';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { AppSettings } from './AppSettings';
|
||||
|
||||
const ServerDashboard = lazy(() => import('./ServerDashboard'));
|
||||
const ServerPrefs = lazy(() => import('./ServerPrefs'));
|
||||
const ServerLibraries = lazy(() => import('./ServerLibraries'));
|
||||
const ServerManage = lazy(() => import('./ServerManage'));
|
||||
|
||||
type NavGroup = { group: string; items: { id: string; label: string; icon: string }[] };
|
||||
|
||||
export const APP_NAV: NavGroup[] = [
|
||||
{
|
||||
group: 'Preferences',
|
||||
items: [
|
||||
{ id: 'general', label: 'General', icon: 'settings' },
|
||||
{ id: 'playback', label: 'Playback', icon: 'playCircle' },
|
||||
{ id: 'subtitles', label: 'Audio & subtitles', icon: 'captions' },
|
||||
{ id: 'interface', label: 'Interface', icon: 'palette' },
|
||||
{ id: 'downloads', label: 'Downloads', icon: 'download' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Help',
|
||||
items: [
|
||||
{ id: 'shortcuts', label: 'Keyboard shortcuts', icon: 'keyboard' },
|
||||
{ id: 'about', label: 'About & updates', icon: 'info' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const SERVER_NAV: NavGroup[] = [
|
||||
{
|
||||
group: 'Status',
|
||||
items: [
|
||||
{ id: 'dashboard', label: 'Dashboard', icon: 'activity' },
|
||||
{ id: 'activity', label: 'Activity & history', icon: 'clock' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Settings',
|
||||
items: [
|
||||
{ id: 'general', label: 'General', icon: 'settings' },
|
||||
{ id: 'remote', label: 'Remote access', icon: 'globe' },
|
||||
{ id: 'library', label: 'Library', icon: 'film' },
|
||||
{ id: 'network', label: 'Network', icon: 'network' },
|
||||
{ id: 'transcoder', label: 'Transcoder', icon: 'cpu' },
|
||||
{ id: 'extras', label: 'Extras', icon: 'sparkle' },
|
||||
{ id: 'scheduled', label: 'Scheduled tasks', icon: 'calendar' },
|
||||
{ id: 'dlna', label: 'DLNA', icon: 'tv' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Manage',
|
||||
items: [
|
||||
{ id: 'libraries', label: 'Libraries', icon: 'folder' },
|
||||
{ id: 'devices', label: 'Devices', icon: 'monitor' },
|
||||
{ id: 'troubleshooting', label: 'Troubleshooting', icon: 'tool' },
|
||||
{ id: 'console', label: 'Console', icon: 'terminal' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function serverContent(tab: string): ReactNode {
|
||||
switch (tab) {
|
||||
case 'dashboard':
|
||||
case 'activity':
|
||||
return <ServerDashboard tab={tab} />;
|
||||
case 'libraries':
|
||||
return <ServerLibraries />;
|
||||
case 'devices':
|
||||
case 'troubleshooting':
|
||||
case 'console':
|
||||
return <ServerManage tab={tab} />;
|
||||
default:
|
||||
return <ServerPrefs tab={tab} />;
|
||||
}
|
||||
}
|
||||
|
||||
export default function Settings({ mode, tab }: { mode: 'app' | 'server'; tab: string }) {
|
||||
const server = useSession((s) => s.server);
|
||||
const owned = !!server?.owned;
|
||||
const nav = mode === 'app' ? APP_NAV : SERVER_NAV;
|
||||
const label = nav.flatMap((g) => g.items).find((i) => i.id === tab)?.label ?? 'Settings';
|
||||
const go = (m: 'app' | 'server', t: string) => navigate({ name: 'settings', mode: m, tab: t }, { replace: true });
|
||||
|
||||
return (
|
||||
<div className="settings-shell">
|
||||
<aside className="settings-nav">
|
||||
<h3>Settings</h3>
|
||||
<div className="seg settings-mode">
|
||||
<button className={mode === 'app' ? 'selected' : ''} onClick={() => go('app', 'general')}>
|
||||
Kaleido
|
||||
</button>
|
||||
<button className={mode === 'server' ? 'selected' : ''} onClick={() => go('server', 'dashboard')}>
|
||||
Plex server
|
||||
</button>
|
||||
</div>
|
||||
{nav.map((g) => (
|
||||
<div key={g.group}>
|
||||
<div className="settings-group">{g.group}</div>
|
||||
{g.items.map((i) => (
|
||||
<button key={i.id} className={`settings-link${i.id === tab ? ' selected' : ''}`} onClick={() => go(mode, i.id)}>
|
||||
<Icon name={i.icon} size={16} />
|
||||
{i.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
<div className="settings-main">
|
||||
<div className="settings-inner" key={`${mode}-${tab}`}>
|
||||
<div className="settings-header">
|
||||
<div>
|
||||
<div className="micro">{mode === 'server' ? `Plex server / ${server?.name ?? ''}` : 'Kaleido / This computer'}</div>
|
||||
<h1 className="page-title">{label}</h1>
|
||||
</div>
|
||||
{mode === 'server' && server && (
|
||||
<span className="status-tag">
|
||||
<i className="dot" /> {server.name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{mode === 'app' ? (
|
||||
<AppSettings tab={tab} />
|
||||
) : !owned ? (
|
||||
<EmptyState icon="lock" title="Server management needs the owner">
|
||||
{server?.name ?? 'This server'} is shared with you. Only its owner can view the dashboard and change server settings.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<Suspense fallback={<PageLoader />}>{serverContent(tab)}</Suspense>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
52
src/screens/settings/parts.tsx
Normal file
52
src/screens/settings/parts.tsx
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import type { ReactNode } from 'react';
|
||||
|
||||
export function SettingsSection({ title, description, children, actions }: { title: string; description?: ReactNode; children: ReactNode; actions?: ReactNode }) {
|
||||
return (
|
||||
<section className="settings-section">
|
||||
<div className="settings-section-head">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{description && <p>{description}</p>}
|
||||
</div>
|
||||
{actions}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Pref({ label, description, children, wide }: { label: ReactNode; description?: ReactNode; children?: ReactNode; wide?: boolean }) {
|
||||
return (
|
||||
<div className={`pref${wide ? ' wide' : ''}`}>
|
||||
<div className="pref-text">
|
||||
<strong>{label}</strong>
|
||||
{description && <p>{description}</p>}
|
||||
</div>
|
||||
{children && <div className="pref-control">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatTile({ label, value, detail, tone }: { label: string; value: ReactNode; detail?: ReactNode; tone?: 'good' | 'warn' }) {
|
||||
return (
|
||||
<div className={`stat-tile${tone ? ` ${tone}` : ''}`}>
|
||||
<label>{label}</label>
|
||||
<strong>{value}</strong>
|
||||
{detail && <small>{detail}</small>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({ title, children, actions, className = '' }: { title?: ReactNode; children: ReactNode; actions?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={`admin-card ${className}`}>
|
||||
{(title || actions) && (
|
||||
<div className="admin-card-head">
|
||||
{title && <h2>{title}</h2>}
|
||||
{actions}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue