From 07e1b4e89ab199965837bd20df230854a39ef192 Mon Sep 17 00:00:00 2001 From: WonderAliceUwU Date: Sun, 2 Aug 2026 09:39:16 +0200 Subject: [PATCH] feature and fix: add library, fix season names and episode names language --- server/index.ts | 36 +++-- server/lib/services.ts | 341 +++++++++++++++++++++++++++++++++-------- shared/contracts.ts | 33 ++++ src/App.tsx | 311 ++++++++++++++++++++++++++++++++++--- src/api.ts | 28 ++-- src/index.css | 89 ++++++++++- 6 files changed, 729 insertions(+), 109 deletions(-) diff --git a/server/index.ts b/server/index.ts index 1badc6d..96df762 100644 --- a/server/index.ts +++ b/server/index.ts @@ -32,7 +32,10 @@ import { requestSeason, requestSeries, setEpisodeWatchState, - sanitizeConfig + sanitizeConfig, + getDownloadsResponse, + dismissCompletedDownload, + dismissAllCompletedDownloads } from './lib/services.js'; interface SessionRecord { @@ -228,7 +231,7 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): if (url.pathname === '/api/downloads' && method === 'GET') { const config = await readConfig(session!.encryptionKey); - sendJson(response, 200, await getDownloads(config)); + sendJson(response, 200, await getDownloadsResponse(config)); return; } @@ -296,34 +299,47 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/downloads/dismiss' && method === 'POST') { + const body = await readJson<{ id: string }>(request); + dismissCompletedDownload(String(body.id || '')); + sendJson(response, 200, { ok: true }); + return; + } + + if (url.pathname === '/api/downloads/dismiss-all' && method === 'POST') { + dismissAllCompletedDownloads(); + sendJson(response, 200, { ok: true }); + return; + } + if (url.pathname === '/api/requests/movie' && method === 'POST') { const config = await readConfig(session!.encryptionKey); - const body = await readJson<{ tmdbId: number }>(request); - await requestMovie(config, Number(body.tmdbId)); + const body = await readJson<{ tmdbId: number; user: string | null }>(request); + await requestMovie(config, Number(body.tmdbId), body.user); sendJson(response, 200, { ok: true }); return; } if (url.pathname === '/api/requests/series' && method === 'POST') { const config = await readConfig(session!.encryptionKey); - const body = await readJson<{ tmdbId: number }>(request); - await requestSeries(config, Number(body.tmdbId)); + const body = await readJson<{ tmdbId: number; user: string | null }>(request); + await requestSeries(config, Number(body.tmdbId), body.user); sendJson(response, 200, { ok: true }); return; } if (url.pathname === '/api/requests/season' && method === 'POST') { const config = await readConfig(session!.encryptionKey); - const body = await readJson(request); - await requestSeason(config, body); + const body = await readJson(request); + await requestSeason(config, body, body.user); sendJson(response, 200, { ok: true }); return; } if (url.pathname === '/api/requests/episode' && method === 'POST') { const config = await readConfig(session!.encryptionKey); - const body = await readJson(request); - await requestEpisode(config, body); + const body = await readJson(request); + await requestEpisode(config, body, body.user); sendJson(response, 200, { ok: true }); return; } diff --git a/server/lib/services.ts b/server/lib/services.ts index 8a04128..4b47c9f 100644 --- a/server/lib/services.ts +++ b/server/lib/services.ts @@ -2,14 +2,17 @@ import type { AppConfig, CalendarEntry, CalendarResponse, + CompletedDownloadItem, ConnectionStatus, DashboardResponse, DownloadItem, + DownloadsResponse, EpisodeRequestPayload, EpisodeWatchStateRequest, HubPageResponse, HubSection, MediaCard, + ProcessingItem, SeasonDeletePayload, SeasonRequestPayload, SelectOption, @@ -23,6 +26,88 @@ import type { const TMDB_IMAGE = 'https://image.tmdb.org/t/p'; +const PROCESSING_TTL_MS = 60 * 60 * 1000; // 1 hour max +const processingQueue: ProcessingItem[] = []; +const completedDownloads: CompletedDownloadItem[] = []; +let previousDownloadIds = new Set(); + +export function addProcessingItem(item: Omit): void { + const id = `proc-${item.source}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + processingQueue.push({ + ...item, + id, + user: item.user || 'Unknown', + createdAt: new Date().toISOString(), + }); +} + +export function getProcessingItems(): ProcessingItem[] { + const now = Date.now(); + // Remove expired items (older than 1 hour) + for (let i = processingQueue.length - 1; i >= 0; i--) { + if (now - new Date(processingQueue[i].createdAt).getTime() > PROCESSING_TTL_MS) { + processingQueue.splice(i, 1); + } + } + return [...processingQueue]; +} + +function reconcileProcessingWithDownloads(downloads: DownloadItem[]): void { + const downloadTitles = new Set(downloads.map((d) => d.title.toLowerCase())); + for (let i = processingQueue.length - 1; i >= 0; i--) { + if (downloadTitles.has(processingQueue[i].title.toLowerCase())) { + processingQueue.splice(i, 1); + } + } +} + +function detectCompletedDownloads(currentDownloads: DownloadItem[]): void { + const currentIds = new Set(currentDownloads.map((d) => d.id)); + // Items that were downloading before but are no longer in the queue = completed + for (const prevId of previousDownloadIds) { + if (!currentIds.has(prevId)) { + // Find the item info from the last known state — we stored it below + const cached = lastKnownDownloads.get(prevId); + if (cached) { + completedDownloads.push({ + id: `done-${prevId}-${Date.now()}`, + source: cached.source, + title: cached.title, + subtitle: cached.subtitle, + posterUrl: cached.posterUrl, + backdropUrl: cached.backdropUrl, + tmdbId: cached.tmdbId, + mediaType: cached.mediaType, + completedAt: new Date().toISOString(), + }); + } + } + } + // Update tracking state + previousDownloadIds = currentIds; + lastKnownDownloads.clear(); + for (const d of currentDownloads) { + lastKnownDownloads.set(d.id, d); + } +} + +const lastKnownDownloads = new Map(); + +export function getCompletedDownloads(): CompletedDownloadItem[] { + return [...completedDownloads]; +} + +export function dismissCompletedDownload(id: string): void { + const idx = completedDownloads.findIndex((item) => item.id === id); + if (idx !== -1) { + completedDownloads.splice(idx, 1); + } +} + +export function dismissAllCompletedDownloads(): void { + completedDownloads.length = 0; +} + interface JellyfinItem { Id?: string; Name?: string; @@ -162,16 +247,18 @@ interface TvdbSeriesRecord { overview?: string; image?: string; artworks?: Array<{ image?: string; type?: number }>; - seasons?: Array<{ - id?: number; - number?: number; - image?: string; + seasons?: TvdbSeasonRecord[]; +} + +interface TvdbSeasonRecord { + id?: number; + number?: number; + image?: string; + name?: string; + type?: { name?: string; - type?: { - name?: string; - type?: string; - }; - }>; + type?: string; + }; } interface TvdbEpisodeRecord { @@ -253,6 +340,7 @@ interface SeriesSeasonDescriptor { title: string; seasonNumber?: number; episodeCount?: number; + hasTmdbSeason?: boolean; jellyfinSeasonId?: string; imageUrl?: string; } @@ -378,7 +466,9 @@ export async function getDashboard(config: AppConfig): Promise { console.log(`[getHubPage] Loading page: ${page}`); let library: { continueWatching: MediaCard[]; recentlyAdded: MediaCard[]; allItems: JellyfinItem[] }; - let downloads: DownloadItem[]; try { - [library, downloads] = await Promise.all([ - getLibrarySnapshot(config), - getDownloads(config) - ]); + library = await getLibrarySnapshot(config); } catch (err) { - console.error(`[getHubPage] Error fetching library/downloads for ${page}:`, err); + console.error(`[getHubPage] Error fetching library for ${page}:`, err); library = { continueWatching: [], recentlyAdded: [], allItems: [] }; - downloads = []; } const allSections = await buildHubSections(config, library, page).catch((err) => { @@ -459,16 +544,6 @@ export async function getHubPage( continueWatching: continueWatchingWithLogos, sections: sectionsWithLogos .filter((section) => section.items.some((item) => item.backdropUrl || item.posterUrl)) - .concat( - page === 'library' && downloads.length - ? [{ - id: 'downloads', - title: 'Downloading', - style: 'episode', - items: downloads.map(downloadToCard) - }] - : [] - ) }; } @@ -520,7 +595,23 @@ export async function getDownloads(config: AppConfig): Promise { const downloads = await Promise.all( baseDownloads.map((item) => enrichDownloadItem(config, item, metadataCache)) ); - return downloads.sort((a, b) => b.progress - a.progress); + const sorted = downloads.sort((a, b) => b.progress - a.progress); + + // Reconcile processing queue: remove items that now appear as downloads + reconcileProcessingWithDownloads(sorted); + // Detect completed downloads: items that disappeared from the queue + detectCompletedDownloads(sorted); + + return sorted; +} + +export async function getDownloadsResponse(config: AppConfig): Promise { + const downloading = await getDownloads(config); + return { + processing: getProcessingItems(), + downloading, + completed: getCompletedDownloads(), + }; } export async function getCalendar(config: AppConfig, start: Date, end: Date): Promise { @@ -1231,7 +1322,7 @@ function hasLikelyJapaneseText(value: string | undefined): boolean { async function getTvdbTranslation( config: AppConfig, - entity: 'episodes' | 'series', + entity: 'episodes' | 'seasons' | 'series', id: number ): Promise { const candidates = getTvdbTranslationCandidates(config); @@ -1290,6 +1381,26 @@ async function applyTvdbEpisodeTranslations( ); } +async function applyTvdbSeasonTranslations( + config: AppConfig, + seasons: TvdbSeasonRecord[] +): Promise { + if (!getTvdbTranslationCandidates(config).length) { + return seasons; + } + + return Promise.all( + seasons.map(async (season) => { + if (!season.id) { + return season; + } + + const translation = await getTvdbTranslation(config, 'seasons', season.id); + return translation?.name ? { ...season, name: translation.name } : season; + }) + ); +} + async function getTvdbSeriesSummary(config: AppConfig, tvdbId: number): Promise { const response = await tvdbFetch(config, `/series/${encodeURIComponent(String(tvdbId))}/extended`); const data = asRecord(response?.data); @@ -1297,6 +1408,24 @@ async function getTvdbSeriesSummary(config: AppConfig, tvdbId: number): Promise< return null; } + const seasons = await applyTvdbSeasonTranslations( + config, + asArray(data.seasons).map((entry) => { + const season = asRecord(entry); + const type = asRecord(season.type); + return { + id: Number(season.id || 0) || undefined, + number: Number(season.number || 0) || undefined, + image: typeof season.image === 'string' ? season.image : undefined, + name: typeof season.name === 'string' ? season.name : undefined, + type: { + name: typeof type.name === 'string' ? type.name : undefined, + type: typeof type.type === 'string' ? type.type : undefined + } + } satisfies TvdbSeasonRecord; + }) + ); + return { id: Number(data.id || 0) || undefined, name: typeof data.name === 'string' ? data.name : undefined, @@ -1309,20 +1438,7 @@ async function getTvdbSeriesSummary(config: AppConfig, tvdbId: number): Promise< type: Number(artwork.type || 0) || undefined }; }), - seasons: asArray(data.seasons).map((entry) => { - const season = asRecord(entry); - const type = asRecord(season.type); - return { - id: Number(season.id || 0) || undefined, - number: Number(season.number || 0) || undefined, - image: typeof season.image === 'string' ? season.image : undefined, - name: typeof season.name === 'string' ? season.name : undefined, - type: { - name: typeof type.name === 'string' ? type.name : undefined, - type: typeof type.type === 'string' ? type.type : undefined - } - }; - }) + seasons }; } @@ -1447,7 +1563,7 @@ async function getTmdbSeasonEpisodes( ): Promise { const response = await tmdbFetch( config, - `/tv/${tmdbId}/season/${seasonNumber}` + `/tv/${tmdbId}/season/${seasonNumber}?language=${encodeURIComponent(config.preferences.language)}` ); return asArray(response?.episodes) @@ -1712,11 +1828,21 @@ function buildSeriesSeasonDescriptors( const tvdbSeasonBySeasonNumber = new Map( asArray(tvdbSeries?.seasons) - .map((entry) => entry as NonNullable[number]) + .map((entry) => entry as TvdbSeasonRecord) .filter((season) => typeof season.number === 'number' && season.number >= 0) .map((season) => [season.number as number, season] as const) ); - + const tmdbSeasonBySeasonNumber = new Map( + asArray(tmdbSeries?.seasons) + .map((entry) => asRecord(entry)) + .map((season) => ({ + seasonNumber: Number(season.season_number || 0), + name: typeof season.name === 'string' ? season.name : '', + episodeCount: Number(season.episode_count || 0) || undefined + } satisfies TmdbSeasonSummary)) + .filter((season) => Number.isFinite(season.seasonNumber) && season.seasonNumber >= 0) + .map((season) => [season.seasonNumber, season] as const) + ); const seasonNumbers = new Set([ ...tvdbEpisodeCountBySeasonNumber.keys(), ...tvdbSeasonBySeasonNumber.keys(), @@ -1730,16 +1856,23 @@ function buildSeriesSeasonDescriptors( .map((seasonNumber) => { const jellyfinSeason = jellyfinBySeasonNumber.get(seasonNumber); const tvdbSeason = tvdbSeasonBySeasonNumber.get(seasonNumber); + const tmdbSeason = tmdbSeasonBySeasonNumber.get(seasonNumber); + const episodeCount = tvdbEpisodeCountBySeasonNumber.get(seasonNumber) + ?? sonarrEpisodeCountBySeasonNumber.get(seasonNumber) + ?? jellyfinSeason?.episodeCount; return { id: buildSeasonId(seasonNumber), title: seasonNumber === 0 - ? jellyfinSeason?.title || tvdbSeason?.name || 'Specials' - : jellyfinSeason?.title || tvdbSeason?.name || `Season ${seasonNumber}`, + ? tvdbSeason?.name || jellyfinSeason?.title || 'Specials' + : tvdbSeason?.name || jellyfinSeason?.title || `Season ${seasonNumber}`, seasonNumber, - episodeCount: tvdbEpisodeCountBySeasonNumber.get(seasonNumber) - ?? sonarrEpisodeCountBySeasonNumber.get(seasonNumber) - ?? jellyfinSeason?.episodeCount, + episodeCount, + hasTmdbSeason: Boolean( + tmdbSeason + && episodeCount + && tmdbSeason.episodeCount === episodeCount + ), jellyfinSeasonId: jellyfinSeason?.jellyfinSeasonId }; }) @@ -1770,6 +1903,7 @@ function buildSeriesSeasonDescriptors( : season.name || `Season ${season.seasonNumber}`, seasonNumber: season.seasonNumber, episodeCount: season.episodeCount ?? jellyfinSeason?.episodeCount, + hasTmdbSeason: true, jellyfinSeasonId: jellyfinSeason?.jellyfinSeasonId }; }) @@ -1835,7 +1969,7 @@ async function buildSeasonEpisodes( ): Promise { const seasonNumber = season.seasonNumber; const [tmdbEpisodes, jellyfinEpisodes] = await Promise.all([ - tmdbId && typeof seasonNumber === 'number' + tmdbId && season.hasTmdbSeason && typeof seasonNumber === 'number' ? getTmdbSeasonEpisodes(config, tmdbId, seasonNumber) : Promise.resolve([]), jellyfinSeriesId && season.jellyfinSeasonId @@ -1922,8 +2056,8 @@ async function buildSeasonEpisodes( id: jellyfinEpisode?.id || buildEpisodeId(seasonNumber, episodeNumber), sonarrEpisodeId, seasonId: season.id, - title: tvdbEpisode?.name || sonarrEpisode?.title || jellyfinEpisode?.title || tmdbEpisode?.name || `Episode ${episodeNumber}`, - overview: tvdbEpisode?.overview || sonarrEpisode?.overview || jellyfinEpisode?.overview || tmdbEpisode?.overview || '', + title: tmdbEpisode?.name || tvdbEpisode?.name || sonarrEpisode?.title || jellyfinEpisode?.title || `Episode ${episodeNumber}`, + overview: tmdbEpisode?.overview || tvdbEpisode?.overview || sonarrEpisode?.overview || jellyfinEpisode?.overview || '', subtitle: [ typeof seasonNumber === 'number' ? `Season ${seasonNumber}` : '', `Episode ${episodeNumber}` @@ -2186,7 +2320,7 @@ function mapJellyfinEpisode(episode: JellyfinItem): TitleDetailsEpisode { }; } -export async function requestMovie(config: AppConfig, tmdbId: number): Promise { +export async function requestMovie(config: AppConfig, tmdbId: number, user: string | null): Promise { if (!config.radarr.baseUrl || !config.radarr.apiKey) { throw new Error('Radarr is not configured.'); } @@ -2260,9 +2394,19 @@ export async function requestMovie(config: AppConfig, tmdbId: number): Promise { +export async function requestSeries(config: AppConfig, tmdbId: number, user: string | null): Promise { if (!config.sonarr.baseUrl || !config.sonarr.apiKey) { throw new Error('Sonarr is not configured.'); } @@ -2281,6 +2425,15 @@ export async function requestSeries(config: AppConfig, tmdbId: number): Promise< } const sonarrRequestConfig = await resolveSonarrRequestConfig(config); + addProcessingItem({ + source: 'sonarr', + title: details.name || 'Series', + subtitle: 'All seasons', + tmdbId, + mediaType: 'series', + user: user || 'Unknown', + }); + await fetchJson(`${config.sonarr.baseUrl}/api/v3/series`, { method: 'POST', headers: { @@ -2302,9 +2455,17 @@ export async function requestSeries(config: AppConfig, tmdbId: number): Promise< } }) }); + + addProcessingItem({ + source: 'sonarr', + title: String(details.name || details.original_name || 'Series'), + tmdbId, + mediaType: 'tv', + requestedBy: 'You', + }); } -export async function requestSeason(config: AppConfig, payload: SeasonRequestPayload): Promise { +export async function requestSeason(config: AppConfig, payload: SeasonRequestPayload, user: string | null): Promise { if (!config.sonarr.baseUrl || !config.sonarr.apiKey) { throw new Error('Sonarr is not configured.'); } @@ -2352,9 +2513,18 @@ export async function requestSeason(config: AppConfig, payload: SeasonRequestPay seasonNumber: payload.seasonNumber }) }); + + addProcessingItem({ + source: 'sonarr', + title: series.title || 'Series', + subtitle: `Season ${payload.seasonNumber}`, + tmdbId: series.tmdbId, + mediaType: 'tv', + user: user || 'Unknown', + }); } -export async function requestEpisode(config: AppConfig, payload: EpisodeRequestPayload): Promise { +export async function requestEpisode(config: AppConfig, payload: EpisodeRequestPayload, user: string | null): Promise { if (!config.sonarr.baseUrl || !config.sonarr.apiKey) { throw new Error('Sonarr is not configured.'); } @@ -2374,6 +2544,32 @@ export async function requestEpisode(config: AppConfig, payload: EpisodeRequestP episodeIds: [payload.episodeId] }) }); + + // Try to get episode details for the processing item + try { + const episode = await fetchJson<{ title?: string; seasonNumber?: number; episodeNumber?: number; series?: { title?: string; tmdbId?: number } }>( + `${config.sonarr.baseUrl}/api/v3/episode/${encodeURIComponent(String(payload.episodeId))}`, + { headers: { 'X-Api-Key': config.sonarr.apiKey } } + ); + addProcessingItem({ + source: 'sonarr', + title: episode?.series?.title || 'Series', + subtitle: episode?.seasonNumber != null && episode?.episodeNumber != null + ? `S${String(episode.seasonNumber).padStart(2, '0')}E${String(episode.episodeNumber).padStart(2, '0')} \u00b7 ${episode.title || ''}` + : episode?.title || 'Episode', + tmdbId: episode?.series?.tmdbId, + mediaType: 'tv', + user: user || 'Unknown', + }); + } catch { + addProcessingItem({ + source: 'sonarr', + title: 'Episode', + subtitle: `Episode #${payload.episodeId}`, + mediaType: 'tv', + user: user || 'Unknown', + }); + } } export async function deleteSeasonFiles(config: AppConfig, payload: SeasonDeletePayload): Promise { @@ -2502,11 +2698,11 @@ async function getLibrarySnapshot(config: AppConfig): Promise<{ try { [resume, nextUp, allItems] = await Promise.all([ - jellyfinFetch(config, `/Users/${config.jellyfin.userId}/Items/Resume?mediaTypes=Video&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber`), - jellyfinFetch(config, `/Shows/NextUp?userId=${config.jellyfin.userId}&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber`), + jellyfinFetch(config, `/Users/${config.jellyfin.userId}/Items/Resume?mediaTypes=Video&enableUserData=true&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber,UserData`), + jellyfinFetch(config, `/Shows/NextUp?userId=${config.jellyfin.userId}&enableUserData=true&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber,UserData`), jellyfinFetch( config, - `/Users/${config.jellyfin.userId}/Items?recursive=true&includeItemTypes=Movie,Series&hasTmdbId=true&fields=ProviderIds,DateCreated,DateLastMediaAdded,Overview,ImageTags,BackdropImageTags,ProductionYear` + `/Users/${config.jellyfin.userId}/Items?recursive=true&includeItemTypes=Movie,Series&fields=ProviderIds,DateCreated,DateLastMediaAdded,Overview,ImageTags,BackdropImageTags,ProductionYear` ) ]); } catch { @@ -2893,16 +3089,29 @@ async function buildDoramaHub( } async function buildLibraryHub( - config: AppConfig, + _config: AppConfig, library: Awaited> ): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { - const downloads = await getDownloads(config); + const libraryItems = (type: 'Movie' | 'Series') => library.allItems + .filter((item) => item.Type === type) + .map((item) => jellyfinToCard(item, item.Name || 'Library')) + .filter(Boolean) as MediaCard[]; return { - hero: [...(library.continueWatching || []), ...(library.recentlyAdded || [])].slice(0, 6), + hero: (library.recentlyAdded || []).slice(0, 6), sections: [ - { id: 'recent', title: 'Recently Added', style: 'landscape', items: library.recentlyAdded || [] }, - { id: 'downloads', title: 'Downloading', style: 'episode', items: (downloads || []).map(downloadToCard) } + { + id: 'library-series', + title: 'Series', + style: 'landscape', + items: libraryItems('Series') + }, + { + id: 'library-movies', + title: 'Movies', + style: 'landscape', + items: libraryItems('Movie') + } ] }; } diff --git a/shared/contracts.ts b/shared/contracts.ts index d037490..5c6ca1b 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -200,6 +200,37 @@ export interface DownloadItem { mediaType?: 'movie' | 'tv' | 'series'; } +export interface ProcessingItem { + id: string; + source: 'sonarr' | 'radarr'; + title: string; + subtitle?: string; + posterUrl?: string; + backdropUrl?: string; + tmdbId?: number; + mediaType?: 'movie' | 'tv' | 'series'; + user: string; + createdAt: string; +} + +export interface CompletedDownloadItem { + id: string; + source: 'sonarr' | 'radarr'; + title: string; + subtitle?: string; + posterUrl?: string; + backdropUrl?: string; + tmdbId?: number; + mediaType?: 'movie' | 'tv' | 'series'; + completedAt: string; +} + +export interface DownloadsResponse { + processing: ProcessingItem[]; + downloading: DownloadItem[]; + completed: CompletedDownloadItem[]; +} + export interface CalendarEntry { id: string; source: 'sonarr' | 'radarr'; @@ -230,6 +261,8 @@ export interface DashboardResponse { recommendations: MediaCard[]; trendingSeries: MediaCard[]; downloads: DownloadItem[]; + processing: ProcessingItem[]; + completedDownloads: CompletedDownloadItem[]; } export interface TitleDetailsRequest { diff --git a/src/App.tsx b/src/App.tsx index 75b9a39..b96ce0c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -17,9 +17,11 @@ import { type AppConfig, type AppRoute, type ConnectionStatus, + type CompletedDownloadItem, type DownloadItem, type HubPageResponse, type MediaCard, + type ProcessingItem, type SearchResponse, type SelectOption, type ServiceOptionsResponse, @@ -81,6 +83,8 @@ function App() { radarrQualityProfiles: [], }) const [downloads, setDownloads] = useState([]) + const [processingItems, setProcessingItems] = useState([]) + const [completedDownloads, setCompletedDownloads] = useState([]) const [connections, setConnections] = useState([]) const [hubPages, setHubPages] = useState>>({}) const [hubLoading, setHubLoading] = useState(false) @@ -125,6 +129,8 @@ function App() { setConfig(settings) setOptions(serviceOptions) setDownloads(dashboard.downloads) + setProcessingItems(dashboard.processing || []) + setCompletedDownloads(dashboard.completedDownloads || []) setConnections(dashboard.connections) setEntryStage(resolveEntryStage(settings, serviceOptions)) } @@ -188,7 +194,12 @@ function App() { return } - if (route === 'downloads' || route === 'settings' || route === 'calendar' || route === 'search') { + if (route === 'settings' || route === 'calendar' || route === 'search') { + return + } + + if (route === 'downloads') { + void refreshBaseData() return } @@ -322,9 +333,9 @@ function App() { setNotice('') try { if (card.mediaType === 'movie') { - await api.requestMovie(card.tmdbId) + await api.requestMovie(card.tmdbId, currentJellyfinUser) } else { - await api.requestSeries(card.tmdbId) + await api.requestSeries(card.tmdbId, currentJellyfinUser) } if (route === 'calendar') { await loadCalendar({ silent: true }) @@ -345,8 +356,10 @@ function App() { setNotice('') try { await api.deleteDownload({ id }) - const nextDownloads = await api.getDownloads() - setDownloads(nextDownloads) + const resp = await api.getDownloads() + setDownloads(resp.downloading) + setProcessingItems(resp.processing) + setCompletedDownloads(resp.completed) setNotice('Download removed from the queue.') } catch (deleteError) { setError(deleteError instanceof Error ? deleteError.message : 'Failed to remove the download.') @@ -355,6 +368,24 @@ function App() { } } + 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) @@ -462,7 +493,7 @@ function App() { {route === 'calendar' ? setSelectedCard({ card, originRect: originRect ?? null })} /> : null} - {route === 'downloads' ? : null} + {route === 'downloads' ? : null} {route === 'search' ? ( setSelectedCard(null)} originRect={selectedCard.originRect} onRequest={handleRequest} + currentUser={currentJellyfinUser} /> ) : null} @@ -909,12 +941,34 @@ function HubPageView(props: { ) : 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('') @@ -1258,6 +1312,7 @@ function TitleDetailsModal(props: { onClose: () => void originRect: ModalOriginRect | null onRequest: (card: MediaCard) => Promise + currentUser: string | null }) { const [details, setDetails] = useState(null) const [detailsLoading, setDetailsLoading] = useState(true) @@ -1803,7 +1858,7 @@ function TitleDetailsModal(props: { await api.requestSeason({ seriesId: details.sonarrSeriesId, seasonNumber: activeSeasonNumber, - }) + }, props.currentUser) } else { await props.onRequest(props.card) } @@ -1895,7 +1950,7 @@ function TitleDetailsModal(props: { canDownload: false, })) - void api.requestEpisode({ episodeId: sonarrEpisodeId }) + void api.requestEpisode({ episodeId: sonarrEpisodeId }, props.currentUser) .catch(() => { setPendingEpisodeRequestIds((current) => current.filter((id) => id !== episodeId)) updateEpisodeInCaches(episodeId, (episode) => ({ @@ -2500,30 +2555,240 @@ function SearchPage(props: { ) } +function CollapsibleSection(props: { + title: string + count: number + children: ReactNode +}) { + const [isCollapsed, setIsCollapsed] = useState(false) + + return ( +
+ + {!isCollapsed &&
{props.children}
} +
+ ) +} + +function ProcessingCard(props: { + item: ProcessingItem, + onCancel: (id: string) => void +}) { + return ( +
+ {props.item.backdropUrl && } +
+
+
+
+
+
+

{props.item.title}

+

{props.item.subtitle}

+

Requested by: {props.item.user}

+
+ +
+
+ ) +} + +function DownloadingCard(props: { + item: DownloadItem, + onCancel: (id: string) => void +}) { + return ( +
+ {props.item.backdropUrl && } +
+
+
+

{props.item.title}

+

{props.item.subtitle}

+
+ +
+
+
+
+

{props.item.size} @ {props.item.eta}

+
+ ) +} + +function CompletedCard(props: { + item: CompletedDownloadItem, + onDismiss: (id: string) => void +}) { + return ( +
+ {props.item.backdropUrl && } +
+
+
+

{props.item.title}

+

{props.item.subtitle}

+

Completed

+
+ +
+
+ ) +} + function DownloadsPage(props: { downloads: DownloadItem[] + processingItems: ProcessingItem[] + completedDownloads: CompletedDownloadItem[] busyId: string onDelete: (id: string) => Promise + onDismissCompleted: (id: string) => void + onDismissAllCompleted: () => void }) { + const hasAny = props.processingItems.length > 0 || props.downloads.length > 0 || props.completedDownloads.length > 0 + return (

Downloads

-
-
- {props.downloads.length - ? props.downloads.map((item) => ( - - )) - : } -
-
+ + {props.processingItems.length > 0 ? ( +
+

Processing

+
+ {props.processingItems.map((item) => ( +
+
+
+ {item.posterUrl || item.backdropUrl + ? {item.title} + :
{item.title.slice(0, 1).toUpperCase()}
} +
+
+

{item.title}

+ {item.subtitle ?

{item.subtitle}

: null} +

+

+
+
+
+
+
+ Processing +
+
+
+
+ ))} +
+
+ ) : null} + + {props.downloads.length > 0 ? ( +
+

Downloading

+
+ {props.downloads.map((item) => ( + + ))} +
+
+ ) : null} + + {props.completedDownloads.length > 0 ? ( +
+
+

Completed

+ +
+
+ {props.completedDownloads.map((item) => ( +
+
+
+ {item.posterUrl || item.backdropUrl + ? {item.title} + :
{item.title.slice(0, 1).toUpperCase()}
} +
+
+

{item.title}

+ {item.subtitle ?

{item.subtitle}

: null} +

Download completed

+
+
+
+
+
+ 100% + Completed +
+
+
+
+
+ +
+
+
+
+ ))} +
+
+ ) : null} + + {!hasAny ? ( +
+
+ +
+
+ ) : null}
) } diff --git a/src/api.ts b/src/api.ts index 17ab0a6..deace13 100644 --- a/src/api.ts +++ b/src/api.ts @@ -5,6 +5,7 @@ import type { CalendarResponse, DashboardResponse, DownloadItem, + DownloadsResponse, HubPageResponse, MediaCard, SearchResponse, @@ -96,31 +97,40 @@ export const api = { method: 'POST', body: JSON.stringify(payload), }), - getDownloads: () => request('/api/downloads'), + getDownloads: () => request('/api/downloads'), deleteDownload: (payload: { id: string }) => request<{ ok: boolean }>('/api/downloads/delete', { method: 'POST', body: JSON.stringify(payload), }), - requestMovie: (tmdbId: number) => + dismissCompleted: (payload: { id: string }) => + request<{ ok: boolean }>('/api/downloads/dismiss', { + method: 'POST', + body: JSON.stringify(payload), + }), + dismissAllCompleted: () => + request<{ ok: boolean }>('/api/downloads/dismiss-all', { + method: 'POST', + }), + requestMovie: (tmdbId: number, user: string | null) => request<{ ok: boolean }>('/api/requests/movie', { method: 'POST', - body: JSON.stringify({ tmdbId }), + body: JSON.stringify({ tmdbId, user }), }), - requestSeries: (tmdbId: number) => + requestSeries: (tmdbId: number, user: string | null) => request<{ ok: boolean }>('/api/requests/series', { method: 'POST', - body: JSON.stringify({ tmdbId }), +body: JSON.stringify({ tmdbId, user }), }), - requestSeason: (payload: SeasonRequestPayload) => + requestSeason: (payload: SeasonRequestPayload, user: string | null) => request<{ ok: boolean }>('/api/requests/season', { method: 'POST', - body: JSON.stringify(payload), + body: JSON.stringify({ ...payload, user }), }), - requestEpisode: (payload: EpisodeRequestPayload) => + requestEpisode: (payload: EpisodeRequestPayload, user: string | null) => request<{ ok: boolean }>('/api/requests/episode', { method: 'POST', - body: JSON.stringify(payload), + body: JSON.stringify({ ...payload, user }), }), deleteSeason: (payload: SeasonDeletePayload) => request<{ ok: boolean }>('/api/seasons/delete', { diff --git a/src/index.css b/src/index.css index 5b52a5a..3448b2a 100644 --- a/src/index.css +++ b/src/index.css @@ -1052,6 +1052,23 @@ img { border-radius: 1.3rem; } +.library-grid-section { + display: grid; + gap: 0.9rem; + margin: 2.25rem 0; +} + +.library-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(23rem, 1fr)); + gap: 1.15rem; + padding: 1.5rem; +} + +.library-grid .media-tile.landscape { + width: 100%; +} + .profile .media-art { aspect-ratio: 1 / 1; border-radius: 999px; @@ -2985,6 +3002,77 @@ img { padding-bottom: 0.06rem; } +.downloads-section-title { + font-size: 1.05rem; + font-weight: 600; + color: #d8e5f9; + margin-bottom: 0.6rem; +} + +.downloads-section-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 0.6rem; +} + +.downloads-section-header .downloads-section-title { + margin-bottom: 0; +} + +.downloads-dismiss-all-button { + border: 0; + background: rgba(255, 255, 255, 0.07); + color: #98a8c4; + font-size: 0.82rem; + padding: 0.35rem 0.85rem; + border-radius: 999px; + cursor: pointer; + transition: background 0.15s, color 0.15s; +} + +.downloads-dismiss-all-button:hover { + background: rgba(255, 255, 255, 0.13); + color: #dbe2ee; +} + +.download-processing-label { + display: flex; + align-items: center; + gap: 0.45rem; +} + +.download-processing-spinner { + display: inline-block; + width: 0.85rem; + height: 0.85rem; + border: 2px solid rgba(255, 255, 255, 0.15); + border-top-color: #6aa9ff; + border-radius: 50%; + animation: processing-spin 0.8s linear infinite; +} + +@keyframes processing-spin { + to { transform: rotate(360deg); } +} + +.download-processing-badge { + font-size: 0.85rem; + color: #6aa9ff; + font-weight: 500; +} + +.download-completed-label { + color: #34c759; +} + +.download-completed-badge { + color: #34c759; +} + +.download-row-completed { + opacity: 0.85; +} .settings-page { grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -3777,4 +3865,3 @@ img { .calendar-entry-detail { color: #93a0b9; } -