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
258
src/app/App.tsx
Normal file
258
src/app/App.tsx
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { queryClient, invalidateLibrary } from './queries';
|
||||
import { useSession } from './session';
|
||||
import { useRouter, navigate, type Route } from './router';
|
||||
import { useSettings } from './settings';
|
||||
import { TopBar } from './TopBar';
|
||||
import { MenuHost, ToastHost, ConfirmHost } from '../ui/overlays';
|
||||
import { HoverPreviewHost } from '../ui/HoverPreview';
|
||||
import { PageLoader } from '../ui/primitives';
|
||||
import { Splash } from '../screens/Splash';
|
||||
import { SignIn } from '../screens/SignIn';
|
||||
import { ServerPicker } from '../screens/ServerPicker';
|
||||
import { win } from '../platform/native';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { PlayerOverlay } from '../player/PlayerOverlay';
|
||||
import { DialogHost } from '../screens/dialogs/DialogHost';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { libraryRevision } from '../plex/api';
|
||||
import { checkForUpdate } from './updater';
|
||||
import { Home } from '../screens/Home';
|
||||
import { SectionScreen } from '../screens/Section';
|
||||
import { ItemScreen } from '../screens/Item';
|
||||
|
||||
const Search = lazy(() => import('../screens/Search'));
|
||||
const Downloads = lazy(() => import('../screens/Downloads'));
|
||||
const Settings = lazy(() => import('../screens/settings/Settings'));
|
||||
const Person = lazy(() => import('../screens/Person'));
|
||||
const HubScreen = lazy(() => import('../screens/HubScreen'));
|
||||
|
||||
function Screen({ route }: { route: Route }) {
|
||||
switch (route.name) {
|
||||
case 'home':
|
||||
return <Home />;
|
||||
case 'section':
|
||||
return <SectionScreen kind={route.kind} tab={route.tab} />;
|
||||
case 'item':
|
||||
return <ItemScreen id={route.id} />;
|
||||
case 'person':
|
||||
return <Person id={route.id} title={route.title} thumb={route.thumb} />;
|
||||
case 'hub':
|
||||
return <HubScreen hubKey={route.key} title={route.title} />;
|
||||
case 'search':
|
||||
return <Search initial={route.query} />;
|
||||
case 'downloads':
|
||||
return <Downloads />;
|
||||
case 'settings':
|
||||
return <Settings mode={route.mode} tab={route.tab} />;
|
||||
}
|
||||
}
|
||||
|
||||
/** One scroll container per history entry; its position is restored on Back. */
|
||||
function Page({ onScrolled }: { onScrolled: (top: number) => void }) {
|
||||
const entry = useRouter((s) => s.current);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const target = entry.scroll;
|
||||
el.scrollTop = target;
|
||||
onScrolled(target);
|
||||
if (!target) return;
|
||||
// Content may still be loading; keep trying briefly until it is tall enough.
|
||||
let tries = 0;
|
||||
const t = setInterval(() => {
|
||||
if (!ref.current || tries++ > 30) return clearInterval(t);
|
||||
ref.current.scrollTop = target;
|
||||
if (Math.abs(ref.current.scrollTop - target) < 2) clearInterval(t);
|
||||
}, 50);
|
||||
return () => clearInterval(t);
|
||||
}, [entry]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="main-scroll"
|
||||
data-route={entry.route.name}
|
||||
onScroll={(e) => {
|
||||
const top = (e.target as HTMLDivElement).scrollTop;
|
||||
entry.scroll = top;
|
||||
onScrolled(top);
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<main className="page-enter" key={entry.id}>
|
||||
<Screen route={entry.route} />
|
||||
</main>
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useGlobalShortcuts() {
|
||||
useEffect(() => {
|
||||
const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName));
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (usePlayer.getState().open) return;
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'search' });
|
||||
} else if (e.altKey && e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
useRouter.getState().back();
|
||||
} else if (e.altKey && e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
useRouter.getState().forward();
|
||||
} else if (e.key === 'F11') {
|
||||
e.preventDefault();
|
||||
win.isFullscreen().then((fs) => win.setFullscreen(!fs));
|
||||
} else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) {
|
||||
if (e.key === 'Escape' && document.fullscreenElement) return;
|
||||
useRouter.getState().back();
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'settings', mode: 'app', tab: 'general' });
|
||||
}
|
||||
};
|
||||
// Mouse back/forward buttons.
|
||||
const onMouse = (e: MouseEvent) => {
|
||||
if (usePlayer.getState().open) return;
|
||||
if (e.button === 3) {
|
||||
e.preventDefault();
|
||||
useRouter.getState().back();
|
||||
} else if (e.button === 4) {
|
||||
e.preventDefault();
|
||||
useRouter.getState().forward();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
window.addEventListener('mouseup', onMouse);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('mouseup', onMouse);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** Refreshes browsing when the server's libraries change. */
|
||||
function useLibrarySync() {
|
||||
const server = useSession((s) => s.server);
|
||||
useEffect(() => {
|
||||
if (!server) return;
|
||||
let last = '';
|
||||
let stopped = false;
|
||||
const tick = async () => {
|
||||
if (stopped || document.hidden || usePlayer.getState().open) return;
|
||||
try {
|
||||
const rev = await libraryRevision(server);
|
||||
if (last && rev !== last) invalidateLibrary();
|
||||
last = rev;
|
||||
} catch {
|
||||
/* transient */
|
||||
}
|
||||
};
|
||||
tick();
|
||||
const t = setInterval(tick, 20000);
|
||||
const onVisible = () => !document.hidden && tick();
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearInterval(t);
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [server]);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
const playerOpen = usePlayer((s) => s.open);
|
||||
const startPage = useSettings.getState().startPage;
|
||||
useGlobalShortcuts();
|
||||
useLibrarySync();
|
||||
useEffect(() => {
|
||||
if (startPage !== 'home') useRouter.getState().reset(startPage === 'movies' ? { name: 'section', kind: 'movie', tab: 'discover' } : { name: 'section', kind: 'show', tab: 'discover' });
|
||||
useDownloads.getState().init().then(() => useDownloads.getState().resumeInterrupted());
|
||||
const t = setTimeout(() => checkForUpdate(false), 8000);
|
||||
return () => clearTimeout(t);
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<div className="app-shell" aria-hidden={playerOpen}>
|
||||
<TopBar solid={scrolled} />
|
||||
<Page onScrolled={(top) => setScrolled(top > 24)} />
|
||||
</div>
|
||||
<PlayerOverlay />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function OfflineShell() {
|
||||
const error = useSession((s) => s.error);
|
||||
const init = useSession((s) => s.init);
|
||||
useEffect(() => {
|
||||
useDownloads.getState().init();
|
||||
useRouter.getState().reset({ name: 'downloads' });
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<div className="app-shell offline">
|
||||
<div className="offline-banner" data-tauri-drag-region>
|
||||
<span>{error || 'You’re offline.'}</span>
|
||||
<button className="btn text" onClick={() => init()}>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
<div className="main-scroll">
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<Downloads offline />
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
<PlayerOverlay />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const status = useSession((s) => s.status);
|
||||
const hasServer = useSession((s) => !!s.server);
|
||||
const reducedMotion = useSettings((s) => s.reducedMotion);
|
||||
const [splashDone, setSplashDone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
useSession.getState().init();
|
||||
// The window appears once the first frame is painted (no white flash).
|
||||
requestAnimationFrame(() => win.show());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('reduced-motion', reducedMotion);
|
||||
}, [reducedMotion]);
|
||||
|
||||
// Switching servers or users starts browsing fresh.
|
||||
const serverId = useSession((s) => s.server?.machineId);
|
||||
useEffect(() => {
|
||||
if (serverId) useRouter.getState().reset({ name: 'home' });
|
||||
}, [serverId]);
|
||||
|
||||
let body;
|
||||
if (status === 'loading') body = null;
|
||||
else if (status === 'signed-out') body = <SignIn />;
|
||||
else if (status === 'choose-server' || (status === 'connecting' && !hasServer)) body = <ServerPicker />;
|
||||
else if (status === 'offline') body = <OfflineShell />;
|
||||
else body = <Shell />;
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{body}
|
||||
{(!splashDone || status === 'loading') && <Splash ready={status !== 'loading'} onDone={() => setSplashDone(true)} />}
|
||||
<HoverPreviewHost />
|
||||
<DialogHost />
|
||||
<MenuHost />
|
||||
<ConfirmHost />
|
||||
<ToastHost />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
126
src/app/TopBar.tsx
Normal file
126
src/app/TopBar.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { navigate, topLevel, useRouter } from './router';
|
||||
import { useSession } from './session';
|
||||
import { useSettings } from './settings';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { KaleidoMark } from '../ui/primitives';
|
||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||
import { isNative, win } from '../platform/native';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { useHomeUsers } from './useHomeUsers';
|
||||
|
||||
const NAV = [
|
||||
{ id: 'home', label: 'Home', route: { name: 'home' } as const },
|
||||
{ id: 'movies', label: 'Movies', route: { name: 'section', kind: 'movie', tab: 'discover' } as const },
|
||||
{ id: 'shows', label: 'TV Shows', route: { name: 'section', kind: 'show', tab: 'discover' } as const },
|
||||
{ id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const },
|
||||
];
|
||||
|
||||
function WindowControls() {
|
||||
const [maximized, setMaximized] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!isNative) return;
|
||||
let off: (() => void) | undefined;
|
||||
const sync = () => win.isMaximized().then(setMaximized);
|
||||
sync();
|
||||
win.onResized(sync).then((u) => (off = u));
|
||||
return () => off?.();
|
||||
}, []);
|
||||
if (!isNative) return null;
|
||||
return (
|
||||
<div className="window-controls">
|
||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
||||
<Icon name={maximized ? 'restore' : '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>
|
||||
);
|
||||
}
|
||||
|
||||
function Avatar() {
|
||||
const user = useSession((s) => s.user);
|
||||
const server = useSession((s) => s.server);
|
||||
const connection = useSession((s) => s.connection);
|
||||
const showServerPicker = useSession((s) => s.showServerPicker);
|
||||
const signOut = useSession((s) => s.signOut);
|
||||
const home = useHomeUsers();
|
||||
const initial = (user?.title || server?.name || 'K').slice(0, 1).toUpperCase();
|
||||
const menu = (el: HTMLElement) => {
|
||||
const items: MenuItem[] = [
|
||||
{ heading: user ? user.title : 'Kaleido' },
|
||||
{
|
||||
label: server ? `${server.name}` : 'No server',
|
||||
hint: connection ? (connection.relay ? 'Relay' : connection.local ? 'Local' : 'Remote') : '',
|
||||
icon: 'server',
|
||||
onSelect: showServerPicker,
|
||||
},
|
||||
];
|
||||
if (home.users.length > 1) {
|
||||
items.push({
|
||||
label: 'Switch profile',
|
||||
icon: 'users',
|
||||
submenu: home.users.map((u) => ({ label: u.title, checked: u.uuid === user?.uuid, onSelect: () => home.switchTo(u) })),
|
||||
});
|
||||
}
|
||||
items.push(
|
||||
{ divider: true },
|
||||
{ label: 'Settings', icon: 'settings', onSelect: () => navigate({ name: 'settings', mode: 'app', tab: 'general' }) },
|
||||
);
|
||||
if (server?.owned) items.push({ label: 'Server dashboard', icon: 'activity', onSelect: () => navigate({ name: 'settings', mode: 'server', tab: 'dashboard' }) });
|
||||
items.push({ divider: true }, { label: 'Sign out', icon: 'logout', onSelect: signOut });
|
||||
openMenu(items, el, { align: 'end', minWidth: 250 });
|
||||
};
|
||||
return (
|
||||
<button className="avatar-btn" aria-label="Account" onClick={(e) => menu(e.currentTarget)}>
|
||||
{user?.thumb ? <img src={user.thumb} alt="" draggable={false} /> : <span>{initial}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function TopBar({ solid }: { solid: boolean }) {
|
||||
const current = useRouter((s) => s.current.route);
|
||||
const canBack = useRouter((s) => s.index > 0);
|
||||
const back = useRouter((s) => s.back);
|
||||
const active = topLevel(current);
|
||||
const activeDownloads = useDownloads((s) => s.items.filter((d) => d.status === 'downloading' || d.status === 'queued').length);
|
||||
const startPage = useSettings((s) => s.startPage);
|
||||
void startPage;
|
||||
const showBack = canBack && !active;
|
||||
|
||||
return (
|
||||
<header className={`topbar${solid ? ' solid' : ''}`} data-tauri-drag-region>
|
||||
<div className="topbar-left" data-tauri-drag-region>
|
||||
<button className={`nav-back${showBack ? ' show' : ''}`} aria-label="Back" onClick={back} tabIndex={showBack ? 0 : -1}>
|
||||
<Icon name="arrowLeft" size={19} />
|
||||
</button>
|
||||
<button className="brand" onClick={() => navigate({ name: 'home' })} aria-label="Kaleido home">
|
||||
<KaleidoMark size={24} />
|
||||
<span>KALEIDO</span>
|
||||
</button>
|
||||
<nav className="primary-nav" aria-label="Main navigation" data-tauri-drag-region>
|
||||
{NAV.map((n) => (
|
||||
<button key={n.id} className={`nav-item${active === n.id ? ' active' : ''}`} onClick={() => navigate(n.route)}>
|
||||
{n.label}
|
||||
{n.id === 'downloads' && activeDownloads > 0 && <span className="nav-count">{activeDownloads}</span>}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<div className="topbar-right" data-tauri-drag-region>
|
||||
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title="Search (Ctrl+K)" onClick={() => navigate({ name: 'search' })}>
|
||||
<Icon name="search" size={19} />
|
||||
</button>
|
||||
<button className={`icon-btn${active === 'settings' ? ' on' : ''}`} aria-label="Settings" title="Settings" onClick={() => navigate({ name: 'settings', mode: 'app', tab: 'general' })}>
|
||||
<Icon name="settings" size={19} />
|
||||
</button>
|
||||
<Avatar />
|
||||
<WindowControls />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
230
src/app/actions.ts
Normal file
230
src/app/actions.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import { create } from 'zustand';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { navigate } from './router';
|
||||
import { useSession } from './session';
|
||||
import { invalidateItem, invalidateLibrary } from './queries';
|
||||
import { isWatched } from './format';
|
||||
import { useSettings } from './settings';
|
||||
import { usePlayer, type PlayOptions } from '../player/store';
|
||||
import { confirmDialog, toast, toastError, type MenuItem } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
|
||||
const server = () => {
|
||||
const s = useSession.getState().server;
|
||||
if (!s) throw new Error('Not connected to a server.');
|
||||
return s;
|
||||
};
|
||||
|
||||
export const canManage = () => !!useSession.getState().server?.owned;
|
||||
|
||||
export function openItem(item: Item) {
|
||||
if (item.type === 'clip') {
|
||||
playItem(item, { resume: false });
|
||||
return;
|
||||
}
|
||||
if (item.type === 'person') {
|
||||
navigate({ name: 'person', id: item.id, title: item.title, thumb: item.thumb });
|
||||
return;
|
||||
}
|
||||
navigate({ name: 'item', id: item.id, title: item.title });
|
||||
}
|
||||
|
||||
/** Plays a title. Shows and seasons play their next episode. */
|
||||
export async function playItem(item: Item, opts: PlayOptions = {}) {
|
||||
try {
|
||||
if (item.type === 'show' || item.type === 'season') {
|
||||
const s = server();
|
||||
const full = await api.metadata(s, item.id);
|
||||
let next = await api.onDeckFor(s, full);
|
||||
if (!next) {
|
||||
const leaves = await api.allLeaves(s, item.id);
|
||||
next = leaves.find((e) => !isWatched(e)) ?? leaves[0] ?? null;
|
||||
}
|
||||
if (!next) throw new Error('There are no episodes to play.');
|
||||
await usePlayer.getState().play(next, { resume: true, ...opts });
|
||||
return;
|
||||
}
|
||||
if (item.type === 'collection') {
|
||||
const items = await api.collectionItems(server(), item.id);
|
||||
if (items[0]) await playItem(items[0], opts);
|
||||
return;
|
||||
}
|
||||
const local = useDownloads.getState().localFileFor(item.id);
|
||||
if (local && !opts.localFile && !useSession.getState().server) opts = { ...opts, localFile: local };
|
||||
await usePlayer.getState().play(item, { resume: true, ...opts });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function shuffleItem(item: Item) {
|
||||
try {
|
||||
const leaves = await api.allLeaves(server(), item.id);
|
||||
if (!leaves.length) return;
|
||||
const pick = leaves[Math.floor(Math.random() * leaves.length)];
|
||||
await usePlayer.getState().play(pick, { resume: false });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function setWatched(item: Item, watched: boolean) {
|
||||
try {
|
||||
await api.setWatched(server(), item.id, watched);
|
||||
toast(watched ? `Marked “${item.title}” watched` : `Marked “${item.title}” unwatched`, 'success');
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeFromContinueWatching(item: Item) {
|
||||
try {
|
||||
await api.removeFromContinueWatching(server(), item.id);
|
||||
toast('Removed from Continue Watching', 'success');
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function run(label: string, fn: () => Promise<unknown>, done?: string) {
|
||||
try {
|
||||
await fn();
|
||||
if (done) toast(done, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
void label;
|
||||
}
|
||||
|
||||
export const admin = {
|
||||
refresh: (item: Item) =>
|
||||
run('refresh', async () => {
|
||||
await api.refreshMetadata(server(), item.id);
|
||||
setTimeout(() => invalidateItem(item.id), 4000);
|
||||
}, `Refreshing metadata for “${item.title}”`),
|
||||
analyze: (item: Item) => run('analyze', () => api.analyze(server(), item.id), `Analyzing “${item.title}”`),
|
||||
unmatch: async (item: Item) => {
|
||||
if (!(await confirmDialog({ title: 'Unmatch this title?', message: `Plex will remove the metadata for “${item.title}” and show it by its file name until it is matched again.`, confirm: 'Unmatch', danger: true }))) return;
|
||||
await run('unmatch', async () => {
|
||||
await api.unmatch(server(), item.id);
|
||||
invalidateLibrary();
|
||||
}, 'Title unmatched');
|
||||
},
|
||||
split: async (item: Item) => {
|
||||
if (!(await confirmDialog({ title: 'Split apart?', message: `Each version of “${item.title}” will become a separate title.`, confirm: 'Split apart' }))) return;
|
||||
await run('split', async () => {
|
||||
await api.splitApart(server(), item.id);
|
||||
invalidateLibrary();
|
||||
}, 'Versions split apart');
|
||||
},
|
||||
remove: async (item: Item, onDone?: () => void) => {
|
||||
const ok = await confirmDialog({
|
||||
title: `Delete “${item.title}”?`,
|
||||
message: 'This permanently deletes the media files from the server’s disk and removes the title from the library. This cannot be undone.',
|
||||
confirm: 'Delete files',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.deleteItem(server(), item.id);
|
||||
toast(`Deleted “${item.title}”`, 'success');
|
||||
invalidateLibrary();
|
||||
onDone?.();
|
||||
} catch (e: any) {
|
||||
toast(e?.status === 403 || e?.status === 401 ? 'The server does not allow media deletion. Enable it in Settings › Plex server › Library.' : e.message, 'error');
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// —— Dialog routing ——————————————————————————————————————————————
|
||||
|
||||
export type DialogRequest =
|
||||
| { kind: 'edit'; item: Item }
|
||||
| { kind: 'match'; item: Item }
|
||||
| { kind: 'info'; item: Item }
|
||||
| { kind: 'artwork'; item: Item; type: 'poster' | 'art' | 'clearLogo' }
|
||||
| { kind: 'collection'; item: Item }
|
||||
| { kind: 'playlist'; item: Item }
|
||||
| { kind: 'trailer'; item: Item }
|
||||
| { kind: 'synopsis'; item: Item }
|
||||
| { kind: 'versions'; item: Item; onPick: (index: number) => void };
|
||||
|
||||
export const useDialogs = create<{ dialog: DialogRequest | null; open(d: DialogRequest): void; close(): void }>((set) => ({
|
||||
dialog: null,
|
||||
open: (dialog) => set({ dialog }),
|
||||
close: () => set({ dialog: null }),
|
||||
}));
|
||||
export const openDialog = (d: DialogRequest) => useDialogs.getState().open(d);
|
||||
|
||||
/** Plays with a version choice when a title has several. */
|
||||
export function playWithVersion(item: Item, opts: PlayOptions = {}) {
|
||||
if (item.media.length > 1 && opts.mediaIndex === undefined) {
|
||||
openDialog({ kind: 'versions', item, onPick: (mediaIndex) => playItem(item, { ...opts, mediaIndex }) });
|
||||
return;
|
||||
}
|
||||
playItem(item, opts);
|
||||
}
|
||||
|
||||
/** The full context menu for a title, as on cards and the detail page "More" button. */
|
||||
export function itemMenu(item: Item, ctx: { continueWatching?: boolean; onDeleted?: () => void; detail?: boolean } = {}): MenuItem[] {
|
||||
const owned = canManage();
|
||||
const playable = ['movie', 'episode', 'show', 'season', 'clip'].includes(item.type);
|
||||
const watched = isWatched(item, useSettings.getState().watchedPercent);
|
||||
const downloads = useDownloads.getState();
|
||||
const items: MenuItem[] = [];
|
||||
if (playable) {
|
||||
items.push({ label: item.viewOffset ? 'Resume' : 'Play', icon: 'play', onSelect: () => playWithVersion(item) });
|
||||
if (item.viewOffset) items.push({ label: 'Play from beginning', icon: 'replay10', onSelect: () => playWithVersion(item, { offsetMs: 0, resume: false }) });
|
||||
if (item.type === 'show' || item.type === 'season') items.push({ label: 'Shuffle episodes', icon: 'shuffle', onSelect: () => shuffleItem(item) });
|
||||
}
|
||||
if (!ctx.detail) items.push({ label: 'Details', icon: 'info', onSelect: () => openItem(item) });
|
||||
if (item.type === 'episode') {
|
||||
items.push({ label: 'Go to season', icon: 'layers', onSelect: () => navigate({ name: 'item', id: item.parentId }) });
|
||||
items.push({ label: 'Go to show', icon: 'tv', onSelect: () => navigate({ name: 'item', id: item.grandparentId }) });
|
||||
}
|
||||
if (item.type === 'season') items.push({ label: 'Go to show', icon: 'tv', onSelect: () => navigate({ name: 'item', id: item.parentId }) });
|
||||
if (playable && item.type !== 'clip') {
|
||||
items.push({ divider: true });
|
||||
items.push({ label: watched ? 'Mark unwatched' : 'Mark watched', icon: watched ? 'minus' : 'check', onSelect: () => setWatched(item, !watched) });
|
||||
if (ctx.continueWatching || (item.viewOffset > 0 && !watched)) items.push({ label: 'Remove from Continue Watching', icon: 'x', onSelect: () => removeFromContinueWatching(item) });
|
||||
}
|
||||
if (item.type === 'movie' || item.type === 'episode') {
|
||||
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
|
||||
items.push(
|
||||
dl
|
||||
? { label: dl.status === 'completed' ? 'Downloaded' : 'Downloading…', icon: 'downloaded', onSelect: () => navigate({ name: 'downloads' }) }
|
||||
: { label: 'Download', icon: 'download', onSelect: () => downloads.start(item) },
|
||||
);
|
||||
} else if (item.type === 'season' || item.type === 'show') {
|
||||
items.push({ label: item.type === 'show' ? 'Download all episodes' : 'Download season', icon: 'download', onSelect: () => downloads.startAll(item) });
|
||||
}
|
||||
if (['movie', 'show', 'season', 'episode'].includes(item.type)) {
|
||||
items.push({ label: 'Add to playlist…', icon: 'queue', onSelect: () => openDialog({ kind: 'playlist', item }) });
|
||||
}
|
||||
if (owned && ['movie', 'show'].includes(item.type)) items.push({ label: 'Add to collection…', icon: 'collection', onSelect: () => openDialog({ kind: 'collection', item }) });
|
||||
if (['movie', 'episode'].includes(item.type)) items.push({ label: 'Media info', icon: 'info', onSelect: () => openDialog({ kind: 'info', item }) });
|
||||
if (owned && ['movie', 'show', 'season', 'episode', 'collection'].includes(item.type)) {
|
||||
const manage: MenuItem[] = [
|
||||
{ label: 'Edit metadata…', icon: 'edit', onSelect: () => openDialog({ kind: 'edit', item }) },
|
||||
{ label: 'Change poster…', icon: 'image', onSelect: () => openDialog({ kind: 'artwork', item, type: 'poster' }) },
|
||||
{ label: 'Change background…', icon: 'image', onSelect: () => openDialog({ kind: 'artwork', item, type: 'art' }) },
|
||||
{ label: 'Refresh metadata', icon: 'refresh', onSelect: () => admin.refresh(item) },
|
||||
];
|
||||
if (item.type !== 'collection') manage.push({ label: 'Analyze', icon: 'activity', onSelect: () => admin.analyze(item) });
|
||||
if (item.type === 'movie' || item.type === 'show') {
|
||||
manage.push({ label: 'Fix match…', icon: 'wand', onSelect: () => openDialog({ kind: 'match', item }) });
|
||||
manage.push({ label: 'Unmatch', icon: 'unlink', onSelect: () => admin.unmatch(item) });
|
||||
}
|
||||
if (item.type === 'movie' && item.media.length > 1) manage.push({ label: 'Split apart', icon: 'split', onSelect: () => admin.split(item) });
|
||||
if (item.type !== 'collection') {
|
||||
manage.push({ divider: true });
|
||||
manage.push({ label: 'Delete from server…', icon: 'trash', danger: true, onSelect: () => admin.remove(item, ctx.onDeleted) });
|
||||
}
|
||||
items.push({ divider: true });
|
||||
items.push({ label: 'Manage', icon: 'tool', submenu: manage });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
190
src/app/format.ts
Normal file
190
src/app/format.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import type { Item, Media } from '../plex/types';
|
||||
|
||||
export function duration(ms: number): string {
|
||||
if (!ms || ms < 0) return '';
|
||||
const m = Math.round(ms / 60000);
|
||||
if (m < 60) return `${m}m`;
|
||||
const h = Math.floor(m / 60);
|
||||
return m % 60 ? `${h}h ${m % 60}m` : `${h}h`;
|
||||
}
|
||||
|
||||
export function clock(seconds: number, forceHours = false): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) seconds = 0;
|
||||
const s = Math.floor(seconds % 60);
|
||||
const m = Math.floor((seconds / 60) % 60);
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return h || forceHours ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
|
||||
}
|
||||
|
||||
export function remaining(item: Item): string {
|
||||
if (!item.duration || !item.viewOffset) return '';
|
||||
const left = Math.max(0, item.duration - item.viewOffset);
|
||||
const m = Math.round(left / 60000);
|
||||
if (m < 1) return 'Almost done';
|
||||
return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m left` : `${m}m left`;
|
||||
}
|
||||
|
||||
export function episodeLabel(item: Item, long = false): string {
|
||||
if (item.type !== 'episode') return '';
|
||||
if (long) return `Season ${item.parentIndex} · Episode ${item.index}`;
|
||||
return `S${item.parentIndex} · E${item.index}`;
|
||||
}
|
||||
|
||||
export function progress(item: Item): number {
|
||||
if (!item.duration || !item.viewOffset) return 0;
|
||||
return Math.min(1, Math.max(0, item.viewOffset / item.duration));
|
||||
}
|
||||
|
||||
export function isWatched(item: Item, percent = 90): boolean {
|
||||
if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount;
|
||||
if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100;
|
||||
return item.viewCount > 0;
|
||||
}
|
||||
|
||||
export function remainingEpisodes(item: Item): number {
|
||||
return Math.max(0, item.leafCount - item.viewedLeafCount);
|
||||
}
|
||||
|
||||
export function displayTitle(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentTitle || item.title;
|
||||
if (item.type === 'season') return item.parentTitle ? `${item.parentTitle}` : item.title;
|
||||
return item.title;
|
||||
}
|
||||
|
||||
export function subtitleFor(item: Item): string {
|
||||
switch (item.type) {
|
||||
case 'episode':
|
||||
return `${episodeLabel(item)} ${item.title}`;
|
||||
case 'season':
|
||||
return item.title + (item.leafCount ? ` · ${item.leafCount} episodes` : '');
|
||||
case 'show':
|
||||
return [item.year || '', item.childCount ? `${item.childCount} season${item.childCount === 1 ? '' : 's'}` : ''].filter(Boolean).join(' · ');
|
||||
case 'collection':
|
||||
return item.childCount ? `${item.childCount} titles` : 'Collection';
|
||||
case 'clip':
|
||||
return [extraLabel(item), duration(item.duration)].filter(Boolean).join(' · ');
|
||||
default:
|
||||
return [item.year || '', duration(item.duration)].filter(Boolean).join(' · ');
|
||||
}
|
||||
}
|
||||
|
||||
export function extraLabel(item: Item): string {
|
||||
const map: Record<string, string> = {
|
||||
trailer: 'Trailer',
|
||||
behindTheScenes: 'Behind the scenes',
|
||||
deletedScene: 'Deleted scene',
|
||||
featurette: 'Featurette',
|
||||
interview: 'Interview',
|
||||
sceneOrSample: 'Scene',
|
||||
short: 'Short',
|
||||
};
|
||||
return map[item.subtype] ?? (item.type === 'clip' ? 'Extra' : '');
|
||||
}
|
||||
|
||||
/** Image path choices per presentation. */
|
||||
export const art = {
|
||||
poster(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentThumb || item.parentThumb || item.thumb;
|
||||
if (item.type === 'season') return item.thumb || item.parentThumb;
|
||||
return item.thumb;
|
||||
},
|
||||
landscape(item: Item): string {
|
||||
if (item.type === 'episode' || item.type === 'clip') return item.thumb || item.art;
|
||||
return item.art || item.grandparentArt || item.thumb;
|
||||
},
|
||||
backdrop(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentArt || item.art || item.thumb;
|
||||
return item.art || item.grandparentArt || item.thumb;
|
||||
},
|
||||
};
|
||||
|
||||
export function resolutionLabel(m?: Media): string {
|
||||
if (!m) return '';
|
||||
const r = m.videoResolution.toLowerCase();
|
||||
if (r === '4k') return '4K';
|
||||
if (r === 'sd') return 'SD';
|
||||
if (/^\d+$/.test(r)) return `${r}p`;
|
||||
if (m.height >= 2000) return '4K';
|
||||
if (m.height >= 1000) return '1080p';
|
||||
if (m.height >= 700) return '720p';
|
||||
return r.toUpperCase();
|
||||
}
|
||||
|
||||
export function channelLabel(n: number): string {
|
||||
return n === 1 ? 'Mono' : n === 2 ? 'Stereo' : n === 6 ? '5.1' : n === 8 ? '7.1' : n ? `${n} ch` : '';
|
||||
}
|
||||
|
||||
/** Format badges: 4K, HDR flavor, Atmos/5.1 — the facts that matter at a glance. */
|
||||
export function formatBadges(item: Item): string[] {
|
||||
const m = item.media[0];
|
||||
if (!m) return [];
|
||||
const out: string[] = [];
|
||||
const res = resolutionLabel(m);
|
||||
if (res === '4K' || res === '1080p' || res === '720p') out.push(res.toUpperCase());
|
||||
if (m.dynamicRange === 'Dolby Vision') out.push('DOLBY VISION');
|
||||
else if (m.dynamicRange) out.push(m.dynamicRange === 'HDR10' ? 'HDR' : m.dynamicRange);
|
||||
if (m.atmos) out.push('ATMOS');
|
||||
else if (m.audioChannels >= 6) out.push(channelLabel(m.audioChannels));
|
||||
return out;
|
||||
}
|
||||
|
||||
export function technicalLine(m?: Media): string {
|
||||
if (!m) return '';
|
||||
return [
|
||||
m.videoCodec.toUpperCase(),
|
||||
[m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' '),
|
||||
m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
export function fileSize(bytes: number): string {
|
||||
if (!bytes) return '';
|
||||
if (bytes >= 1e12) return `${(bytes / 1e12).toFixed(2)} TB`;
|
||||
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
|
||||
if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
|
||||
return `${Math.round(bytes / 1e3)} KB`;
|
||||
}
|
||||
|
||||
export function bitrate(kbps: number): string {
|
||||
if (!kbps) return '';
|
||||
return kbps >= 1000 ? `${(kbps / 1000).toFixed(kbps >= 10000 ? 0 : 1)} Mbps` : `${kbps} kbps`;
|
||||
}
|
||||
|
||||
export function date(value: string | number): string {
|
||||
if (!value) return '';
|
||||
const d = typeof value === 'number' ? new Date(value * 1000) : new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
export function relativeTime(seconds: number): string {
|
||||
if (!seconds) return '';
|
||||
const diff = Date.now() / 1000 - seconds;
|
||||
if (diff < 60) return 'just now';
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)} min ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)} hr ago`;
|
||||
if (diff < 86400 * 30) return `${Math.floor(diff / 86400)} days ago`;
|
||||
return date(seconds);
|
||||
}
|
||||
|
||||
export function plural(n: number, word: string, pluralWord = `${word}s`) {
|
||||
return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`;
|
||||
}
|
||||
|
||||
/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */
|
||||
export function washGradient(u: Item['ultraBlur'], strength = 1): string {
|
||||
if (!u) return '';
|
||||
const c = (hex: string, a: number) => {
|
||||
const n = parseInt(hex, 16);
|
||||
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${(a * strength).toFixed(3)})`;
|
||||
};
|
||||
return [
|
||||
`radial-gradient(ellipse at 100% 0%, ${c(u.topRight, 0.95)} 0%, transparent 62%)`,
|
||||
`radial-gradient(ellipse at 0% 0%, ${c(u.topLeft, 0.7)} 0%, transparent 55%)`,
|
||||
`radial-gradient(ellipse at 100% 100%, ${c(u.bottomRight, 0.55)} 0%, transparent 60%)`,
|
||||
`radial-gradient(ellipse at 0% 100%, ${c(u.bottomLeft, 0.45)} 0%, transparent 60%)`,
|
||||
].join(', ');
|
||||
}
|
||||
91
src/app/keyboardNav.ts
Normal file
91
src/app/keyboardNav.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
/**
|
||||
* Arrow-key movement between titles, for keyboard users. Focus moves to the
|
||||
* nearest card in the pressed direction (by on-screen geometry), so it works
|
||||
* the same across shelves, grids, episode lists and people rows.
|
||||
*/
|
||||
const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link';
|
||||
|
||||
function center(r: DOMRect) {
|
||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
}
|
||||
|
||||
function nearest(from: HTMLElement, dir: 'left' | 'right' | 'up' | 'down'): HTMLElement | null {
|
||||
const a = from.getBoundingClientRect();
|
||||
const ac = center(a);
|
||||
const scope = from.closest('.main-scroll') ?? document;
|
||||
let best: HTMLElement | null = null;
|
||||
let bestScore = Infinity;
|
||||
for (const el of scope.querySelectorAll<HTMLElement>(TARGETS)) {
|
||||
if (el === from || el.offsetParent === null) continue;
|
||||
const b = el.getBoundingClientRect();
|
||||
const bc = center(b);
|
||||
const dx = bc.x - ac.x;
|
||||
const dy = bc.y - ac.y;
|
||||
let primary: number;
|
||||
let secondary: number;
|
||||
switch (dir) {
|
||||
case 'right':
|
||||
if (b.left < a.right - 4 || Math.abs(dy) > a.height * 0.6) continue;
|
||||
primary = dx;
|
||||
secondary = Math.abs(dy);
|
||||
break;
|
||||
case 'left':
|
||||
if (b.right > a.left + 4 || Math.abs(dy) > a.height * 0.6) continue;
|
||||
primary = -dx;
|
||||
secondary = Math.abs(dy);
|
||||
break;
|
||||
case 'down':
|
||||
if (b.top < a.bottom - 4) continue;
|
||||
primary = dy;
|
||||
secondary = Math.abs(dx);
|
||||
break;
|
||||
case 'up':
|
||||
if (b.bottom > a.top + 4) continue;
|
||||
primary = -dy;
|
||||
secondary = Math.abs(dx);
|
||||
break;
|
||||
}
|
||||
// Prefer the next row/column first, then the closest within it.
|
||||
const score = primary + secondary * (dir === 'up' || dir === 'down' ? 0.35 : 2);
|
||||
if (score < bestScore) {
|
||||
bestScore = score;
|
||||
best = el;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function installKeyboardNav() {
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
const target = e.target as HTMLElement;
|
||||
if (document.documentElement.classList.contains('player-open')) return;
|
||||
if (document.querySelector('.menu-layer, .dialog-layer')) return;
|
||||
|
||||
// "/" focuses the nearest search field.
|
||||
if (e.key === '/' && !target.closest('input, textarea')) {
|
||||
const field = document.querySelector<HTMLInputElement>('.lib-search input, .search-field input');
|
||||
if (field) {
|
||||
e.preventDefault();
|
||||
field.focus();
|
||||
field.select();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!target.matches?.(TARGETS)) return;
|
||||
if ((e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) && !target.matches('.shelf-title-link')) {
|
||||
e.preventDefault();
|
||||
const r = target.getBoundingClientRect();
|
||||
target.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 24, clientY: r.top + 24 }));
|
||||
return;
|
||||
}
|
||||
const dir = ({ ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down' } as const)[e.key as 'ArrowLeft'];
|
||||
if (!dir) return;
|
||||
const next = nearest(target, dir);
|
||||
if (!next) return;
|
||||
e.preventDefault();
|
||||
next.focus({ preventScroll: true });
|
||||
next.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
|
||||
});
|
||||
}
|
||||
53
src/app/queries.ts
Normal file
53
src/app/queries.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item, Section } from '../plex/types';
|
||||
import { useServer } from './session';
|
||||
import { useSettings } from './settings';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 60_000,
|
||||
gcTime: 30 * 60_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/** Every key starts with the server so switching servers never mixes caches. */
|
||||
export function useKey(...parts: unknown[]) {
|
||||
const server = useServer();
|
||||
return [server.machineId, ...parts];
|
||||
}
|
||||
|
||||
export function useServerQuery<T>(parts: unknown[], fn: (s: ReturnType<typeof useServer>) => Promise<T>, opts: Partial<UseQueryOptions<T>> = {}) {
|
||||
const server = useServer();
|
||||
return useQuery<T>({ queryKey: [server.machineId, ...parts], queryFn: () => fn(server), ...opts } as UseQueryOptions<T>);
|
||||
}
|
||||
|
||||
export const useSections = () => useServerQuery(['sections'], (s) => api.sections(s), { staleTime: 5 * 60_000 });
|
||||
|
||||
/** The library a Movies or TV destination shows: the user's choice, else the first. */
|
||||
export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null; all: Section[]; loading: boolean } {
|
||||
const { data, isLoading } = useSections();
|
||||
const chosen = useSettings((s) => (kind === 'movie' ? s.movieSection : s.showSection));
|
||||
const all = (data ?? []).filter((s) => s.type === kind && !s.hidden);
|
||||
return { section: all.find((s) => s.id === chosen) ?? all[0] ?? null, all, loading: isLoading };
|
||||
}
|
||||
|
||||
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
|
||||
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts });
|
||||
|
||||
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 });
|
||||
|
||||
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });
|
||||
|
||||
/** After a watched-state or metadata change, refresh everything that may show it. */
|
||||
export function invalidateLibrary() {
|
||||
queryClient.invalidateQueries({ predicate: (q) => !['sections', 'libraryMeta', 'filterOptions', 'serverPrefs'].includes(String(q.queryKey[1])) });
|
||||
}
|
||||
|
||||
export function invalidateItem(id: string) {
|
||||
queryClient.invalidateQueries({ predicate: (q) => q.queryKey.includes(id) });
|
||||
}
|
||||
101
src/app/router.ts
Normal file
101
src/app/router.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { create } from 'zustand';
|
||||
|
||||
export type SectionKind = 'movie' | 'show';
|
||||
export type SectionTab = 'discover' | 'library' | 'collections';
|
||||
|
||||
export type Route =
|
||||
| { name: 'home' }
|
||||
| { name: 'section'; kind: SectionKind; tab: SectionTab }
|
||||
| { name: 'item'; id: string; title?: string }
|
||||
| { name: 'person'; id: string; title: string; thumb?: string }
|
||||
| { name: 'hub'; key: string; title: string }
|
||||
| { name: 'search'; query?: string }
|
||||
| { name: 'downloads' }
|
||||
| { name: 'settings'; mode: 'app' | 'server'; tab: string };
|
||||
|
||||
export interface Entry {
|
||||
id: number;
|
||||
route: Route;
|
||||
scroll: number;
|
||||
/** Per-screen state to restore on Back (e.g. selected season, library offset). */
|
||||
state: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface RouterState {
|
||||
entries: Entry[];
|
||||
index: number;
|
||||
current: Entry;
|
||||
navigate(route: Route, opts?: { replace?: boolean }): void;
|
||||
back(): void;
|
||||
forward(): void;
|
||||
canBack(): boolean;
|
||||
saveScroll(scroll: number): void;
|
||||
setState(patch: Record<string, unknown>): void;
|
||||
reset(route: Route): void;
|
||||
}
|
||||
|
||||
let nextId = 1;
|
||||
const entry = (route: Route): Entry => ({ id: nextId++, route, scroll: 0, state: {} });
|
||||
const MAX = 60;
|
||||
|
||||
const sameDestination = (a: Route, b: Route) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
export const useRouter = create<RouterState>((set, get) => {
|
||||
const first = entry({ name: 'home' });
|
||||
return {
|
||||
entries: [first],
|
||||
index: 0,
|
||||
current: first,
|
||||
navigate(route, opts) {
|
||||
const { entries, index } = get();
|
||||
if (sameDestination(entries[index].route, route)) return;
|
||||
const e = entry(route);
|
||||
let next = entries.slice(0, index + 1);
|
||||
if (opts?.replace) next[next.length - 1] = e;
|
||||
else next.push(e);
|
||||
if (next.length > MAX) next = next.slice(next.length - MAX);
|
||||
set({ entries: next, index: next.length - 1, current: e });
|
||||
},
|
||||
back() {
|
||||
const { entries, index } = get();
|
||||
if (index > 0) set({ index: index - 1, current: entries[index - 1] });
|
||||
},
|
||||
forward() {
|
||||
const { entries, index } = get();
|
||||
if (index < entries.length - 1) set({ index: index + 1, current: entries[index + 1] });
|
||||
},
|
||||
canBack: () => get().index > 0,
|
||||
saveScroll(scroll) {
|
||||
get().current.scroll = scroll;
|
||||
},
|
||||
setState(patch) {
|
||||
const cur = get().current;
|
||||
cur.state = { ...cur.state, ...patch };
|
||||
},
|
||||
reset(route) {
|
||||
const e = entry(route);
|
||||
set({ entries: [e], index: 0, current: e });
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const navigate = (route: Route, opts?: { replace?: boolean }) => useRouter.getState().navigate(route, opts);
|
||||
export const goBack = () => useRouter.getState().back();
|
||||
|
||||
/** The top-level destination a route belongs to, for the navigation highlight. */
|
||||
export function topLevel(route: Route): string {
|
||||
switch (route.name) {
|
||||
case 'home':
|
||||
return 'home';
|
||||
case 'section':
|
||||
return route.kind === 'movie' ? 'movies' : 'shows';
|
||||
case 'search':
|
||||
return 'search';
|
||||
case 'downloads':
|
||||
return 'downloads';
|
||||
case 'settings':
|
||||
return 'settings';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
213
src/app/session.ts
Normal file
213
src/app/session.ts
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
import { create } from 'zustand';
|
||||
import { appInfo, devSession, isNative, secrets } from '../platform/native';
|
||||
import { configureClient, PlexError, PlexServer } from '../plex/client';
|
||||
import * as account from '../plex/account';
|
||||
import type { PlexUser, ServerResource } from '../plex/types';
|
||||
|
||||
export type Status = 'loading' | 'signed-out' | 'choose-server' | 'connecting' | 'ready' | 'offline';
|
||||
|
||||
interface StoredServer {
|
||||
id: string;
|
||||
name: string;
|
||||
uri: string;
|
||||
owned: boolean;
|
||||
manual?: boolean;
|
||||
}
|
||||
|
||||
interface SessionState {
|
||||
status: Status;
|
||||
error: string;
|
||||
accountToken: string | null;
|
||||
user: PlexUser | null;
|
||||
resources: ServerResource[];
|
||||
server: PlexServer | null;
|
||||
connection: { local: boolean; relay: boolean } | null;
|
||||
init(): Promise<void>;
|
||||
completeSignIn(token: string): Promise<void>;
|
||||
refreshResources(): Promise<ServerResource[]>;
|
||||
chooseServer(resource: ServerResource): Promise<void>;
|
||||
connectManual(uri: string, token: string): Promise<void>;
|
||||
reconnect(): Promise<void>;
|
||||
switchUser(token: string): Promise<void>;
|
||||
showServerPicker(): void;
|
||||
signOut(): Promise<void>;
|
||||
}
|
||||
|
||||
const SERVER_KEY = 'kaleido.server';
|
||||
const loadStoredServer = (): StoredServer | null => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SERVER_KEY) ?? 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const storeServer = (s: StoredServer | null) => (s ? localStorage.setItem(SERVER_KEY, JSON.stringify(s)) : localStorage.removeItem(SERVER_KEY));
|
||||
|
||||
export const useSession = create<SessionState>((set, get) => ({
|
||||
status: 'loading',
|
||||
error: '',
|
||||
accountToken: null,
|
||||
user: null,
|
||||
resources: [],
|
||||
server: null,
|
||||
connection: null,
|
||||
|
||||
async init() {
|
||||
const info = await appInfo();
|
||||
configureClient({ version: info.version, deviceName: info.deviceName });
|
||||
let token = await secrets.get('account-token');
|
||||
const stored = loadStoredServer();
|
||||
|
||||
if (!token) {
|
||||
const dev = await devSession();
|
||||
if (dev) {
|
||||
// The development token is the owner's account token.
|
||||
try {
|
||||
await account.getUser(dev.token);
|
||||
token = dev.token;
|
||||
await secrets.set('account-token', token);
|
||||
} catch {
|
||||
try {
|
||||
await get().connectManual(dev.server, dev.token);
|
||||
return;
|
||||
} catch {
|
||||
/* fall through to sign-in */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stored?.manual) {
|
||||
const serverToken = await secrets.get('server-token');
|
||||
if (serverToken) {
|
||||
try {
|
||||
await get().connectManual(stored.uri, serverToken);
|
||||
return;
|
||||
} catch (e: any) {
|
||||
set({ status: 'offline', error: e.message });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
set({ status: 'signed-out' });
|
||||
return;
|
||||
}
|
||||
set({ accountToken: token });
|
||||
try {
|
||||
const user = await account.getUser(token);
|
||||
set({ user });
|
||||
} catch (e: any) {
|
||||
if (e instanceof PlexError && (e.status === 401 || e.status === 403)) {
|
||||
await secrets.delete('account-token');
|
||||
set({ status: 'signed-out', accountToken: null, error: 'Your Plex session has expired. Sign in again.' });
|
||||
return;
|
||||
}
|
||||
// plex.tv unreachable: try the last server directly.
|
||||
if (stored) {
|
||||
const serverToken = (await secrets.get('server-token')) ?? token;
|
||||
try {
|
||||
await get().connectManual(stored.uri, serverToken);
|
||||
return;
|
||||
} catch {
|
||||
/* offline */
|
||||
}
|
||||
}
|
||||
set({ status: 'offline', error: 'Kaleido cannot reach Plex right now. Downloaded titles are still available.' });
|
||||
return;
|
||||
}
|
||||
const resources = await get().refreshResources().catch(() => [] as ServerResource[]);
|
||||
const preferred = resources.find((r) => r.id === stored?.id);
|
||||
if (preferred) {
|
||||
await get().chooseServer(preferred);
|
||||
return;
|
||||
}
|
||||
if (resources.length === 1) {
|
||||
await get().chooseServer(resources[0]);
|
||||
return;
|
||||
}
|
||||
set({ status: resources.length ? 'choose-server' : 'choose-server', error: resources.length ? '' : 'No Plex Media Servers are available to this account.' });
|
||||
},
|
||||
|
||||
async completeSignIn(token) {
|
||||
await secrets.set('account-token', token);
|
||||
set({ accountToken: token, error: '', status: 'connecting' });
|
||||
const user = await account.getUser(token);
|
||||
set({ user });
|
||||
const resources = await get().refreshResources();
|
||||
if (resources.length === 1) await get().chooseServer(resources[0]);
|
||||
else set({ status: 'choose-server' });
|
||||
},
|
||||
|
||||
async refreshResources() {
|
||||
const token = get().accountToken;
|
||||
if (!token) return [];
|
||||
const resources = await account.getResources(token);
|
||||
resources.sort((a, b) => Number(b.owned) - Number(a.owned) || Number(b.presence) - Number(a.presence) || a.name.localeCompare(b.name));
|
||||
set({ resources });
|
||||
return resources;
|
||||
},
|
||||
|
||||
async chooseServer(resource) {
|
||||
set({ status: 'connecting', error: '' });
|
||||
const stored = loadStoredServer();
|
||||
try {
|
||||
const r = await account.connect(resource, stored?.id === resource.id ? stored.uri : undefined);
|
||||
const server = new PlexServer(r.uri, resource.accessToken, r.machineId, resource.name, resource.owned, r.local);
|
||||
storeServer({ id: resource.id, name: resource.name, uri: r.uri, owned: resource.owned });
|
||||
await secrets.set('server-token', resource.accessToken);
|
||||
set({ server, status: 'ready', connection: { local: r.local, relay: r.relay } });
|
||||
} catch (e: any) {
|
||||
set({ status: 'choose-server', error: e.message ?? String(e) });
|
||||
}
|
||||
},
|
||||
|
||||
async connectManual(uri, token) {
|
||||
set({ status: 'connecting', error: '' });
|
||||
const r = await account.connectManual(uri, token);
|
||||
const owned = await account
|
||||
.getUser(token)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
const server = new PlexServer(r.uri, token, r.machineId, r.name, owned, r.local);
|
||||
storeServer({ id: r.machineId, name: r.name, uri: r.uri, owned, manual: !get().accountToken });
|
||||
await secrets.set('server-token', token);
|
||||
set({ server, status: 'ready', connection: { local: r.local, relay: false } });
|
||||
},
|
||||
|
||||
async reconnect() {
|
||||
const { resources, server } = get();
|
||||
const resource = resources.find((r) => r.id === server?.machineId);
|
||||
if (resource) await get().chooseServer(resource);
|
||||
else await get().init();
|
||||
},
|
||||
|
||||
async switchUser(token) {
|
||||
await secrets.set('account-token', token);
|
||||
storeServer(null);
|
||||
set({ accountToken: token, server: null, status: 'connecting' });
|
||||
await get().init();
|
||||
},
|
||||
|
||||
showServerPicker() {
|
||||
set({ status: 'choose-server', error: '' });
|
||||
get().refreshResources().catch(() => {});
|
||||
},
|
||||
|
||||
async signOut() {
|
||||
const token = get().accountToken;
|
||||
if (token && isNative) await account.signOut(token);
|
||||
await secrets.delete('account-token');
|
||||
await secrets.delete('server-token');
|
||||
storeServer(null);
|
||||
set({ status: 'signed-out', accountToken: null, user: null, server: null, resources: [], connection: null, error: '' });
|
||||
},
|
||||
}));
|
||||
|
||||
/** The connected server. Only call beneath screens rendered when status is ready. */
|
||||
export function useServer(): PlexServer {
|
||||
const s = useSession((st) => st.server);
|
||||
if (!s) throw new Error('No server connection');
|
||||
return s;
|
||||
}
|
||||
102
src/app/settings.ts
Normal file
102
src/app/settings.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
|
||||
export type Quality = 'original' | '2160' | '1080' | '720' | '480';
|
||||
export type SkipMode = 'off' | 'button' | 'auto';
|
||||
export type SubtitleMode = 'auto' | 'always' | 'forced' | 'off';
|
||||
|
||||
export interface Preferences {
|
||||
// Playback
|
||||
quality: Quality;
|
||||
remoteQuality: Quality;
|
||||
hwdec: boolean;
|
||||
hdrPassthrough: boolean;
|
||||
autoplayNext: boolean;
|
||||
countdownSeconds: number;
|
||||
skipIntro: SkipMode;
|
||||
skipCredits: SkipMode;
|
||||
watchedPercent: number;
|
||||
audioLanguage: string;
|
||||
subtitleMode: SubtitleMode;
|
||||
subtitleLanguage: string;
|
||||
subtitleScale: number;
|
||||
subtitleBackground: boolean;
|
||||
volume: number;
|
||||
seekStep: number;
|
||||
// Interface
|
||||
startPage: 'home' | 'movies' | 'shows';
|
||||
colorWash: boolean;
|
||||
reducedMotion: boolean;
|
||||
posterSize: 'compact' | 'comfortable' | 'large';
|
||||
heroRotation: boolean;
|
||||
themeMusic: boolean;
|
||||
themeVolume: number;
|
||||
// Libraries shown for Movies and TV Shows
|
||||
movieSection: string;
|
||||
showSection: string;
|
||||
// Downloads
|
||||
downloadDir: string;
|
||||
// Remembered library views per section
|
||||
libraryViews: Record<string, { sort: string; filters: Record<string, string> }>;
|
||||
}
|
||||
|
||||
export const defaults: Preferences = {
|
||||
quality: 'original',
|
||||
remoteQuality: '1080',
|
||||
hwdec: true,
|
||||
hdrPassthrough: true,
|
||||
autoplayNext: true,
|
||||
countdownSeconds: 8,
|
||||
skipIntro: 'button',
|
||||
skipCredits: 'button',
|
||||
watchedPercent: 90,
|
||||
audioLanguage: '',
|
||||
subtitleMode: 'auto',
|
||||
subtitleLanguage: '',
|
||||
subtitleScale: 1,
|
||||
subtitleBackground: false,
|
||||
volume: 100,
|
||||
seekStep: 10,
|
||||
startPage: 'home',
|
||||
colorWash: true,
|
||||
reducedMotion: false,
|
||||
posterSize: 'comfortable',
|
||||
heroRotation: true,
|
||||
themeMusic: false,
|
||||
themeVolume: 30,
|
||||
movieSection: '',
|
||||
showSection: '',
|
||||
downloadDir: '',
|
||||
libraryViews: {},
|
||||
};
|
||||
|
||||
interface SettingsState extends Preferences {
|
||||
set<K extends keyof Preferences>(key: K, value: Preferences[K]): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export const useSettings = create<SettingsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
...defaults,
|
||||
set: (key, value) => set({ [key]: value } as Partial<SettingsState>),
|
||||
reset: () => set({ ...defaults }),
|
||||
}),
|
||||
{ name: 'kaleido.settings', version: 1 },
|
||||
),
|
||||
);
|
||||
|
||||
export const QUALITY_LABEL: Record<Quality, string> = {
|
||||
original: 'Original quality',
|
||||
'2160': '4K (40 Mbps)',
|
||||
'1080': '1080p (20 Mbps)',
|
||||
'720': '720p (4 Mbps)',
|
||||
'480': '480p (1.5 Mbps)',
|
||||
};
|
||||
|
||||
export const QUALITY_PROFILE: Record<Exclude<Quality, 'original'>, { kbps: number; width: number; height: number }> = {
|
||||
'2160': { kbps: 40000, width: 3840, height: 2160 },
|
||||
'1080': { kbps: 20000, width: 1920, height: 1080 },
|
||||
'720': { kbps: 4000, width: 1280, height: 720 },
|
||||
'480': { kbps: 1500, width: 854, height: 480 },
|
||||
};
|
||||
64
src/app/updater.ts
Normal file
64
src/app/updater.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
/**
|
||||
* Application updates through Tauri's signed updater. The feed
|
||||
* (`updates/latest.json`) lists a build per platform, so the same flow serves
|
||||
* Windows, macOS and Linux.
|
||||
*/
|
||||
import { create } from 'zustand';
|
||||
import { isNative } from '../platform/native';
|
||||
import { toast } from '../ui/overlays';
|
||||
|
||||
interface UpdaterState {
|
||||
checking: boolean;
|
||||
installing: boolean;
|
||||
progress: number;
|
||||
checkedAt: number;
|
||||
error: string;
|
||||
available: { version: string; notes: string } | null;
|
||||
}
|
||||
|
||||
export const useUpdater = create<UpdaterState>(() => ({
|
||||
checking: false,
|
||||
installing: false,
|
||||
progress: 0,
|
||||
checkedAt: 0,
|
||||
error: '',
|
||||
available: null,
|
||||
}));
|
||||
|
||||
let pending: import('@tauri-apps/plugin-updater').Update | null = null;
|
||||
|
||||
export async function checkForUpdate(manual = false) {
|
||||
if (!isNative || useUpdater.getState().checking) return;
|
||||
useUpdater.setState({ checking: true, error: '' });
|
||||
try {
|
||||
const { check } = await import('@tauri-apps/plugin-updater');
|
||||
const update = await check({ timeout: 15000 });
|
||||
pending = update;
|
||||
useUpdater.setState({ available: update ? { version: update.version, notes: update.body ?? '' } : null, checkedAt: Date.now() });
|
||||
if (update && !manual) toast(`Kaleido ${update.version} is available`, 'info', { label: 'Install', onClick: installUpdate });
|
||||
} catch (e: any) {
|
||||
if (manual) useUpdater.setState({ error: `Couldn’t check for updates: ${e?.message ?? e}` });
|
||||
} finally {
|
||||
useUpdater.setState({ checking: false });
|
||||
}
|
||||
}
|
||||
|
||||
export async function installUpdate() {
|
||||
if (!pending) return;
|
||||
useUpdater.setState({ installing: true, progress: 0 });
|
||||
try {
|
||||
let total = 0;
|
||||
let received = 0;
|
||||
await pending.downloadAndInstall((event) => {
|
||||
if (event.event === 'Started') total = event.data.contentLength ?? 0;
|
||||
else if (event.event === 'Progress') {
|
||||
received += event.data.chunkLength;
|
||||
if (total) useUpdater.setState({ progress: received / total });
|
||||
}
|
||||
});
|
||||
const { relaunch } = await import('@tauri-apps/plugin-process');
|
||||
await relaunch();
|
||||
} catch (e: any) {
|
||||
useUpdater.setState({ installing: false, error: `The update couldn’t be installed: ${e?.message ?? e}` });
|
||||
}
|
||||
}
|
||||
41
src/app/useHomeUsers.ts
Normal file
41
src/app/useHomeUsers.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getHomeUsers, switchHomeUser } from '../plex/account';
|
||||
import type { HomeUser } from '../plex/types';
|
||||
import { promptDialog, toastError } from '../ui/overlays';
|
||||
import { useSession } from './session';
|
||||
import { queryClient } from './queries';
|
||||
|
||||
/** Plex Home profiles available to the signed-in account. */
|
||||
export function useHomeUsers() {
|
||||
const token = useSession((s) => s.accountToken);
|
||||
const home = useSession((s) => s.user?.home);
|
||||
const { data } = useQuery({
|
||||
queryKey: ['homeUsers', token],
|
||||
queryFn: () => getHomeUsers(token!),
|
||||
enabled: !!token && !!home,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
return {
|
||||
users: data ?? [],
|
||||
async switchTo(u: HomeUser) {
|
||||
try {
|
||||
let pin: string | undefined;
|
||||
if (u.protected) {
|
||||
const v = await promptDialog({
|
||||
title: `Switch to ${u.title}`,
|
||||
message: 'This profile is protected by a PIN.',
|
||||
confirm: 'Switch',
|
||||
input: { label: 'PIN', type: 'password', placeholder: '4-digit PIN' },
|
||||
});
|
||||
if (v === null) return;
|
||||
pin = v;
|
||||
}
|
||||
const next = await switchHomeUser(token!, u.uuid, pin);
|
||||
queryClient.clear();
|
||||
await useSession.getState().switchUser(next);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue