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, 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; }