import { type CSSProperties, type FormEvent, type MouseEvent, type ReactNode, startTransition, useCallback, useEffect, useLayoutEffect, useRef, useState, } from 'react' import { api } from './api' import { type CalendarEntry, defaultConfig, type AppConfig, type AppRoute, type ConnectionStatus, type CompletedDownloadItem, type DownloadItem, type DiskSpaceStatus, type HubPageResponse, type MediaCard, type ProcessingItem, type SearchResponse, type SelectOption, type ServiceOptionsResponse, type TitleDetailsCastMember, type TitleDetailsEpisode, type TitleDetailsResponse, } from '../shared/contracts' type AuthState = 'loading' | 'setup' | 'login' | 'profiles' | 'admin' | 'app' type EntryStage = 'onboarding' | 'profiles' | 'dashboard' type EntryTransitionState = 'idle' | 'forward-enter' | 'forward-exit' | 'back-enter' | 'back-exit' const MAX_CACHED_HUB_PAGES = 3 type ModalOriginRect = { left: number; top: number; width: number; height: number } type SelectedCardState = { card: MediaCard; originRect: ModalOriginRect | null } const CAROUSEL_SCROLL_DISTANCE_RATIO = 0.84 const EPISODE_SCROLL_DISTANCE_RATIO = 0.72 const SEASON_DOMINANCE_SWITCH_RATIO = 0.12 const SEASON_DOMINANCE_SWITCH_MIN_PX = 56 type SidebarItem = { route: AppRoute; label: string; short: string; icon?: 'calendar' | 'search' | 'downloads' | 'home' | 'library'; iconClassName?: string } const topSidebarItems: SidebarItem[] = [ { route: 'search', label: 'Search', short: 'S', icon: 'search', iconClassName: 'sidebar-search-icon' }, { route: 'calendar', label: 'Upcoming', short: 'C', icon: 'calendar' }, { route: 'downloads', label: 'Downloads', short: 'D', icon: 'downloads' }, ] const sidebarItems: SidebarItem[] = [ { route: 'home', label: 'Inicio', short: 'H', icon: 'home' }, { route: 'dorama', label: 'K-Drama', short: '아' }, { route: 'anime', label: 'Anime', short: 'あ' }, { route: 'library', label: 'Library', short: 'L', icon: 'library' }, ] const networkSidebarItems: Array<{ route: AppRoute; label: string; icon: string; iconClassName?: string }> = [ { route: 'netflix', label: 'Netflix', icon: '/networks/netflix.png' }, { route: 'primevideo', label: 'Prime Video', icon: '/networks/prime.svg' }, { route: 'hbo', label: 'HBO', icon: '/networks/hbo.svg', iconClassName: 'sidebar-network-icon-image white-network-icon' }, { route: 'viki', label: 'Viki', icon: '/networks/viki.png' }, { route: 'disney', label: 'Disney+', icon: '/networks/disney.webp' }, ] function App() { const [authState, setAuthState] = useState('loading') const [sessionRole, setSessionRole] = useState<'admin' | 'user' | null>(null) const [entryStage, setEntryStage] = useState('profiles') const [route, setRoute] = useState('home') const [busy, setBusy] = useState(false) const [jellyfinUsersBusy, setJellyfinUsersBusy] = useState(false) const [error, setError] = useState('') const [notice, setNotice] = useState('') const [password, setPassword] = useState('') const [config, setConfig] = useState(defaultConfig) const [options, setOptions] = useState({ jellyfinUsers: [], sonarrRootFolders: [], sonarrQualityProfiles: [], sonarrLanguageProfiles: [], radarrRootFolders: [], radarrQualityProfiles: [], }) const [downloads, setDownloads] = useState([]) const [processingItems, setProcessingItems] = useState([]) const [completedDownloads, setCompletedDownloads] = useState([]) const [connections, setConnections] = useState([]) const [diskSpace, setDiskSpace] = useState(null) const [hubPages, setHubPages] = useState>>({}) const [hubLoading, setHubLoading] = useState(false) const [searchQuery, setSearchQuery] = useState('') const [searchResults, setSearchResults] = useState([]) const [searchLoading, setSearchLoading] = useState(false) const [lastSearchQuery, setLastSearchQuery] = useState('') const [selectedCard, setSelectedCard] = useState(null) const [downloadDeleteId, setDownloadDeleteId] = useState('') const [entryTransitionState, setEntryTransitionState] = useState('idle') async function transitionEntryStage(nextStage: EntryStage) { if (nextStage === entryStage) { return } const isProfileDashboardSwitch = (entryStage === 'profiles' && nextStage === 'dashboard') || (entryStage === 'dashboard' && nextStage === 'profiles') if (!isProfileDashboardSwitch) { setEntryStage(nextStage) return } setEntryTransitionState(entryStage === 'profiles' ? 'forward-exit' : 'back-exit') await wait(240) setEntryStage(nextStage) setEntryTransitionState(nextStage === 'dashboard' ? 'forward-enter' : 'back-enter') await wait(520) setEntryTransitionState('idle') } async function refreshBaseData() { const [settings, serviceOptions, dashboard, storage] = await Promise.all([ api.getSettings(), api.getOptions(), api.getDashboard(), api.getDiskSpace(), ]) setConfig(settings) setOptions(serviceOptions) setDownloads(dashboard.downloads) setProcessingItems(dashboard.processing || []) setCompletedDownloads(dashboard.completedDownloads || []) setConnections(dashboard.connections) setDiskSpace(storage) setEntryStage(resolveEntryStage(settings, serviceOptions)) } async function refreshDownloads() { const response = await api.getDownloads() setDownloads(response.downloading) setProcessingItems(response.processing) setCompletedDownloads(response.completed) } async function loadHub(page: HubPageResponse['page'], options?: { silent?: boolean }) { if (!options?.silent) { setHubLoading(true) } try { const hub = await api.getHub(page) setHubPages((current) => cacheHubPage(current, page, hub)) } catch (loadError) { setError(loadError instanceof Error ? loadError.message : 'Failed to load this section.') } finally { if (!options?.silent) { setHubLoading(false) } } } useEffect(() => { let cancelled = false async function boot() { try { const session = await api.getSession() if (cancelled) return if (session.needsSetup) { setAuthState('setup') return } if (!session.authenticated) { const profiles = await api.getProfiles() if (cancelled) return setOptions((current) => ({ ...current, jellyfinUsers: profiles.jellyfinUsers })) setConnections(profiles.connections) setAuthState('profiles') return } setSessionRole(session.role ?? null) await refreshBaseData() if (!cancelled) setAuthState(session.role === 'admin' ? 'admin' : 'app') } catch (bootError) { if (!cancelled) { setError(bootError instanceof Error ? bootError.message : 'Failed to start OmniArr.') setAuthState('profiles') } } } void boot() return () => { cancelled = true } }, []) useEffect(() => { if (authState !== 'app' || entryStage !== 'dashboard') { return } if (route === 'settings' || route === 'calendar' || route === 'search') { return } if (route === 'downloads') { void refreshDownloads() const interval = window.setInterval(() => { void refreshDownloads() }, 2500) return () => window.clearInterval(interval) } const page = route as HubPageResponse['page'] let cancelled = false setHubLoading(true) void api.getHub(page) .then((hub) => { if (cancelled) return setHubPages((current) => cacheHubPage(current, page, hub)) }) .catch((loadError) => { if (cancelled) return setError(loadError instanceof Error ? loadError.message : 'Failed to load this section.') }) .finally(() => { if (cancelled) return setHubLoading(false) }) return () => { cancelled = true } }, [authState, entryStage, route]) useEffect(() => { if (authState !== 'app' || entryStage !== 'dashboard') { return } const interval = window.setInterval(() => { void refreshBaseData() if (route !== 'downloads' && route !== 'settings' && route !== 'search' && route !== 'calendar') { void loadHub(route as HubPageResponse['page'], { silent: true }) } }, 30000) return () => window.clearInterval(interval) }, [authState, entryStage, route]) async function handleAuthSubmit() { setBusy(true) setError('') try { if (authState === 'setup') { await api.register({ password }) } else { await api.login({ password }) } await refreshBaseData() setPassword('') setSessionRole('admin') if (authState === 'setup') { setNotice('Instance initialized.') } else { setRoute('settings') } setAuthState(authState === 'setup' ? 'app' : 'admin') } catch (authError) { setError(authError instanceof Error ? authError.message : 'Authentication failed.') } finally { setBusy(false) } } async function handleLoadJellyfinUsers() { setJellyfinUsersBusy(true) setError('') setNotice('') try { const response = await api.loadJellyfinUsers({ baseUrl: config.jellyfin.baseUrl, apiKey: config.jellyfin.apiKey, }) setOptions((current) => ({ ...current, jellyfinUsers: response.jellyfinUsers })) await transitionEntryStage(response.jellyfinUsers.length ? 'profiles' : 'onboarding') setNotice(response.jellyfinUsers.length ? 'Jellyfin users loaded.' : 'No Jellyfin users found.') } catch (loadError) { setError(loadError instanceof Error ? loadError.message : 'Failed to load Jellyfin users.') } finally { setJellyfinUsersBusy(false) } } async function handleSelectJellyfinUser(userId: string, jellyfinPassword: string) { setBusy(true) setError('') setNotice('') try { await api.loginProfile({ userId, password: jellyfinPassword }) setSessionRole('user') await refreshBaseData() await transitionEntryStage('dashboard') setRoute('home') setAuthState('app') } catch (selectError) { setError(selectError instanceof Error ? selectError.message : 'Failed to select Jellyfin profile.') } finally { setBusy(false) } } async function handleSaveSettings(event: FormEvent) { event.preventDefault() setBusy(true) setError('') setNotice('') try { const response = await api.saveSettings(config) setConfig(response.config) await refreshBaseData() setNotice('Settings saved and services refreshed.') } catch (saveError) { setError(saveError instanceof Error ? saveError.message : 'Failed to save settings.') } finally { setBusy(false) } } async function handleRequest(card: MediaCard, qualityProfileId?: number, seasonNumber?: number) { if (!card.tmdbId) return setBusy(true) setError('') setNotice('') try { if (card.mediaType === 'movie') { await api.requestMovie(card.tmdbId, currentJellyfinUser, qualityProfileId) } else { await api.requestSeries(card.tmdbId, currentJellyfinUser, qualityProfileId, seasonNumber) } if (route !== 'downloads' && route !== 'settings' && route !== 'search' && route !== 'calendar') { await loadHub(route as HubPageResponse['page'], { silent: true }) } setNotice(`${card.title} sent to ${card.mediaType === 'movie' ? 'Radarr' : 'Sonarr'}.`) } catch (requestError) { setError(requestError instanceof Error ? requestError.message : 'Failed to send request.') } finally { setBusy(false) } } async function handleDeleteDownload(id: string) { setDownloadDeleteId(id) setError('') setNotice('') try { await api.deleteDownload({ id }) await refreshDownloads() } catch (deleteError) { setError(deleteError instanceof Error ? deleteError.message : 'Failed to remove the download.') } finally { setDownloadDeleteId('') } } async function handleDismissCompleted(id: string) { try { await api.dismissCompleted({ id }) setCompletedDownloads((current) => current.filter((item) => item.id !== id)) } catch { // silent } } async function handleDismissAllCompleted() { try { await api.dismissAllCompleted() setCompletedDownloads([]) } catch { // silent } } async function handleSearchSubmit(query: string) { const trimmedQuery = query.trim() setSearchQuery(query) setError('') if (!trimmedQuery) { setLastSearchQuery('') setSearchResults([]) return } setSearchLoading(true) try { const response = await api.searchTitles(trimmedQuery) setSearchResults(response.items) setLastSearchQuery(response.query) } catch (searchError) { setError(searchError instanceof Error ? searchError.message : 'Failed to search the catalog.') } finally { setSearchLoading(false) } } function updateConfig(key: K, value: AppConfig[K]) { setConfig((current) => ({ ...current, [key]: value, })) } if (authState === 'loading') { return } if (authState === 'setup') { return ( ) } if (authState === 'login') { return ( { setPassword(''); setAuthState('profiles') }} onSubmit={handleAuthSubmit} password={password} setPassword={setPassword} /> ) } if (authState === 'profiles') { return ( !connection.ok)} error={error} notice={notice} onAdmin={() => setAuthState(sessionRole === 'admin' ? 'admin' : 'login')} onSelectUser={handleSelectJellyfinUser} users={options.jellyfinUsers} /> ) } if (authState === 'admin') { return ( setAuthState('profiles')} onLoadJellyfinUsers={handleLoadJellyfinUsers} onSave={handleSaveSettings} options={options} updateConfig={updateConfig} /> ) } if (entryStage === 'onboarding') { return ( updateConfig('jellyfin', { ...config.jellyfin, apiKey }) } onBaseUrlChange={(baseUrl) => updateConfig('jellyfin', { ...config.jellyfin, baseUrl }) } onLoadUsers={handleLoadJellyfinUsers} users={options.jellyfinUsers} /> ) } if (entryStage === 'profiles') { return (
!connection.ok)} error={error} notice={notice} onAdmin={() => setAuthState(sessionRole === 'admin' ? 'admin' : 'login')} onContinue={() => void transitionEntryStage('dashboard')} onSelectUser={handleSelectJellyfinUser} users={options.jellyfinUsers} />
) } const currentJellyfinUser = sessionRole === 'admin' ? 'Administration' : options.jellyfinUsers.find((option) => option.id === config.jellyfin.userId)?.label || 'Media cockpit' const currentHub = route !== 'downloads' && route !== 'settings' && route !== 'calendar' && route !== 'search' ? hubPages[route as HubPageResponse['page']] : undefined return (
void transitionEntryStage('profiles')} canManage={sessionRole === 'admin'} route={route} setRoute={setRoute} />
{notice ?

{notice}

: null} {error ?

{error}

: null}
{route === 'calendar' ? setSelectedCard({ card, originRect: originRect ?? null })} /> : null} {route === 'downloads' ? : null} {route === 'search' ? ( setSelectedCard({ card, originRect: originRect ?? null })} onSearch={handleSearchSubmit} query={searchQuery} results={searchResults} submittedQuery={lastSearchQuery} updateQuery={setSearchQuery} /> ) : null} {route === 'settings' ? ( ) : null} {route !== 'downloads' && route !== 'settings' && route !== 'calendar' && route !== 'search' ? ( setSelectedCard({ card, originRect: originRect ?? null })} onRequest={handleRequest} route={route} tmdbToken={config.tmdb.bearerToken} /> ) : null}
{selectedCard ? ( config.preferences.sonarrDownloadQualityProfileIds.includes(profile.id)), radarr: options.radarrQualityProfiles.filter((profile) => config.preferences.radarrDownloadQualityProfileIds.includes(profile.id)), }} onClose={() => setSelectedCard(null)} originRect={selectedCard.originRect} onRequest={handleRequest} currentUser={currentJellyfinUser} /> ) : null}
) } function getEntryTransitionClassName(state: EntryTransitionState) { return state === 'idle' ? 'entry-stage-shell' : `entry-stage-shell is-${state}` } function wait(ms: number) { return new Promise((resolve) => window.setTimeout(resolve, ms)) } function Sidebar(props: { route: AppRoute setRoute: (route: AppRoute) => void currentUser: string diskSpace: DiskSpaceStatus | null connections: ConnectionStatus[] busy: boolean canManage: boolean onExitProfile: () => void }) { const [menuOpen, setMenuOpen] = useState(false) const hasServiceFailure = props.connections.some((connection) => !connection.ok) useEffect(() => { function closeOnEscape(event: KeyboardEvent) { if (event.key === 'Escape') { setMenuOpen(false) } } window.addEventListener('keydown', closeOnEscape) return () => window.removeEventListener('keydown', closeOnEscape) }, []) function navigate(route: AppRoute) { setMenuOpen(false) startTransition(() => props.setRoute(route)) } return ( <> ) } function DiskSpaceIndicator({ diskSpace }: { diskSpace: DiskSpaceStatus }) { const usedPercentage = diskSpace.totalBytes > 0 ? Math.max(0, Math.min(100, ((diskSpace.totalBytes - diskSpace.availableBytes) / diskSpace.totalBytes) * 100)) : 0 return (
Disk space {formatBytes(diskSpace.availableBytes)} free
) } function formatBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes <= 0) { return '0 B' } const units = ['B', 'KB', 'MB', 'GB', 'TB'] const unitIndex = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1) const value = bytes / (1024 ** unitIndex) const formattedValue = unitIndex === 0 || Number.isInteger(value) ? value.toFixed(0) : value.toFixed(1) return `${formattedValue} ${units[unitIndex]}` } function LoadingScreen() { return (

Preparing OmniArr…

) } function SearchGlyph() { return ( ) } function HomeGlyph() { return ( ) } function LibraryGlyph() { return ( ) } function SettingsGlyph() { return ( ) } function DiskGlyph() { return ( ) } function ArrowRightGlyph() { return ( ) } function ActionButton(props: { children: ReactNode className?: string disabled?: boolean onClick?: () => void type?: 'button' | 'submit' variant?: 'default' | 'play' }) { const className = [ 'secondary-button', 'title-action-button', props.variant === 'play' ? 'title-action-button-play' : '', props.className || '', ].filter(Boolean).join(' ') return ( ) } function AuthScreen({ password, setPassword, onSubmit, busy, error, }: { password: string setPassword: (value: string) => void onSubmit: () => Promise busy: boolean error: string }) { const isPasswordValid = password.trim().length >= 8 function handleSubmit() { if (busy || !isPasswordValid) { return } void onSubmit() } return (

Create your master password

This password protects the administration area and service settings.

{ event.preventDefault() handleSubmit() }} > {!isPasswordValid && password.length > 0 ?

Password must be at least 8 non-space characters.

: null} {error ?

{error}

: null} {busy ?

Contacting backend…

: null}

Migration

  • Server-side session auth
  • Encrypted persisted settings
  • Jellyfin, Sonarr and Radarr
  • Rebuilt React UI with Reiverr layout
) } function JellyfinOnboardingScreen(props: { baseUrl: string apiKey: string users: SelectOption[] busy: boolean error: string notice: string onBaseUrlChange: (value: string) => void onApiKeyChange: (value: string) => void onLoadUsers: () => Promise }) { return (

Jellyfin setup

Connect your server

Enter your Jellyfin URL and API key to load the available profiles before entering the dashboard.

{props.error ?

{props.error}

: null} {props.notice ?

{props.notice}

: null}

Profiles

{props.users.map((user) => (
{user.label}
))}
) } function ProfileSelectionScreen(props: { users: SelectOption[] currentUserId: string hasServiceFailure: boolean busy: boolean error: string notice: string onSelectUser: (userId: string, password: string) => Promise onAdmin: () => void onContinue?: () => void }) { const [selectedUserId, setSelectedUserId] = useState('') const [password, setPassword] = useState('') const [isReturning, setIsReturning] = useState(false) const [hasReturned, setHasReturned] = useState(false) const [isSelecting, setIsSelecting] = useState(false) const [isEntering, setIsEntering] = useState(false) function submit() { if (selectedUserId && password) { void props.onSelectUser(selectedUserId, password) } } function goBack() { setIsReturning(true) window.setTimeout(() => { setSelectedUserId('') setPassword('') setIsReturning(false) setHasReturned(true) window.setTimeout(() => setHasReturned(false), 520) }, 240) } function selectProfile(userId: string) { setIsSelecting(true) window.setTimeout(() => { setSelectedUserId(userId) setIsSelecting(false) setIsEntering(true) window.setTimeout(() => setIsEntering(false), 520) }, 240) } const selectedUser = props.users.find((user) => user.id === selectedUserId) return (

{selectedUser ? `Sign in as ${selectedUser.label}` : 'Who\'s watching?'}

{props.error ?

{props.error}

: null} {props.notice ?

{props.notice}

: null}
{selectedUser ? } onBack={goBack} onSubmit={submit} password={password} placeholder="Enter the password" setPassword={setPassword} /> :
{props.users.map((user) => ( ))}
} {!selectedUser ?
: null}
) } function ProfileAvatar({ user }: { user: SelectOption }) { return
{user.imageUrl ? : user.label.slice(0, 1).toUpperCase()}
} function AdministrationLoginScreen(props: { busy: boolean error: string password: string setPassword: (value: string) => void onBack: () => void onSubmit: () => Promise }) { const [isReturning, setIsReturning] = useState(false) function goBack() { setIsReturning(true) window.setTimeout(props.onBack, 240) } return (

Administration

{props.error ?

{props.error}

: null}
} onBack={goBack} onSubmit={() => { void props.onSubmit() }} password={props.password} placeholder="Enter the master password" setPassword={props.setPassword} />
) } function ProfileLoginForm(props: { busy: boolean icon: ReactNode password: string placeholder: string setPassword: (value: string) => void onBack: () => void onSubmit: () => void }) { return (
{ event.preventDefault(); props.onSubmit() }}> {props.icon}
) } function SignInGlyph() { return ( ) } function HubPageView(props: { route: AppRoute hub?: HubPageResponse loading: boolean onRequest: (card: MediaCard) => Promise onOpenCard: (card: MediaCard, originRect?: ModalOriginRect | null) => void busy: boolean tmdbToken: string }) { if (props.loading) { return } if (!props.hub) { return ( ) } const hasHero = props.hub.hero.length > 0 const hasSections = props.hub.sections.some((section) => section.items.length > 0) const hasContinueWatching = Boolean(props.hub.continueWatching?.length) if (!hasHero && !hasSections && !hasContinueWatching) { return ( ) } return (
{props.hub.continueWatching?.length ? ( ) : null} {props.hub.sections.map((section) => ( section.id === 'library-movies' || section.id === 'library-series' ? : ))}
) } function LibraryGrid(props: { section: HubPageResponse['sections'][number] onRequest: (card: MediaCard) => Promise onOpenCard: (card: MediaCard, originRect?: ModalOriginRect | null) => void busy: boolean }) { if (!props.section.items.length) return null return (
{props.section.title}
{props.section.items.map((card) => ( ))}
) } function HeroShowcase({ hero, onOpenCard, tmdbToken }: { hero: MediaCard[]; onOpenCard: (card: MediaCard, originRect?: ModalOriginRect | null) => void; tmdbToken: string }) { const [activeIndex, setActiveIndex] = useState(0) const [activeLogoUrl, setActiveLogoUrl] = useState('') const logoCacheRef = useRef(new Map()) useEffect(() => { setActiveIndex((current) => (hero.length ? Math.min(current, hero.length - 1) : 0)) }, [hero]) useEffect(() => { if (hero.length <= 1) { return } const interval = window.setInterval(() => { setActiveIndex((current) => (current + 1) % hero.length) }, 9000) return () => window.clearInterval(interval) }, [hero]) const featured = hero[activeIndex] useEffect(() => { if (!featured?.tmdbId) { setActiveLogoUrl(featured?.logoUrl || '') return } if (featured.logoUrl) { setActiveLogoUrl(featured.logoUrl) return } const mediaType = featured.mediaType === 'movie' ? 'movie' : featured.mediaType === 'tv' || featured.mediaType === 'series' || featured.mediaType === 'episode' ? 'tv' : '' if (!mediaType) { setActiveLogoUrl('') return } let cancelled = false const cacheKey = `${mediaType}:${featured.tmdbId}` const cachedLogoUrl = logoCacheRef.current.get(cacheKey) if (cachedLogoUrl !== undefined) { setActiveLogoUrl(cachedLogoUrl) return } const fetchImages = tmdbToken ? fetch(`https://api.themoviedb.org/3/${mediaType}/${featured.tmdbId}/images`, { headers: { Authorization: `Bearer ${tmdbToken}`, }, }) : fetch(`/api/tmdb/logo?tmdbId=${featured.tmdbId}&mediaType=${mediaType}`) void fetchImages .then(async (response) => { if (!response.ok) { throw new Error('Failed to load logo') } return response.json() as Promise<{ logos?: Array<{ file_path: string; iso_639_1: string | null }> backdrops?: Array<{ file_path: string; iso_639_1: string | null }> }> }) .then((payload) => { if (!cancelled) { const englishLogos = payload.logos?.filter((logo) => logo.iso_639_1 === 'en') || [] const logo = englishLogos[0] || payload.logos?.[0] const nextLogoUrl = logo?.file_path ? `https://image.tmdb.org/t/p/original${logo.file_path}` : '' logoCacheRef.current.set(cacheKey, nextLogoUrl) setActiveLogoUrl(nextLogoUrl) } }) .catch(() => { if (!cancelled) { logoCacheRef.current.set(cacheKey, '') setActiveLogoUrl('') } }) return () => { cancelled = true } }, [featured, tmdbToken]) if (!featured) { return (
Library

No featured media yet

Once Jellyfin and TMDb return content, featured titles will appear here.

) } return (
onOpenCard(featured)} >
) } function resolveHeroSlideStyle(card: MediaCard | undefined) { if (!card) { return undefined } const slideImage = card.backdropUrl || card.posterUrl return slideImage ? { backgroundImage: `url("${slideImage}")` } : undefined } function getSeasonEpisodes( episodes: TitleDetailsEpisode[], seasonId: string ): TitleDetailsEpisode[] { return episodes.filter((episode) => episode.seasonId === seasonId) } function findSeasonAnchorElement(list: HTMLDivElement, seasonId: string) { return list.querySelector(`[data-season-id="${CSS.escape(seasonId)}"]`) } function findEpisodeElement(list: HTMLDivElement, episodeId: string) { return list.querySelector(`[data-episode-id="${CSS.escape(episodeId)}"]`) } function centerEpisodeInList(list: HTMLDivElement, episodeId: string, behavior: ScrollBehavior) { const targetEpisode = findEpisodeElement(list, episodeId) if (!targetEpisode) { return false } const centeredLeft = Math.max(0, targetEpisode.offsetLeft - (list.clientWidth - targetEpisode.offsetWidth) / 2) list.scrollTo({ left: centeredLeft, behavior }) return true } function cacheHubPage( current: Partial>, page: HubPageResponse['page'], hub: HubPageResponse ): Partial> { const next = { ...current, [page]: hub } const pages = Object.keys(next) as HubPageResponse['page'][] if (pages.length <= MAX_CACHED_HUB_PAGES) { return next } const trimmed: Partial> = {} pages.slice(-MAX_CACHED_HUB_PAGES).forEach((cachedPage) => { trimmed[cachedPage] = next[cachedPage] }) return trimmed } function SectionCarousel(props: { section: HubPageResponse['sections'][number] onRequest: (card: MediaCard) => Promise onOpenCard: (card: MediaCard, originRect?: ModalOriginRect | null) => void busy: boolean }) { const trackRef = useRef(null) const [scrollState, setScrollState] = useState({ canScrollLeft: false, canScrollRight: false }) useEffect(() => { const track = trackRef.current if (!track) { setScrollState({ canScrollLeft: false, canScrollRight: false }) return } const syncScrollState = () => { const maxScrollLeft = track.scrollWidth - track.clientWidth setScrollState({ canScrollLeft: track.scrollLeft > 8, canScrollRight: maxScrollLeft - track.scrollLeft > 8, }) } syncScrollState() track.addEventListener('scroll', syncScrollState, { passive: true }) window.addEventListener('resize', syncScrollState) return () => { track.removeEventListener('scroll', syncScrollState) window.removeEventListener('resize', syncScrollState) } }, [props.section.items.length]) if (!props.section.items.length) return null function scrollTrack(direction: 'left' | 'right') { const track = trackRef.current if (!track) return const distance = Math.max(track.clientWidth * CAROUSEL_SCROLL_DISTANCE_RATIO, 320) track.scrollBy({ left: direction === 'left' ? -distance : distance, behavior: 'smooth', }) } return (
{props.section.title}
{scrollState.canScrollLeft ? (
) } function MediaTile(props: { card: MediaCard isContinueWatching: boolean styleType: 'poster' | 'landscape' | 'profile' | 'genre' | 'network' | 'episode' busy: boolean onOpenCard: (card: MediaCard, originRect?: ModalOriginRect | null) => void onRequest: (card: MediaCard) => Promise }) { const imageUrl = props.styleType === 'landscape' || props.styleType === 'episode' ? (props.card.backdropUrl || props.card.posterUrl) : props.card.posterUrl const continueEpisodeMeta = props.isContinueWatching ? parseContinueEpisodeMeta(props.card) : null const showLandscapeLogo = (props.styleType === 'landscape' || props.styleType === 'episode') && props.card.logoUrl && props.card.backdropLanguageFallback const tileClassName = [ 'media-tile', props.styleType, showLandscapeLogo ? 'has-landscape-logo' : '', props.isContinueWatching ? 'continue-tile' : '', props.isContinueWatching && props.card.progress ? 'has-progress' : '', ].filter(Boolean).join(' ') return (
) } function TitleDetailsModal(props: { card: MediaCard config: AppConfig onClose: () => void originRect: ModalOriginRect | null onRequest: (card: MediaCard, qualityProfileId?: number, seasonNumber?: number) => Promise currentUser: string | null qualityProfiles: { sonarr: SelectOption[]; radarr: SelectOption[] } }) { const [details, setDetails] = useState(null) const [detailsLoading, setDetailsLoading] = useState(true) const [detailsError, setDetailsError] = useState('') const [activeSeasonId, setActiveSeasonId] = useState(undefined) const [episodeWatchBusyId, setEpisodeWatchBusyId] = useState(null) const [episodeDownloadBusyId, setEpisodeDownloadBusyId] = useState(null) const [pendingEpisodeRequestIds, setPendingEpisodeRequestIds] = useState([]) const [pendingSeasonRequestIds, setPendingSeasonRequestIds] = useState([]) const [seasonActionBusy, setSeasonActionBusy] = useState<'download' | 'delete' | null>(null) const [seasonMenuOpen, setSeasonMenuOpen] = useState(false) const [movieRequestPending, setMovieRequestPending] = useState(false) const [movieDeleteBusy, setMovieDeleteBusy] = useState(false) const [qualityPicker, setQualityPicker] = useState<{ title: string logoUrl?: string profiles: SelectOption[] onConfirm: (qualityProfileId?: number) => void } | null>(null) const [playerTarget, setPlayerTarget] = useState<{ id: string; title: string } | null>(null) const [isOverviewExpanded, setIsOverviewExpanded] = useState(false) const [episodeScrollState, setEpisodeScrollState] = useState({ canScrollLeft: false, canScrollRight: false }) const [transitionState, setTransitionState] = useState<'opening' | 'open' | 'closing'>( props.originRect ? 'opening' : 'open' ) const [transitionStyle, setTransitionStyle] = useState(undefined) const closeTimeoutRef = useRef(null) const modalRef = useRef(null) const episodeListRef = useRef(null) const seasonMenuRef = useRef(null) const seasonMenuOptionsRef = useRef(null) const pendingSeasonScrollRef = useRef(null) const initialEpisodeFocusKeyRef = useRef('') const hasUserScrolledEpisodeListRef = useRef(false) const initialEpisodeListScrollLeftRef = useRef(0) const seasonValue = activeSeasonId ?? details?.selectedSeasonId ?? '' useLayoutEffect(() => { if (!props.originRect || !modalRef.current) { setTransitionState('open') setTransitionStyle(undefined) return } const modalRect = modalRef.current.getBoundingClientRect() const scaleX = props.originRect.width / modalRect.width const scaleY = props.originRect.height / modalRect.height const translateX = props.originRect.left - modalRect.left const translateY = props.originRect.top - modalRect.top setTransitionStyle({ ['--title-modal-from-x' as '--title-modal-from-x']: `${translateX}px`, ['--title-modal-from-y' as '--title-modal-from-y']: `${translateY}px`, ['--title-modal-from-scale-x' as '--title-modal-from-scale-x']: `${scaleX}`, ['--title-modal-from-scale-y' as '--title-modal-from-scale-y']: `${scaleY}`, } as CSSProperties) let frameA = 0 let frameB = 0 frameA = window.requestAnimationFrame(() => { frameB = window.requestAnimationFrame(() => { setTransitionState('open') }) }) return () => { window.cancelAnimationFrame(frameA) window.cancelAnimationFrame(frameB) } }, [props.card.id, props.originRect]) useEffect(() => () => { if (closeTimeoutRef.current) { window.clearTimeout(closeTimeoutRef.current) } }, []) useEffect(() => { setDetails(null) setDetailsLoading(true) setDetailsError('') setActiveSeasonId(undefined) setEpisodeWatchBusyId(null) setEpisodeDownloadBusyId(null) setPendingEpisodeRequestIds([]) setPendingSeasonRequestIds([]) setSeasonActionBusy(null) setSeasonMenuOpen(false) setMovieRequestPending(false) setPlayerTarget(null) setIsOverviewExpanded(false) pendingSeasonScrollRef.current = null initialEpisodeFocusKeyRef.current = '' hasUserScrolledEpisodeListRef.current = false initialEpisodeListScrollLeftRef.current = 0 }, [props.card.id]) useEffect(() => { if (!seasonMenuOpen) { return } function closeSeasonMenuOnOutsidePress(event: PointerEvent) { if (!seasonMenuRef.current?.contains(event.target as Node)) { setSeasonMenuOpen(false) } } function closeSeasonMenuOnEscape(event: KeyboardEvent) { if (event.key === 'Escape') { setSeasonMenuOpen(false) } } window.addEventListener('pointerdown', closeSeasonMenuOnOutsidePress) window.addEventListener('keydown', closeSeasonMenuOnEscape) return () => { window.removeEventListener('pointerdown', closeSeasonMenuOnOutsidePress) window.removeEventListener('keydown', closeSeasonMenuOnEscape) } }, [seasonMenuOpen]) useEffect(() => { if (!seasonMenuOpen || !seasonMenuOptionsRef.current) { return } const selectedOption = seasonMenuOptionsRef.current.querySelector('[aria-selected="true"]') if (!selectedOption) { return } seasonMenuOptionsRef.current.scrollTop = Math.max( 0, selectedOption.offsetTop - (seasonMenuOptionsRef.current.clientHeight - selectedOption.offsetHeight) / 2 ) }, [seasonMenuOpen, seasonValue]) function updateEpisodeInCaches(episodeId: string, updater: (episode: NonNullable[number]) => NonNullable[number]) { setDetails((current) => current && current.episodes.some((episode) => episode.id === episodeId) ? { ...current, episodes: current.episodes.map((episode) => episode.id === episodeId ? updater(episode) : episode) } : current) } const refreshSeasonState = useCallback(async (targetSeasonId?: string) => { const refreshSeasonId = targetSeasonId || activeSeasonId || details?.selectedSeasonId const nextDetails = await api.getTitleDetails(props.card, refreshSeasonId) setDetails(nextDetails) setDetailsError('') setActiveSeasonId(refreshSeasonId || nextDetails.selectedSeasonId) }, [activeSeasonId, details?.selectedSeasonId, props.card]) useEffect(() => { let cancelled = false setDetailsLoading(true) setDetailsError('') void api.getTitleDetails(props.card) .then((nextDetails) => { if (cancelled) return setDetails(nextDetails) setActiveSeasonId(nextDetails.selectedSeasonId) }) .catch((error) => { if (cancelled) return setDetailsError(error instanceof Error ? error.message : 'Failed to load title details.') }) .finally(() => { if (cancelled) return setDetailsLoading(false) }) return () => { cancelled = true } }, [props.card]) useEffect(() => { const list = episodeListRef.current const targetSeasonId = pendingSeasonScrollRef.current if (!list || !targetSeasonId) { return } const targetEpisode = findSeasonAnchorElement(list, targetSeasonId) if (!targetEpisode) { return } list.scrollTo({ left: Math.max(0, targetEpisode.offsetLeft - (list.clientWidth - targetEpisode.offsetWidth) / 2), behavior: 'smooth', }) pendingSeasonScrollRef.current = null }, [details, seasonValue]) useLayoutEffect(() => { const list = episodeListRef.current const playTargetId = details?.playTargetId if (!list || !playTargetId || pendingSeasonScrollRef.current) { return } const focusKey = `${props.card.id}:${playTargetId}` if (initialEpisodeFocusKeyRef.current === focusKey) { return } if (!centerEpisodeInList(list, playTargetId, 'auto')) { return } initialEpisodeListScrollLeftRef.current = list.scrollLeft initialEpisodeFocusKeyRef.current = focusKey }, [details?.playTargetId, props.card.id]) useEffect(() => { const list = episodeListRef.current if (!list || detailsLoading || details?.mediaType !== 'series') { setEpisodeScrollState({ canScrollLeft: false, canScrollRight: false }) return } const syncScrollState = () => { const maxScrollLeft = list.scrollWidth - list.clientWidth setEpisodeScrollState({ canScrollLeft: list.scrollLeft > 8, canScrollRight: maxScrollLeft - list.scrollLeft > 8, }) if ( !hasUserScrolledEpisodeListRef.current && Math.abs(list.scrollLeft - initialEpisodeListScrollLeftRef.current) > 32 ) { hasUserScrolledEpisodeListRef.current = true } const viewportLeft = list.scrollLeft const viewportRight = viewportLeft + list.clientWidth const coverageBySeason = new Map() const boundsBySeason = new Map() const cards = list.querySelectorAll('[data-season-id]') for (const card of cards) { const seasonId = card.dataset.seasonId if (!seasonId) continue const cardLeft = card.offsetLeft const cardRight = cardLeft + card.offsetWidth const currentBounds = boundsBySeason.get(seasonId) boundsBySeason.set(seasonId, { left: currentBounds ? Math.min(currentBounds.left, cardLeft) : cardLeft, right: currentBounds ? Math.max(currentBounds.right, cardRight) : cardRight, }) const visibleWidth = Math.min(cardRight, viewportRight) - Math.max(cardLeft, viewportLeft) if (visibleWidth <= 0) continue coverageBySeason.set(seasonId, (coverageBySeason.get(seasonId) || 0) + visibleWidth) } let dominantSeasonId = seasonValue let dominantCoverage = -1 for (const [seasonId, coverage] of coverageBySeason.entries()) { if (coverage > dominantCoverage) { dominantCoverage = coverage dominantSeasonId = seasonId } } const currentCoverage = coverageBySeason.get(activeSeasonId || seasonValue) || 0 const coverageThreshold = Math.max(currentCoverage * SEASON_DOMINANCE_SWITCH_RATIO, SEASON_DOMINANCE_SWITCH_MIN_PX) if ( hasUserScrolledEpisodeListRef.current && !pendingSeasonScrollRef.current && dominantSeasonId && dominantSeasonId !== activeSeasonId && dominantCoverage - currentCoverage > coverageThreshold ) { setActiveSeasonId(dominantSeasonId) } } syncScrollState() list.addEventListener('scroll', syncScrollState, { passive: true }) window.addEventListener('resize', syncScrollState) return () => { list.removeEventListener('scroll', syncScrollState) window.removeEventListener('resize', syncScrollState) } }, [activeSeasonId, details, detailsLoading, seasonValue]) const canRequest = Boolean(props.card.tmdbId && props.card.mediaType !== 'mixed') const playId = details?.playTargetId || details?.providerId || props.card.providerId const isAvailableInJellyfin = details?.availableInJellyfin ?? Boolean(props.card.providerId) const canPlay = Boolean(isAvailableInJellyfin && playId && props.config.jellyfin.baseUrl) const backgroundImage = details?.backdropUrl || props.card.backdropUrl || props.card.posterUrl const logoUrl = details?.logoUrl || props.card.logoUrl const displayTitle = details?.title || props.card.title const displaySubtitle = details?.subtitle || props.card.subtitle const displayOverview = details?.overview || props.card.overview || 'No details available yet.' const displayYear = props.card.releaseDate?.slice(0, 4) || props.card.firstAirDate?.slice(0, 4) || displaySubtitle.match(/\b(19|20)\d{2}\b/)?.[0] || '' const truncatedOverview = truncateOverview(displayOverview, window.matchMedia('(max-width: 980px)').matches ? 150 : 260) const shouldShowOverviewToggle = truncatedOverview !== displayOverview const jellyfinPlayerUrl = playerTarget && props.config.jellyfin.baseUrl ? buildJellyfinPlayerUrl(props.config.jellyfin.baseUrl, playerTarget.id) : '' const playLabel = playerTarget?.title || details?.episodes.find((episode) => episode.id === playId)?.title || displayTitle const activeSeasonMeta = details?.seasons.find((season) => season.id === seasonValue) const effectiveActiveSeasonMeta = activeSeasonMeta && pendingSeasonRequestIds.includes(activeSeasonMeta.id) && activeSeasonMeta.downloadStatus === 'idle' ? { ...activeSeasonMeta, downloadStatus: 'processing' as const, } : activeSeasonMeta const activeSeasonDetails = details && seasonValue ? { episodes: getSeasonEpisodes(details.episodes, seasonValue) } : null const movieRequestStatus = movieRequestPending && (details?.requestStatus || 'idle') === 'idle' ? 'processing' : details?.requestStatus || 'idle' const movieRequestProgress = details?.requestProgress || 0 const isMovieRequestActive = details?.mediaType === 'movie' && (movieRequestStatus === 'processing' || movieRequestStatus === 'downloading') const canDeleteMovieAction = Boolean(details?.mediaType === 'movie' && details.radarrMovieId) const activeSeasonNumber = effectiveActiveSeasonMeta?.seasonNumber const activeSeasonDownloadStatus = effectiveActiveSeasonMeta?.downloadStatus || 'idle' const currentSeasonIndex = details?.seasons.findIndex((season) => season.id === seasonValue) ?? -1 const resolvedSeasonIndex = currentSeasonIndex >= 0 ? currentSeasonIndex : 0 const hasPreviousSeason = Boolean(details?.seasons.length && resolvedSeasonIndex > 0) const hasNextSeason = Boolean(details?.seasons.length && resolvedSeasonIndex < details.seasons.length - 1) const visibleEpisodes = details ? details.episodes.map((episode) => pendingEpisodeRequestIds.includes(episode.id) && episode.downloadStatus !== 'downloading' && episode.availability !== 'available' ? { ...episode, downloadStatus: 'processing' as const, canDownload: false, } : episode) : [] const canDownloadSeasonAction = Boolean( activeSeasonDownloadStatus === 'processing' || activeSeasonDownloadStatus === 'downloading' || (details?.sonarrSeriesId && typeof activeSeasonNumber === 'number' && activeSeasonNumber > 0) || effectiveActiveSeasonMeta?.canDownload || (canRequest && !details?.sonarrSeriesId && typeof activeSeasonNumber === 'number') ) const episodesForSeason = visibleEpisodes.filter(episode => episode.seasonId === seasonValue); const isSeasonFullyDownloadedExceptUnaired = episodesForSeason.length > 0 && episodesForSeason.every( (episode) => episode.availability === 'available' || episode.availability === 'unaired' ); const canDeleteSeasonAction = (Boolean(effectiveActiveSeasonMeta?.canDelete) || isSeasonFullyDownloadedExceptUnaired); const shouldShowDownloadSeasonAction = canDownloadSeasonAction && !canDeleteSeasonAction; useEffect(() => { if (!details || details.mediaType !== 'series') { return } setPendingEpisodeRequestIds((current) => current.filter((episodeId) => { const episode = details.episodes.find((entry) => entry.id === episodeId) if (!episode) { return false } return episode.downloadStatus !== 'downloading' && episode.availability !== 'available' })) }, [details]) useEffect(() => { if (!pendingEpisodeRequestIds.length) { return } const timeoutId = window.setTimeout(() => { setPendingEpisodeRequestIds([]) }, 20000) return () => { window.clearTimeout(timeoutId) } }, [pendingEpisodeRequestIds]) useEffect(() => { if (!details || details.mediaType !== 'series') { return } setPendingSeasonRequestIds((current) => current.filter((seasonId) => { const season = details.seasons.find((entry) => entry.id === seasonId) if (!season) { return false } return season.downloadStatus !== 'downloading' && season.canDelete !== true })) }, [details]) useEffect(() => { if (!pendingSeasonRequestIds.length) { return } const timeoutId = window.setTimeout(() => { setPendingSeasonRequestIds([]) }, 25000) return () => { window.clearTimeout(timeoutId) } }, [pendingSeasonRequestIds]) useEffect(() => { if (!details || details.mediaType !== 'series') { return } if (activeSeasonDownloadStatus !== 'processing' && activeSeasonDownloadStatus !== 'downloading') { return } const timeoutId = window.setTimeout(() => { void refreshSeasonState(seasonValue || undefined) }, 3500) return () => { window.clearTimeout(timeoutId) } }, [activeSeasonDownloadStatus, details, refreshSeasonState, seasonValue]) useEffect(() => { if (!details || details.mediaType !== 'series') { return } const hasEpisodeTransfers = details.episodes.some((episode) => episode.downloadStatus === 'processing' || episode.downloadStatus === 'downloading' ) if (!hasEpisodeTransfers) { return } const timeoutId = window.setTimeout(() => { void refreshSeasonState(seasonValue || undefined) }, 2500) return () => { window.clearTimeout(timeoutId) } }, [details, refreshSeasonState, seasonValue]) useEffect(() => { if (!details || details.mediaType !== 'movie') { return } if (movieRequestPending && details.requestStatus === 'downloading') { setMovieRequestPending(false) } }, [details, movieRequestPending]) useEffect(() => { if (!movieRequestPending) { return } const timeoutId = window.setTimeout(() => { setMovieRequestPending(false) }, 5 * 60 * 1000) return () => { window.clearTimeout(timeoutId) } }, [movieRequestPending]) useEffect(() => { if (!details || details.mediaType !== 'movie') { return } if (movieRequestStatus !== 'processing' && movieRequestStatus !== 'downloading') { return } const timeoutId = window.setTimeout(() => { void refreshSeasonState() }, movieRequestStatus === 'processing' ? 2000 : 2500) return () => { window.clearTimeout(timeoutId) } }, [details, movieRequestStatus, refreshSeasonState]) function handleRequestClose() { if (!props.originRect || transitionState === 'closing') { props.onClose() return } setTransitionState('closing') closeTimeoutRef.current = window.setTimeout(() => { props.onClose() }, 680) } function scrollEpisodes(direction: 'left' | 'right') { const list = episodeListRef.current if (!list) return const distance = Math.max(list.clientWidth * EPISODE_SCROLL_DISTANCE_RATIO, 320) list.scrollBy({ left: direction === 'left' ? -distance : distance, behavior: 'smooth', }) } function changeSeason(offset: -1 | 1) { if (!details?.seasons.length) { return } const nextSeason = details.seasons[resolvedSeasonIndex + offset] if (!nextSeason) { return } pendingSeasonScrollRef.current = nextSeason.id setActiveSeasonId(nextSeason.id) } function handleSeasonSelectChange(nextSeasonId: string) { pendingSeasonScrollRef.current = nextSeasonId || null setActiveSeasonId(nextSeasonId || undefined) setSeasonMenuOpen(false) } function handleEpisodeWatchToggle( event: MouseEvent, episodeId: string, watched: boolean | undefined, progress: number | undefined, playbackPositionTicks: number | undefined ) { event.preventDefault() event.stopPropagation() const nextWatched = !watched setEpisodeWatchBusyId(episodeId) updateEpisodeInCaches(episodeId, (episode) => ({ ...episode, watched: nextWatched, progress: nextWatched ? undefined : 0, playbackPositionTicks: nextWatched ? undefined : 0, })) void api.setEpisodeWatchState({ episodeId, watched: nextWatched }) .catch(() => { updateEpisodeInCaches(episodeId, (episode) => ({ ...episode, watched: watched ?? false, progress, playbackPositionTicks, })) }) .finally(() => { setEpisodeWatchBusyId((current) => current === episodeId ? null : current) }) } function openQualityPicker( title: string, profiles: SelectOption[], onConfirm: (qualityProfileId?: number) => void ) { setQualityPicker({ title, logoUrl, profiles, onConfirm }) } async function handleSeasonDownload(qualityProfileId?: number) { if (typeof activeSeasonNumber !== 'number') { return } if (activeSeasonDownloadStatus === 'processing' || activeSeasonDownloadStatus === 'downloading') { return } setSeasonActionBusy('download') setDetailsError('') try { if (activeSeasonMeta?.id) { setPendingSeasonRequestIds((current) => current.includes(activeSeasonMeta.id) ? current : [...current, activeSeasonMeta.id]) } if (details?.sonarrSeriesId) { await api.requestSeason({ seriesId: details.sonarrSeriesId, seasonNumber: activeSeasonNumber, qualityProfileId, }, props.currentUser) } else { await props.onRequest(props.card, qualityProfileId, activeSeasonNumber) } await refreshSeasonState(seasonValue || undefined) } catch (error) { if (activeSeasonMeta?.id) { setPendingSeasonRequestIds((current) => current.filter((id) => id !== activeSeasonMeta.id)) } setDetailsError(error instanceof Error ? error.message : 'Failed to queue the season download.') } finally { setSeasonActionBusy(null) } } async function handleSeasonDelete() { if (!details?.sonarrSeriesId || typeof activeSeasonNumber !== 'number') { return } if (!window.confirm(`Delete downloaded files for Season ${activeSeasonNumber}?`)) { return } setSeasonActionBusy('delete') setDetailsError('') try { await api.deleteSeason({ seriesId: details.sonarrSeriesId, seasonNumber: activeSeasonNumber, }) setDetails((current) => current ? { ...current, episodes: current.episodes.map((episode) => { if (episode.seasonId !== seasonValue || episode.availability === 'unaired') { return episode } return { ...episode, availableInJellyfin: false, availability: 'missing', downloadStatus: 'idle', downloadProgress: undefined, canDownload: true, canDelete: false, } }), seasons: current.seasons.map((season) => season.id === seasonValue ? { ...season, availableEpisodeCount: 0, missingEpisodeCount: current.episodes.filter( (episode) => episode.seasonId === seasonValue && episode.availability !== 'unaired' ).length, canDownload: true, canDelete: false, isDownloading: false, downloadStatus: 'idle', downloadProgress: undefined, downloadLabel: undefined, } : season), } : current) window.setTimeout(() => { void refreshSeasonState(seasonValue || undefined) }, 2000) } catch (error) { setDetailsError(error instanceof Error ? error.message : 'Failed to delete season files.') } finally { setSeasonActionBusy(null) } } async function handleMovieRequest(qualityProfileId?: number) { if (details?.mediaType !== 'movie' || movieRequestStatus === 'processing' || movieRequestStatus === 'downloading') { return } setDetailsError('') setMovieRequestPending(true) setDetails((current) => current && current.mediaType === 'movie' ? { ...current, requestStatus: 'processing', requestProgress: undefined, } : current) try { await props.onRequest(props.card, qualityProfileId) await refreshSeasonState() } catch (error) { setMovieRequestPending(false) setDetails((current) => current && current.mediaType === 'movie' ? { ...current, requestStatus: 'idle', requestProgress: undefined, } : current) setDetailsError(error instanceof Error ? error.message : 'Failed to queue the movie download.') } } async function handleMovieDelete() { if (!details?.radarrMovieId) { return } if (!window.confirm(`Delete ${displayTitle} from Radarr and remove its downloaded files?`)) { return } setMovieDeleteBusy(true) setDetailsError('') try { await api.deleteMovie({ movieId: details.radarrMovieId }) setDetails((current) => current && current.mediaType === 'movie' ? { ...current, availableInJellyfin: false, providerId: undefined, playTargetId: undefined, radarrMovieId: undefined, requestStatus: 'idle', requestProgress: undefined, } : current) } catch (error) { setDetailsError(error instanceof Error ? error.message : 'Failed to delete movie files.') } finally { setMovieDeleteBusy(false) } } function handleEpisodeDownload( event: MouseEvent, episodeId: string, sonarrEpisodeId: number | undefined, availability: TitleDetailsResponse['episodes'][number]['availability'] ) { event.preventDefault() event.stopPropagation() if (!sonarrEpisodeId || availability === 'downloading' || episodeDownloadBusyId === episodeId) { return } openQualityPicker( `Download ${details?.episodes.find((episode) => episode.id === episodeId)?.title || 'episode'}`, props.qualityProfiles.sonarr, (qualityProfileId) => queueEpisodeDownload(episodeId, sonarrEpisodeId, availability, qualityProfileId) ) } function queueEpisodeDownload( episodeId: string, sonarrEpisodeId: number, availability: TitleDetailsResponse['episodes'][number]['availability'], qualityProfileId?: number ) { setEpisodeDownloadBusyId(episodeId) setPendingEpisodeRequestIds((current) => current.includes(episodeId) ? current : [...current, episodeId]) updateEpisodeInCaches(episodeId, (episode) => ({ ...episode, downloadStatus: 'processing', downloadProgress: undefined, canDownload: false, })) void api.requestEpisode({ episodeId: sonarrEpisodeId, qualityProfileId }, props.currentUser) .catch(() => { setPendingEpisodeRequestIds((current) => current.filter((id) => id !== episodeId)) updateEpisodeInCaches(episodeId, (episode) => ({ ...episode, availability, downloadStatus: 'idle', downloadProgress: undefined, canDownload: availability === 'missing', })) }) .finally(() => { setEpisodeDownloadBusyId((current) => current === episodeId ? null : current) }) } return (
event.stopPropagation()} ref={modalRef} role="dialog" aria-modal="true" style={transitionStyle} > {detailsLoading && !details ? (
) : null}
{playerTarget && jellyfinPlayerUrl ? (