feature and fix: add library, fix season names and episode names language

This commit is contained in:
WonderAliceUwU committed 2026-08-02 09:39:16 +02:00
1 parent e72a1ceb30
commit 07e1b4e89a
6 files changed
+729 -109

No files matched your search

+26 -10
View File
@@ -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<SeasonRequestPayload>(request);
await requestSeason(config, body);
const body = await readJson<SeasonRequestPayload & { user: string | null }>(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<EpisodeRequestPayload>(request);
await requestEpisode(config, body);
const body = await readJson<EpisodeRequestPayload & { user:string | null }>(request);
await requestEpisode(config, body, body.user);
sendJson(response, 200, { ok: true });
return;
}
+275 -66
View File
@@ -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<string>();
export function addProcessingItem(item: Omit<ProcessingItem, 'id' | 'createdAt'>): 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<string, DownloadItem>();
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<DashboardResponse
recentlyAdded: library.recentlyAdded,
recommendations: filteredRecommendations.slice(0, 12),
trendingSeries: filteredTrendingSeries.slice(0, 12),
downloads
downloads,
processing: getProcessingItems(),
completedDownloads: getCompletedDownloads()
};
}
@@ -388,17 +478,12 @@ export async function getHubPage(
): Promise<HubPageResponse> {
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<DownloadItem[]> {
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<DownloadsResponse> {
const downloading = await getDownloads(config);
return {
processing: getProcessingItems(),
downloading,
completed: getCompletedDownloads(),
};
}
export async function getCalendar(config: AppConfig, start: Date, end: Date): Promise<CalendarResponse> {
@@ -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<TvdbTranslationRecord | null> {
const candidates = getTvdbTranslationCandidates(config);
@@ -1290,6 +1381,26 @@ async function applyTvdbEpisodeTranslations(
);
}
async function applyTvdbSeasonTranslations(
config: AppConfig,
seasons: TvdbSeasonRecord[]
): Promise<TvdbSeasonRecord[]> {
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<TvdbSeriesRecord | null> {
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<TmdbEpisodeRecord[]> {
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<TvdbSeriesRecord['seasons']>[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<number>([
...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<TitleDetailsEpisode[]> {
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<void> {
export async function requestMovie(config: AppConfig, tmdbId: number, user: string | null): Promise<void> {
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<v
movieIds: [movie.id]
})
});
addProcessingItem({
source: 'radarr',
title: movie.title || 'Movie',
subtitle: movie.year ? String(movie.year) : undefined,
tmdbId: movie.tmdbId,
posterUrl: extractRemoteImage(movie.images),
mediaType: 'movie',
user: user || 'Unknown',
});
}
export async function requestSeries(config: AppConfig, tmdbId: number): Promise<void> {
export async function requestSeries(config: AppConfig, tmdbId: number, user: string | null): Promise<void> {
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<void> {
export async function requestSeason(config: AppConfig, payload: SeasonRequestPayload, user: string | null): Promise<void> {
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<void> {
export async function requestEpisode(config: AppConfig, payload: EpisodeRequestPayload, user: string | null): Promise<void> {
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<void> {
@@ -2502,11 +2698,11 @@ async function getLibrarySnapshot(config: AppConfig): Promise<{
try {
[resume, nextUp, allItems] = await Promise.all([
jellyfinFetch<JellyfinItem[]>(config, `/Users/${config.jellyfin.userId}/Items/Resume?mediaTypes=Video&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber`),
jellyfinFetch<JellyfinItem[]>(config, `/Shows/NextUp?userId=${config.jellyfin.userId}&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber`),
jellyfinFetch<JellyfinItem[]>(config, `/Users/${config.jellyfin.userId}/Items/Resume?mediaTypes=Video&enableUserData=true&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber,UserData`),
jellyfinFetch<JellyfinItem[]>(config, `/Shows/NextUp?userId=${config.jellyfin.userId}&enableUserData=true&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber,UserData`),
jellyfinFetch<JellyfinItem[]>(
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<ReturnType<typeof getLibrarySnapshot>>
): 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')
}
]
};
}
+33
View File
@@ -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 {
+288 -23
View File
@@ -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<DownloadItem[]>([])
const [processingItems, setProcessingItems] = useState<ProcessingItem[]>([])
const [completedDownloads, setCompletedDownloads] = useState<CompletedDownloadItem[]>([])
const [connections, setConnections] = useState<ConnectionStatus[]>([])
const [hubPages, setHubPages] = useState<Partial<Record<HubPageResponse['page'], HubPageResponse>>>({})
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() {
</div>
{route === 'calendar' ? <CalendarPage onOpenCard={(card, originRect) => setSelectedCard({ card, originRect: originRect ?? null })} /> : null}
{route === 'downloads' ? <DownloadsPage busyId={downloadDeleteId} downloads={downloads} onDelete={handleDeleteDownload} /> : null}
{route === 'downloads' ? <DownloadsPage busyId={downloadDeleteId} completedDownloads={completedDownloads} downloads={downloads} onDelete={handleDeleteDownload} onDismissAllCompleted={handleDismissAllCompleted} onDismissCompleted={handleDismissCompleted} processingItems={processingItems} /> : null}
{route === 'search' ? (
<SearchPage
loading={searchLoading}
@@ -508,6 +539,7 @@ function App() {
onClose={() => setSelectedCard(null)}
originRect={selectedCard.originRect}
onRequest={handleRequest}
currentUser={currentJellyfinUser}
/>
) : null}
</div>
@@ -909,12 +941,34 @@ function HubPageView(props: {
<SectionCarousel busy={props.busy} onOpenCard={props.onOpenCard} onRequest={props.onRequest} section={{ id: 'continue', title: 'Continue Watching', style: 'episode', items: props.hub.continueWatching }} />
) : null}
{props.hub.sections.map((section) => (
<SectionCarousel busy={props.busy} key={section.id} onOpenCard={props.onOpenCard} onRequest={props.onRequest} section={section} />
section.id === 'library-movies' || section.id === 'library-series'
? <LibraryGrid busy={props.busy} key={section.id} onOpenCard={props.onOpenCard} onRequest={props.onRequest} section={section} />
: <SectionCarousel busy={props.busy} key={section.id} onOpenCard={props.onOpenCard} onRequest={props.onRequest} section={section} />
))}
</div>
)
}
function LibraryGrid(props: {
section: HubPageResponse['sections'][number]
onRequest: (card: MediaCard) => Promise<void>
onOpenCard: (card: MediaCard, originRect?: ModalOriginRect | null) => void
busy: boolean
}) {
if (!props.section.items.length) return null
return (
<section className="library-grid-section">
<div className="carousel-title">{props.section.title}</div>
<div className="carousel-section library-grid">
{props.section.items.map((card) => (
<MediaTile busy={props.busy} card={card} isContinueWatching={false} key={card.id} onOpenCard={props.onOpenCard} onRequest={props.onRequest} styleType="landscape" />
))}
</div>
</section>
)
}
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<void>
currentUser: string | null
}) {
const [details, setDetails] = useState<TitleDetailsResponse | null>(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 (
<section className="downloads-section">
<button
className="downloads-section-header"
onClick={() => setIsCollapsed(!isCollapsed)}
type="button"
>
<h2>{props.title} ({props.count})</h2>
<span className={isCollapsed ? 'collapse-arrow' : 'collapse-arrow expanded'}>
<svg viewBox="0 0 16 16" fill="none" >
<path d="M4 6L8 10L12 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
</button>
{!isCollapsed && <div className="downloads-grid">{props.children}</div>}
</section>
)
}
function ProcessingCard(props: {
item: ProcessingItem,
onCancel: (id: string) => void
}) {
return (
<div className="download-card processing-card">
{props.item.backdropUrl && <img src={props.item.backdropUrl} className="download-card-backdrop" alt="" />}
<div className="download-card-overlay" />
<div className="download-card-content">
<div className="download-card-spinner">
<div className="loading-orb" />
</div>
<div className="download-card-info">
<h3>{props.item.title}</h3>
<p>{props.item.subtitle}</p>
<p className="download-card-user">Requested by: {props.item.user}</p>
</div>
<button
className="download-card-cancel"
onClick={() => props.onCancel(props.item.id)}
type="button"
>
×
</button>
</div>
</div>
)
}
function DownloadingCard(props: {
item: DownloadItem,
onCancel: (id: string) => void
}) {
return (
<div className="download-card downloading-card">
{props.item.backdropUrl && <img src={props.item.backdropUrl} className="download-card-backdrop" alt="" />}
<div className="download-card-overlay" />
<div className="download-card-content">
<div className="download-card-info">
<h3>{props.item.title}</h3>
<p>{props.item.subtitle}</p>
</div>
<button
className="download-card-cancel"
onClick={() => props.onCancel(props.item.id)}
type="button"
>
×
</button>
</div>
<div className="download-card-progress">
<div className="download-card-progress-bar" style={{ width: `${props.item.progress}%` }} />
</div>
<p className="download-card-details">{props.item.size} @ {props.item.eta}</p>
</div>
)
}
function CompletedCard(props: {
item: CompletedDownloadItem,
onDismiss: (id: string) => void
}) {
return (
<div className="download-card completed-card">
{props.item.backdropUrl && <img src={props.item.backdropUrl} className="download-card-backdrop" alt="" />}
<div className="download-card-overlay" />
<div className="download-card-content">
<div className="download-card-info">
<h3>{props.item.title}</h3>
<p>{props.item.subtitle}</p>
<p className="download-card-completed-badge">Completed</p>
</div>
<button
className="download-card-cancel"
onClick={() => props.onDismiss(props.item.id)}
type="button"
>
×
</button>
</div>
</div>
)
}
function DownloadsPage(props: {
downloads: DownloadItem[]
processingItems: ProcessingItem[]
completedDownloads: CompletedDownloadItem[]
busyId: string
onDelete: (id: string) => Promise<void>
onDismissCompleted: (id: string) => void
onDismissAllCompleted: () => void
}) {
const hasAny = props.processingItems.length > 0 || props.downloads.length > 0 || props.completedDownloads.length > 0
return (
<div className="downloads-page">
<div className="downloads-header">
<h2><DownloadGlyph /> <span>Downloads</span></h2>
</div>
<section className="downloads-section">
<div className="downloads-grid">
{props.downloads.length
? props.downloads.map((item) => (
<DownloadRow
busy={props.busyId === item.id}
item={item}
key={item.id}
onDelete={props.onDelete}
/>
))
: <EmptyState copy="The queue will appear here as soon as your services start working." title="No active downloads" />}
</div>
</section>
{props.processingItems.length > 0 ? (
<section className="downloads-section">
<h3 className="downloads-section-title">Processing</h3>
<div className="downloads-grid">
{props.processingItems.map((item) => (
<article className="download-row download-row-processing" key={item.id}>
<div className="download-card">
<div className="download-artwork">
{item.posterUrl || item.backdropUrl
? <img alt={item.title} loading="lazy" src={item.backdropUrl || item.posterUrl} />
: <div className="media-fallback download-poster-fallback">{item.title.slice(0, 1).toUpperCase()}</div>}
</div>
<div className="download-copy">
<h4>{item.title}</h4>
{item.subtitle ? <p className="download-subtitle">{item.subtitle}</p> : null}
<p className="download-detail download-processing-label">
<span className="download-processing-spinner" aria-hidden="true" />
Searching…
</p>
</div>
</div>
<div className="download-side">
<div className="download-progress-panel">
<div className="download-progress-header">
<span className="download-processing-badge">Processing</span>
</div>
</div>
</div>
</article>
))}
</div>
</section>
) : null}
{props.downloads.length > 0 ? (
<section className="downloads-section">
<h3 className="downloads-section-title">Downloading</h3>
<div className="downloads-grid">
{props.downloads.map((item) => (
<DownloadRow
busy={props.busyId === item.id}
item={item}
key={item.id}
onDelete={props.onDelete}
/>
))}
</div>
</section>
) : null}
{props.completedDownloads.length > 0 ? (
<section className="downloads-section">
<div className="downloads-section-header">
<h3 className="downloads-section-title">Completed</h3>
<button className="downloads-dismiss-all-button" onClick={props.onDismissAllCompleted} type="button">
Dismiss all
</button>
</div>
<div className="downloads-grid">
{props.completedDownloads.map((item) => (
<article className="download-row download-row-completed" key={item.id}>
<div className="download-card">
<div className="download-artwork">
{item.posterUrl || item.backdropUrl
? <img alt={item.title} loading="lazy" src={item.backdropUrl || item.posterUrl} />
: <div className="media-fallback download-poster-fallback">{item.title.slice(0, 1).toUpperCase()}</div>}
</div>
<div className="download-copy">
<h4>{item.title}</h4>
{item.subtitle ? <p className="download-subtitle">{item.subtitle}</p> : null}
<p className="download-detail download-completed-label">Download completed</p>
</div>
</div>
<div className="download-side">
<div className="download-progress-panel">
<div className="download-progress-header">
<strong className="download-completed-badge">100%</strong>
<span>Completed</span>
</div>
<div className="download-progress-row">
<div className="download-progress-bar download-progress-complete">
<div className="download-progress-fill" style={{ width: '100%' }} />
</div>
<button
aria-label={`Dismiss ${item.title}`}
className="download-action-button download-delete-button"
onClick={() => props.onDismissCompleted(item.id)}
type="button"
>
×
</button>
</div>
</div>
</div>
</article>
))}
</div>
</section>
) : null}
{!hasAny ? (
<section className="downloads-section">
<div className="downloads-grid">
<EmptyState copy="The queue will appear here as soon as your services start working." title="No active downloads" />
</div>
</section>
) : null}
</div>
)
}
+19 -9
View File
@@ -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<DownloadItem[]>('/api/downloads'),
getDownloads: () => request<DownloadsResponse>('/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', {
+88 -1
View File
@@ -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;
}