From 79c8072318b82256cdd2275e9b8ea2bc55551c8e Mon Sep 17 00:00:00 2001 From: WonderAliceUwU Date: Wed, 8 Jul 2026 12:16:27 +0200 Subject: [PATCH] feature: add per chapter download --- server/index.ts | 10 ++++ server/lib/services.ts | 63 +++++++++++++++++++- shared/contracts.ts | 7 +++ src/App.tsx | 127 +++++++++++++++++++++++++++++++++++------ src/api.ts | 6 ++ src/index.css | 100 +++++++++++++++++++++++++++----- 6 files changed, 278 insertions(+), 35 deletions(-) diff --git a/server/index.ts b/server/index.ts index 020d792..c6dc7d5 100644 --- a/server/index.ts +++ b/server/index.ts @@ -5,6 +5,7 @@ import { defaultConfig, type AppConfig, type AuthPayload, + type EpisodeRequestPayload, type EpisodeWatchStateRequest, type SeasonDeletePayload, type SeasonRequestPayload, @@ -24,6 +25,7 @@ import { loadJellyfinUsers, proxyJellyfinImage, removeDownload, + requestEpisode, requestMovie, requestSeason, requestSeries, @@ -275,6 +277,14 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/requests/episode' && method === 'POST') { + const config = await readConfig(session!.encryptionKey); + const body = await readJson(request); + await requestEpisode(config, body); + sendJson(response, 200, { ok: true }); + return; + } + if (url.pathname === '/api/seasons/delete' && method === 'POST') { const config = await readConfig(session!.encryptionKey); const body = await readJson(request); diff --git a/server/lib/services.ts b/server/lib/services.ts index 0d3d282..b6bc207 100644 --- a/server/lib/services.ts +++ b/server/lib/services.ts @@ -3,6 +3,7 @@ import type { ConnectionStatus, DashboardResponse, DownloadItem, + EpisodeRequestPayload, EpisodeWatchStateRequest, HubPageResponse, HubSection, @@ -1111,11 +1112,13 @@ async function buildSeasonEpisodes( const tmdbEpisode = tmdbByEpisodeNumber.get(episodeNumber); const jellyfinEpisode = jellyfinByEpisodeNumber.get(episodeNumber); const sonarrEpisode = sonarrByEpisodeNumber.get(episodeNumber); + const queueEntry = sonarrQueue.find((entry) => entry.episode?.seasonNumber === seasonNumber && entry.episode?.episodeNumber === episodeNumber); const airDate = tmdbEpisode?.air_date || sonarrEpisode?.airDateUtc; const isReleased = !airDate || new Date(airDate).getTime() <= Date.now(); const hasFile = Boolean(sonarrEpisode?.hasFile || sonarrEpisode?.episodeFileId); const isAvailableInJellyfin = Boolean(jellyfinEpisode?.id); const isDownloading = downloadingEpisodes.has(episodeNumber); + const isProcessing = Boolean(sonarrEpisode?.id) && !isDownloading && Boolean(sonarrEpisode?.monitored) && availabilityWouldBeMissing(isReleased, isAvailableInJellyfin, hasFile); const availability: TitleDetailsEpisode['availability'] = !isReleased ? 'unaired' : isAvailableInJellyfin || hasFile @@ -1123,9 +1126,15 @@ async function buildSeasonEpisodes( : isDownloading ? 'downloading' : 'missing'; + const downloadStatus: TitleDetailsEpisode['downloadStatus'] = isDownloading + ? 'downloading' + : isProcessing + ? 'processing' + : 'idle'; return { id: jellyfinEpisode?.id || buildEpisodeId(seasonNumber, episodeNumber), + sonarrEpisodeId: sonarrEpisode?.id, seasonId: season.id, title: jellyfinEpisode?.title || sonarrEpisode?.title || tmdbEpisode?.name || `Episode ${episodeNumber}`, overview: jellyfinEpisode?.overview || sonarrEpisode?.overview || tmdbEpisode?.overview || '', @@ -1140,6 +1149,8 @@ async function buildSeasonEpisodes( runtimeMinutes: jellyfinEpisode?.runtimeMinutes || tmdbEpisode?.runtime, availableInJellyfin: isAvailableInJellyfin, availability, + downloadStatus, + downloadProgress: isDownloading ? getEpisodeQueueProgress(queueEntry) : undefined, canDownload: isManagedInSonarr && availability === 'missing', canDelete: hasFile, watched: jellyfinEpisode?.watched, @@ -1149,6 +1160,29 @@ async function buildSeasonEpisodes( }); } +function availabilityWouldBeMissing( + isReleased: boolean, + isAvailableInJellyfin: boolean, + hasFile: boolean +) { + return isReleased && !isAvailableInJellyfin && !hasFile; +} + +function getEpisodeQueueProgress(entry: SonarrQueueRecord | undefined): number | undefined { + if (!entry) { + return undefined; + } + + const total = Number(entry.size || 0); + const left = Number(entry.sizeleft || 0); + if (!total || total <= 0) { + return undefined; + } + + const percent = Math.round(((total - left) / total) * 100); + return Math.max(0, Math.min(100, percent)); +} + function buildTitleSeasons( seasons: SeriesSeasonDescriptor[], allEpisodes: TitleDetailsEpisode[], @@ -1177,7 +1211,9 @@ function buildTitleSeasons( ? Math.max(season.episodeCount - availableEpisodeCount, 0) : undefined, canDownload: false, - canDelete: availableEpisodeCount > 0, + canDelete: typeof season.episodeCount === 'number' + ? availableEpisodeCount >= season.episodeCount + : availableEpisodeCount > 0, isDownloading, downloadStatus: isDownloading ? 'downloading' : isProcessing ? 'processing' : 'idle', downloadProgress: isDownloading ? getSeasonQueueProgress(seasonQueue) : undefined, @@ -1202,7 +1238,7 @@ function buildTitleSeasons( availableEpisodeCount: seasonEpisodes.filter((episode) => episode.availability === 'available').length, missingEpisodeCount: seasonEpisodes.filter((episode) => episode.availability === 'missing').length, canDownload: seasonEpisodes.some((episode) => episode.canDownload), - canDelete: seasonEpisodes.some((episode) => episode.canDelete), + canDelete: seasonEpisodes.length > 0 && seasonEpisodes.every((episode) => episode.canDelete), isDownloading: current.isDownloading || seasonEpisodes.some((episode) => episode.availability === 'downloading') }); } @@ -1412,6 +1448,28 @@ export async function requestSeason(config: AppConfig, payload: SeasonRequestPay }); } +export async function requestEpisode(config: AppConfig, payload: EpisodeRequestPayload): Promise { + if (!config.sonarr.baseUrl || !config.sonarr.apiKey) { + throw new Error('Sonarr is not configured.'); + } + + if (!payload.episodeId) { + throw new Error('Episode id is required.'); + } + + await fetchJson(`${config.sonarr.baseUrl}/api/v3/command`, { + method: 'POST', + headers: { + 'X-Api-Key': config.sonarr.apiKey, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + name: 'EpisodeSearch', + episodeIds: [payload.episodeId] + }) + }); +} + export async function deleteSeasonFiles(config: AppConfig, payload: SeasonDeletePayload): Promise { if (!config.sonarr.baseUrl || !config.sonarr.apiKey) { throw new Error('Sonarr is not configured.'); @@ -2392,6 +2450,7 @@ async function fetchJson(url: string, init?: RequestInit): Promise { } } + function jellyfinToCard( item: JellyfinItem, fallbackTitle: string, diff --git a/shared/contracts.ts b/shared/contracts.ts index 023e0ff..3d4e2ac 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -109,6 +109,7 @@ export interface MediaCard { export interface TitleDetailsEpisode { id: string; + sonarrEpisodeId?: number; seasonId?: string; title: string; overview: string; @@ -120,6 +121,8 @@ export interface TitleDetailsEpisode { runtimeMinutes?: number; availableInJellyfin?: boolean; availability?: 'available' | 'downloading' | 'missing' | 'unaired'; + downloadStatus?: 'idle' | 'processing' | 'downloading'; + downloadProgress?: number; canDownload?: boolean; canDelete?: boolean; watched?: boolean; @@ -211,6 +214,10 @@ export interface SeasonRequestPayload { seasonNumber: number; } +export interface EpisodeRequestPayload { + episodeId: number; +} + export interface SeasonDeletePayload { seriesId: number; seasonNumber: number; diff --git a/src/App.tsx b/src/App.tsx index e783e41..2c1d22f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -574,7 +574,6 @@ function AuthScreen({
-

{isSetup ? 'First boot' : 'Secure access'}

{isSetup ? 'Create your master password' : 'Sign in to OmniArr'}

{isSetup @@ -1048,6 +1047,7 @@ function TitleDetailsModal(props: { const [detailsError, setDetailsError] = useState('') const [activeSeasonId, setActiveSeasonId] = useState(undefined) const [episodeWatchBusyId, setEpisodeWatchBusyId] = useState(null) + const [episodeDownloadBusyId, setEpisodeDownloadBusyId] = useState(null) const [seasonActionBusy, setSeasonActionBusy] = useState<'download' | 'delete' | null>(null) const [playerTarget, setPlayerTarget] = useState<{ id: string; title: string } | null>(null) const [isOverviewExpanded, setIsOverviewExpanded] = useState(false) @@ -1110,6 +1110,7 @@ function TitleDetailsModal(props: { setDetailsError('') setActiveSeasonId(undefined) setEpisodeWatchBusyId(null) + setEpisodeDownloadBusyId(null) setSeasonActionBusy(null) setPlayerTarget(null) setIsOverviewExpanded(false) @@ -1340,6 +1341,28 @@ function TitleDetailsModal(props: { } }, [activeSeasonDownloadStatus, details, 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, seasonValue]) + function handleRequestClose() { if (!props.originRect || transitionState === 'closing') { props.onClose() @@ -1466,6 +1489,42 @@ function TitleDetailsModal(props: { } } + 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 + } + + setEpisodeDownloadBusyId(episodeId) + updateEpisodeInCaches(episodeId, (episode) => ({ + ...episode, + downloadStatus: 'processing', + downloadProgress: undefined, + canDownload: false, + })) + + void api.requestEpisode({ episodeId: sonarrEpisodeId }) + .catch(() => { + updateEpisodeInCaches(episodeId, (episode) => ({ + ...episode, + availability, + downloadStatus: 'idle', + downloadProgress: undefined, + canDownload: availability === 'missing', + })) + }) + .finally(() => { + setEpisodeDownloadBusyId((current) => current === episodeId ? null : current) + }) + } + return (

-
-
- ) : activeSeasonDownloadStatus === 'processing' ? ( + className="title-season-progress" + role="img" + title={activeSeasonMeta?.downloadLabel || 'Downloading'} + > + + {`${activeSeasonMeta?.downloadProgress || 0}%`} +
+ ) : activeSeasonDownloadStatus === 'processing' ? (
{episode.title}
- {episode.canDownload || episode.availability === 'downloading' ? ( + {episode.canDownload || episode.downloadStatus === 'processing' || episode.downloadStatus === 'downloading' ? ( + episode.downloadStatus === 'downloading' ? ( + + {`${episode.downloadProgress || 0}%`} + + ) : episode.downloadStatus === 'processing' ? ( + + + ) : ( + + ) + ) : null} {episode.availableInJellyfin ? (