diff --git a/cypress/config/settings.cypress.json b/cypress/config/settings.cypress.json index f485424fcc..5d7dd37029 100644 --- a/cypress/config/settings.cypress.json +++ b/cypress/config/settings.cypress.json @@ -25,6 +25,7 @@ "mediaServerType": 1, "partialRequestsEnabled": true, "enableSpecialEpisodes": false, + "enableEpisodeAvailability": false, "locale": "en" }, "plex": { diff --git a/seerr-api.yml b/seerr-api.yml index ae1fdc254f..3542b55409 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -253,6 +253,9 @@ components: enableSpecialEpisodes: type: boolean example: false + enableEpisodeAvailability: + type: boolean + example: false versionCheck: type: boolean example: false @@ -1075,6 +1078,10 @@ components: type: number voteCount: type: number + available: + type: boolean + available4k: + type: boolean Season: type: object properties: diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts index 29679d0e51..36c5577b04 100644 --- a/server/api/servarr/sonarr.ts +++ b/server/api/servarr/sonarr.ts @@ -14,7 +14,7 @@ export interface SonarrSeason { percentOfEpisodes: number; }; } -interface EpisodeResult { +export interface EpisodeResult { seriesId: number; episodeFileId: number; seasonNumber: number; diff --git a/server/datasource.ts b/server/datasource.ts index a87920f839..0f59275064 100644 --- a/server/datasource.ts +++ b/server/datasource.ts @@ -1,5 +1,6 @@ import { Blocklist } from '@server/entity/Blocklist'; import DiscoverSlider from '@server/entity/DiscoverSlider'; +import Episode from '@server/entity/Episode'; import Issue from '@server/entity/Issue'; import IssueComment from '@server/entity/IssueComment'; import Media from '@server/entity/Media'; @@ -27,6 +28,7 @@ const DB_SSL_PREFIX = 'DB_SSL_'; const entities = [ Blocklist, DiscoverSlider, + Episode, Issue, IssueComment, Media, diff --git a/server/entity/Episode.ts b/server/entity/Episode.ts new file mode 100644 index 0000000000..4db99eaadd --- /dev/null +++ b/server/entity/Episode.ts @@ -0,0 +1,51 @@ +import { MediaStatus } from '@server/constants/media'; +import { DbAwareColumn, resolveDbType } from '@server/utils/DbColumnHelper'; +import { + Column, + Entity, + Index, + ManyToOne, + PrimaryGeneratedColumn, + Unique, + UpdateDateColumn, +} from 'typeorm'; +import Season from './Season'; + +@Entity() +@Unique(['season', 'episodeNumber']) +class Episode { + @PrimaryGeneratedColumn() + public id: number; + + @Column() + public episodeNumber: number; + + @Column({ type: 'int', default: MediaStatus.UNKNOWN }) + public status: MediaStatus; + + @Column({ type: 'int', default: MediaStatus.UNKNOWN }) + public status4k: MediaStatus; + + @Index() + @ManyToOne(() => Season, (season: Season) => season.episodes, { + onDelete: 'CASCADE', + }) + public season: Promise; + + @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) + public createdAt: Date; + + @UpdateDateColumn({ + type: resolveDbType('datetime'), + default: () => 'CURRENT_TIMESTAMP', + }) + public updatedAt: Date; + + constructor(init?: Partial) { + if (init) { + Object.assign(this, init); + } + } +} + +export default Episode; diff --git a/server/entity/Season.ts b/server/entity/Season.ts index f1e5a11d3e..d45de8a9a0 100644 --- a/server/entity/Season.ts +++ b/server/entity/Season.ts @@ -5,9 +5,11 @@ import { Entity, Index, ManyToOne, + OneToMany, PrimaryGeneratedColumn, UpdateDateColumn, } from 'typeorm'; +import Episode from './Episode'; import Media from './Media'; @Entity() @@ -30,6 +32,11 @@ class Season { @Index() public media: Promise; + @OneToMany(() => Episode, (episode) => episode.season, { + cascade: true, + }) + public episodes?: Episode[]; + @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) public createdAt: Date; diff --git a/server/lib/availabilitySync.test.ts b/server/lib/availabilitySync.test.ts index 7e861e38c5..c2b0a6a109 100644 --- a/server/lib/availabilitySync.test.ts +++ b/server/lib/availabilitySync.test.ts @@ -10,7 +10,11 @@ import type { PlexMetadata } from '@server/api/plexapi'; import PlexAPI from '@server/api/plexapi'; import type { RadarrMovie } from '@server/api/servarr/radarr'; import RadarrAPI from '@server/api/servarr/radarr'; -import type { SonarrSeason, SonarrSeries } from '@server/api/servarr/sonarr'; +import type { + EpisodeResult, + SonarrSeason, + SonarrSeries, +} from '@server/api/servarr/sonarr'; import SonarrAPI from '@server/api/servarr/sonarr'; import TheMovieDb from '@server/api/themoviedb'; import type { @@ -24,13 +28,14 @@ import { } from '@server/constants/media'; import { MediaServerType } from '@server/constants/server'; import { getRepository } from '@server/datasource'; +import Episode from '@server/entity/Episode'; import Media from '@server/entity/Media'; import MediaRequest from '@server/entity/MediaRequest'; import Season from '@server/entity/Season'; import { User } from '@server/entity/User'; import availabilitySync from '@server/lib/availabilitySync'; import type { RadarrSettings, SonarrSettings } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import { setupTestDb } from '@server/test/db'; // --- Mock JellyfinAPI --- @@ -121,6 +126,9 @@ Object.defineProperty(PlexAPI.prototype, 'getChildrenMetadata', { let getSeriesByIdImpl: (id: number) => Promise = async () => { throw new Error('404'); }; +let getSonarrEpisodesImpl: ( + seriesId: number +) => Promise = async () => []; Object.defineProperty(SonarrAPI.prototype, 'getSeriesById', { get() { @@ -130,6 +138,14 @@ Object.defineProperty(SonarrAPI.prototype, 'getSeriesById', { configurable: true, }); +Object.defineProperty(SonarrAPI.prototype, 'getEpisodes', { + get() { + return async (seriesId: number) => getSonarrEpisodesImpl(seriesId); + }, + set() {}, + configurable: true, +}); + // --- Mock RadarrAPI --- let getMovieImpl: (id: number) => Promise = async () => { throw new Error('404'); @@ -442,9 +458,16 @@ describe('AvailabilitySync', () => { getSeriesByIdImpl = async () => { throw new Error('404'); }; + getSonarrEpisodesImpl = async () => []; getMovieImpl = async () => { throw new Error('404'); }; + const settings = getSettings(); + settings.main.enableEpisodeAvailability = false; + settings.metadataSettings = { + tv: MetadataProviderType.TMDB, + anime: MetadataProviderType.TMDB, + }; getTvShowImpl = async ({ tvId }) => fakeTmdbShow( tvId, @@ -2315,4 +2338,409 @@ describe('AvailabilitySync', () => { ); }); }); + + describe('TV episode availability - Sonarr', () => { + function enableEpisodeTracking(): void { + const settings = getSettings(); + settings.main.enableEpisodeAvailability = true; + settings.metadataSettings = { + tv: MetadataProviderType.TVDB, + anime: MetadataProviderType.TMDB, + }; + } + + it('should mark AVAILABLE episodes DELETED when a season is removed even if Sonarr episode fetch fails', async () => { + configurePlex(); + configureSonarr([{ syncEnabled: true }]); + enableEpisodeTracking(); + + const mediaRepository = getRepository(Media); + const episodeRepository = getRepository(Episode); + + const media = new Media(); + media.tmdbId = 4101; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-ep-sync-rk'; + media.externalServiceId = 410; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + new Season({ + seasonNumber: 2, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + + const saved = await mediaRepository.save(media); + const season1 = saved.seasons.find((season) => season.seasonNumber === 1); + const season2 = saved.seasons.find((season) => season.seasonNumber === 2); + assert.ok(season1); + assert.ok(season2); + + await episodeRepository.save([ + new Episode({ + episodeNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season1), + }), + new Episode({ + episodeNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season2), + }), + ]); + + getTvShowImpl = async () => + fakeTmdbShow(4101, [ + { + id: 1, + air_date: '2024-01-01', + episode_count: 1, + name: 'Season 1', + overview: '', + season_number: 1, + }, + { + id: 2, + air_date: '2024-01-01', + episode_count: 1, + name: 'Season 2', + overview: '', + season_number: 2, + }, + ]); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-ep-sync-rk') { + return fakePlexShow('plex-ep-sync-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-ep-sync-rk') { + return [fakePlexSeason(2, 'plex-ep-sync-s2-rk')]; + } + if (key === 'plex-ep-sync-s2-rk') { + return fakePlexEpisodes(1); + } + return []; + }; + + getSeriesByIdImpl = async (id: number) => { + if (id === 410) { + return { + tvdbId: 4101, + id: 410, + title: 'Test Show', + titleSlug: 'test-show', + monitored: true, + statistics: { + episodeFileCount: 1, + totalEpisodeCount: 2, + episodeCount: 2, + percentOfEpisodes: 50, + sizeOnDisk: 0, + seasonCount: 2, + }, + seasons: fakeSonarrSeasons(2, { 2: 1 }), + } as unknown as SonarrSeries; + } + throw new Error('404'); + }; + + getSonarrEpisodesImpl = async () => { + throw new Error('Sonarr episode fetch failed'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 4101 }, + relations: ['seasons'], + }); + const updatedSeason1 = updated.seasons.find( + (season) => season.seasonNumber === 1 + ); + const updatedSeason2 = updated.seasons.find( + (season) => season.seasonNumber === 2 + ); + assert.ok(updatedSeason1); + assert.ok(updatedSeason2); + assert.strictEqual(updatedSeason1.status, MediaStatus.DELETED); + assert.strictEqual(updatedSeason2.status, MediaStatus.AVAILABLE); + + const season1Episodes = await episodeRepository.find({ + where: { season: { id: updatedSeason1.id } }, + }); + const season2Episodes = await episodeRepository.find({ + where: { season: { id: updatedSeason2.id } }, + }); + + assert.strictEqual(season1Episodes[0]?.status, MediaStatus.DELETED); + assert.strictEqual(season2Episodes[0]?.status, MediaStatus.AVAILABLE); + }); + + it('should soft-delete episodes without a file and hard-delete omitted numbers', async () => { + configurePlex(); + configureSonarr([{ syncEnabled: true }]); + enableEpisodeTracking(); + + const mediaRepository = getRepository(Media); + const episodeRepository = getRepository(Episode); + + const media = new Media(); + media.tmdbId = 4102; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-ep-file-rk'; + media.externalServiceId = 411; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + + const saved = await mediaRepository.save(media); + const season1 = saved.seasons.find((season) => season.seasonNumber === 1); + assert.ok(season1); + + await episodeRepository.save([ + new Episode({ + episodeNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season1), + }), + new Episode({ + episodeNumber: 2, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season1), + }), + new Episode({ + episodeNumber: 3, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season1), + }), + ]); + + getTvShowImpl = async () => + fakeTmdbShow(4102, [ + { + id: 1, + air_date: '2024-01-01', + episode_count: 2, + name: 'Season 1', + overview: '', + season_number: 1, + }, + ]); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-ep-file-rk') { + return fakePlexShow('plex-ep-file-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-ep-file-rk') { + return [fakePlexSeason(1, 'plex-ep-file-s1-rk')]; + } + if (key === 'plex-ep-file-s1-rk') { + return fakePlexEpisodes(2); + } + return []; + }; + + getSeriesByIdImpl = async (id: number) => { + if (id === 411) { + return { + tvdbId: 4102, + id: 411, + title: 'Test Show', + titleSlug: 'test-show', + monitored: true, + statistics: { + episodeFileCount: 1, + totalEpisodeCount: 2, + episodeCount: 2, + percentOfEpisodes: 50, + sizeOnDisk: 0, + seasonCount: 1, + }, + seasons: fakeSonarrSeasons(1, { 1: 1 }), + } as unknown as SonarrSeries; + } + throw new Error('404'); + }; + + getSonarrEpisodesImpl = async () => + [ + { + seriesId: 411, + seasonNumber: 1, + episodeNumber: 1, + hasFile: true, + }, + { + seriesId: 411, + seasonNumber: 1, + episodeNumber: 2, + hasFile: false, + }, + ] as EpisodeResult[]; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 4102 }, + relations: ['seasons'], + }); + const updatedSeason = updated.seasons[0]; + assert.ok(updatedSeason); + assert.strictEqual(updatedSeason.status, MediaStatus.AVAILABLE); + + const episodes = await episodeRepository.find({ + where: { season: { id: updatedSeason.id } }, + order: { episodeNumber: 'ASC' }, + }); + + assert.strictEqual(episodes.length, 2); + assert.strictEqual(episodes[0]?.episodeNumber, 1); + assert.strictEqual(episodes[0]?.status, MediaStatus.AVAILABLE); + assert.strictEqual(episodes[1]?.episodeNumber, 2); + assert.strictEqual(episodes[1]?.status, MediaStatus.DELETED); + }); + + it('should still mark Sonarr episodes DELETED when TMDB show lookup fails', async () => { + configurePlex(); + configureSonarr([{ syncEnabled: true }]); + enableEpisodeTracking(); + + const mediaRepository = getRepository(Media); + const episodeRepository = getRepository(Episode); + + const media = new Media(); + media.tmdbId = 4103; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-ep-tmdb-fail-rk'; + media.externalServiceId = 412; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + + const saved = await mediaRepository.save(media); + const season1 = saved.seasons.find((season) => season.seasonNumber === 1); + assert.ok(season1); + + await episodeRepository.save([ + new Episode({ + episodeNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season1), + }), + new Episode({ + episodeNumber: 2, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + season: Promise.resolve(season1), + }), + ]); + + getTvShowImpl = async () => { + throw new Error('TMDB unavailable'); + }; + + getMetadataImpl = async (key: string) => { + if (key === 'plex-ep-tmdb-fail-rk') { + return fakePlexShow('plex-ep-tmdb-fail-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-ep-tmdb-fail-rk') { + return [fakePlexSeason(1, 'plex-ep-tmdb-fail-s1-rk')]; + } + if (key === 'plex-ep-tmdb-fail-s1-rk') { + return fakePlexEpisodes(2); + } + return []; + }; + + getSeriesByIdImpl = async (id: number) => { + if (id === 412) { + return { + tvdbId: 4103, + id: 412, + title: 'Test Show', + titleSlug: 'test-show', + monitored: true, + statistics: { + episodeFileCount: 1, + totalEpisodeCount: 2, + episodeCount: 2, + percentOfEpisodes: 50, + sizeOnDisk: 0, + seasonCount: 1, + }, + seasons: fakeSonarrSeasons(1, { 1: 1 }), + } as unknown as SonarrSeries; + } + throw new Error('404'); + }; + + getSonarrEpisodesImpl = async () => + [ + { + seriesId: 412, + seasonNumber: 1, + episodeNumber: 1, + hasFile: true, + }, + { + seriesId: 412, + seasonNumber: 1, + episodeNumber: 2, + hasFile: false, + }, + ] as EpisodeResult[]; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 4103 }, + relations: ['seasons'], + }); + const updatedSeason = updated.seasons[0]; + assert.ok(updatedSeason); + assert.strictEqual(updatedSeason.status, MediaStatus.AVAILABLE); + + const episodes = await episodeRepository.find({ + where: { season: { id: updatedSeason.id } }, + order: { episodeNumber: 'ASC' }, + }); + + assert.strictEqual(episodes[0]?.status, MediaStatus.AVAILABLE); + assert.strictEqual(episodes[1]?.status, MediaStatus.DELETED); + }); + }); }); diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 4a700ef355..819085f11c 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -6,6 +6,7 @@ import RadarrAPI, { type RadarrMovie } from '@server/api/servarr/radarr'; import type { SonarrSeason, SonarrSeries } from '@server/api/servarr/sonarr'; import SonarrAPI from '@server/api/servarr/sonarr'; import TheMovieDb from '@server/api/themoviedb'; +import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants'; import type { TmdbTvDetails, TmdbTvScanDetails, @@ -13,14 +14,22 @@ import type { import { MediaRequestStatus, MediaStatus } from '@server/constants/media'; import { MediaServerType } from '@server/constants/server'; import { getRepository } from '@server/datasource'; +import Episode from '@server/entity/Episode'; import Media from '@server/entity/Media'; import MediaRequest from '@server/entity/MediaRequest'; import type Season from '@server/entity/Season'; import { User } from '@server/entity/User'; import type { RadarrSettings, SonarrSettings } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import { getHostname } from '@server/utils/getHostname'; +import { In } from 'typeorm'; + +type CachedSonarrEpisode = { + seasonNumber: number; + episodeNumber: number; + hasFile: boolean; +}; class AvailabilitySync { public running = false; @@ -33,6 +42,7 @@ class AvailabilitySync { private jellyfinEpisodeExistsCache: Record; private sonarrSeasonsCache: Record; + private sonarrEpisodesCache: Record; private radarrServers: RadarrSettings[]; private sonarrServers: SonarrSettings[]; private enable4kMovie: boolean; @@ -49,10 +59,12 @@ class AvailabilitySync { this.jellyfinSeasonsCache = {}; this.jellyfinEpisodeExistsCache = {}; this.sonarrSeasonsCache = {}; + this.sonarrEpisodesCache = {}; this.radarrServers = settings.radarr; this.sonarrServers = settings.sonarr; this.enable4kMovie = this.radarrServers.some((server) => server.is4k); this.enable4kShow = this.sonarrServers.some((server) => server.is4k); + const episodeTrackingEnabled = settings.main.enableEpisodeAvailability; try { logger.info(`Starting availability sync...`, { @@ -227,8 +239,36 @@ class AvailabilitySync { let showExists = false; let showExists4k = false; + // We need to fetch from TMDB for anime detection and season enrichment + let tvShow: TmdbTvScanDetails | TmdbTvDetails | undefined; + try { + if (media.tmdbId) { + tvShow = await this.tmdb.getTvShowForScan({ + tvId: Number(media.tmdbId), + }); + } else if (media.tvdbId) { + tvShow = await this.tmdb.getShowByTvdbIdForScan({ + tvdbId: Number(media.tvdbId), + }); + } + } catch (e) { + logger.debug( + `Failed to fetch TMDB data for show [TMDB ID ${media.tmdbId}]. Skipping season enrichment.`, + { label: 'AvailabilitySync', errorMessage: e.message } + ); + } + //plex + const isAnime = !!tvShow?.keywords.results.some( + (keyword) => keyword.id === ANIME_KEYWORD_ID + ); + const shouldTrackEpisodes = + episodeTrackingEnabled && + (isAnime + ? settings.metadataSettings.anime === MetadataProviderType.TVDB + : settings.metadataSettings.tv === MetadataProviderType.TVDB); + const { existsInPlex, seasonsMap: plexSeasonsMap = new Map() } = await this.mediaExistsInPlex(media, false); const { @@ -247,11 +287,11 @@ class AvailabilitySync { } = await this.mediaExistsInJellyfin(media, true); const { existsInSonarr, seasonsMap: sonarrSeasonsMap } = - await this.mediaExistsInSonarr(media, false); + await this.mediaExistsInSonarr(media, false, shouldTrackEpisodes); const { existsInSonarr: existsInSonarr4k, seasonsMap: sonarrSeasonsMap4k, - } = await this.mediaExistsInSonarr(media, true); + } = await this.mediaExistsInSonarr(media, true, shouldTrackEpisodes); //plex if (mediaServerType === MediaServerType.PLEX) { @@ -364,25 +404,6 @@ class AvailabilitySync { ]); } - // We need to fetch from TMDB to get the episode count for each season - let tvShow: TmdbTvScanDetails | TmdbTvDetails | undefined; - try { - if (media.tmdbId) { - tvShow = await this.tmdb.getTvShowForScan({ - tvId: Number(media.tmdbId), - }); - } else if (media.tvdbId) { - tvShow = await this.tmdb.getShowByTvdbIdForScan({ - tvdbId: Number(media.tvdbId), - }); - } - } catch (e) { - logger.debug( - `Failed to fetch TMDB data for show [TMDB ID ${media.tmdbId}]. Skipping season enrichment.`, - { label: 'AvailabilitySync', errorMessage: e.message } - ); - } - if (tvShow) { // fill the finalSeasons and finalSeasons4k maps with false for missing seasons media.seasons.forEach((season) => { @@ -613,6 +634,8 @@ class AvailabilitySync { const nonSpecialSeasonKeys = seasonKeys.filter((key) => key !== 0); try { + const deletedSeasonIds: number[] = []; + for (const mediaSeason of media.seasons) { if ( seasonsPendingRemoval.has(mediaSeason.seasonNumber) && @@ -622,6 +645,35 @@ class AvailabilitySync { MediaStatus.PARTIALLY_AVAILABLE) ) { mediaSeason[is4k ? 'status4k' : 'status'] = MediaStatus.DELETED; + deletedSeasonIds.push(mediaSeason.id); + } + } + + if (deletedSeasonIds.length > 0) { + try { + const existingEpisodes = await getRepository(Episode).find({ + where: { season: { id: In(deletedSeasonIds) } }, + }); + const toSave: Episode[] = []; + + for (const existingEpisode of existingEpisodes) { + const currentStatus = existingEpisode[is4k ? 'status4k' : 'status']; + + if ( + currentStatus !== MediaStatus.DELETED && + currentStatus !== MediaStatus.UNKNOWN + ) { + existingEpisode[is4k ? 'status4k' : 'status'] = + MediaStatus.DELETED; + toSave.push(existingEpisode); + } + } + + if (toSave.length > 0) { + await getRepository(Episode).save(toSave); + } + } catch { + // Keep season deletion even if episode cleanup fails } } @@ -740,7 +792,8 @@ class AvailabilitySync { private async mediaExistsInSonarr( media: Media, - is4k: boolean + is4k: boolean, + shouldTrackEpisodes: boolean ): Promise<{ existsInSonarr: boolean; seasonsMap: Map }> { let existsInSonarr = false; let preventSeasonSearch = false; @@ -779,6 +832,26 @@ class AvailabilitySync { if (sonarr.statistics.episodeFileCount > 0) { existsInSonarr = true; + + if (shouldTrackEpisodes && externalServiceId) { + try { + const episodes = await sonarrAPI.getEpisodes(externalServiceId); + this.sonarrEpisodesCache[`${server.id}-${externalServiceId}`] = + episodes.map((episode) => ({ + seasonNumber: episode.seasonNumber, + episodeNumber: episode.episodeNumber, + hasFile: episode.hasFile, + })); + } catch (e) { + logger.error( + `Failed to fetch episodes for show [TMDB ID ${media.tmdbId}] from Sonarr.`, + { + errorMessage: e.message, + label: 'AvailabilitySync', + } + ); + } + } } } } catch (ex) { @@ -811,11 +884,46 @@ class AvailabilitySync { MediaStatus.PARTIALLY_AVAILABLE ); + const dbEpisodesBySeasonId = new Map(); + if (shouldTrackEpisodes && filteredSeasons.length > 0) { + try { + const existingEpisodes = await getRepository(Episode).find({ + where: { + season: { id: In(filteredSeasons.map((season) => season.id)) }, + }, + relations: ['season'], + }); + + for (const episode of existingEpisodes) { + const episodeSeason = await episode.season; + if (!episodeSeason) { + continue; + } + const seasonEpisodes = dbEpisodesBySeasonId.get(episodeSeason.id); + if (seasonEpisodes) { + seasonEpisodes.push(episode); + } else { + dbEpisodesBySeasonId.set(episodeSeason.id, [episode]); + } + } + } catch (e) { + logger.error( + `Failed to load episodes for show [TMDB ID ${media.tmdbId}].`, + { + errorMessage: e.message, + label: 'AvailabilitySync', + } + ); + } + } + for (const season of filteredSeasons) { const seasonExists = await this.seasonExistsInSonarr( media, season, - is4k + is4k, + shouldTrackEpisodes, + dbEpisodesBySeasonId ); if (seasonExists) { @@ -824,15 +932,30 @@ class AvailabilitySync { } } + for (const server of this.sonarrServers.filter( + (server) => server.is4k === is4k + )) { + const externalServiceId = is4k + ? media.externalServiceId4k + : media.externalServiceId; + if (externalServiceId != null) { + delete this.sonarrEpisodesCache[`${server.id}-${externalServiceId}`]; + } + } + return { existsInSonarr, seasonsMap }; } private async seasonExistsInSonarr( media: Media, season: Season, - is4k: boolean + is4k: boolean, + shouldTrackEpisodes: boolean, + dbEpisodesBySeasonId: Map ): Promise { let seasonExists = false; + const episodeHasFileByNumber = new Map(); + let hasEpisodeCache = false; // Check each sonarr instance to see if the media still exists // If found, we will assume the media exists and prevent removal @@ -841,15 +964,20 @@ class AvailabilitySync { (server) => server.is4k === is4k )) { let sonarrSeasons: SonarrSeason[] | undefined; + let sonarrEpisodes: CachedSonarrEpisode[] | undefined; if (media.externalServiceId && !is4k) { sonarrSeasons = this.sonarrSeasonsCache[`${server.id}-${media.externalServiceId}`]; + sonarrEpisodes = + this.sonarrEpisodesCache[`${server.id}-${media.externalServiceId}`]; } if (media.externalServiceId4k && is4k) { sonarrSeasons = this.sonarrSeasonsCache[`${server.id}-${media.externalServiceId4k}`]; + sonarrEpisodes = + this.sonarrEpisodesCache[`${server.id}-${media.externalServiceId4k}`]; } const seasonIsAvailable = sonarrSeasons?.find( @@ -862,6 +990,95 @@ class AvailabilitySync { if (seasonIsAvailable && sonarrSeasons) { seasonExists = true; } + + if (shouldTrackEpisodes && sonarrEpisodes) { + hasEpisodeCache = true; + for (const episode of sonarrEpisodes) { + if (episode.seasonNumber !== season.seasonNumber) { + continue; + } + + if (episode.hasFile) { + episodeHasFileByNumber.set(episode.episodeNumber, true); + } else if (!episodeHasFileByNumber.has(episode.episodeNumber)) { + episodeHasFileByNumber.set(episode.episodeNumber, false); + } + } + } + } + + if (shouldTrackEpisodes && hasEpisodeCache) { + const existingEpisodes = dbEpisodesBySeasonId.get(season.id) ?? []; + const toSave: Episode[] = []; + const toRemove: Episode[] = []; + + for (const existingEpisode of existingEpisodes) { + const hasFile = episodeHasFileByNumber.get( + existingEpisode.episodeNumber + ); + const currentStatus = existingEpisode[is4k ? 'status4k' : 'status']; + const oppositeStatus = existingEpisode[is4k ? 'status' : 'status4k']; + const oppositeActive = + oppositeStatus !== MediaStatus.DELETED && + oppositeStatus !== MediaStatus.UNKNOWN; + + if (!episodeHasFileByNumber.has(existingEpisode.episodeNumber)) { + // only drop the row when neither standard nor 4K is still active + if (oppositeActive) { + if ( + currentStatus !== MediaStatus.DELETED && + currentStatus !== MediaStatus.UNKNOWN + ) { + existingEpisode[is4k ? 'status4k' : 'status'] = + MediaStatus.DELETED; + toSave.push(existingEpisode); + } + } else { + toRemove.push(existingEpisode); + } + } else if ( + hasFile !== true && + currentStatus !== MediaStatus.DELETED && + currentStatus !== MediaStatus.UNKNOWN + ) { + existingEpisode[is4k ? 'status4k' : 'status'] = MediaStatus.DELETED; + toSave.push(existingEpisode); + } + } + + const episodeRepository = getRepository(Episode); + + if (toRemove.length > 0) { + try { + await episodeRepository.remove(toRemove); + dbEpisodesBySeasonId.set( + season.id, + existingEpisodes.filter((episode) => !toRemove.includes(episode)) + ); + } catch (e) { + logger.debug( + `Failed to remove obsolete episodes for show [TMDB ID ${media.tmdbId}] season ${season.seasonNumber}.`, + { + errorMessage: e.message, + label: 'AvailabilitySync', + } + ); + } + } + + if (toSave.length > 0) { + try { + await episodeRepository.save(toSave); + } catch (e) { + logger.error( + `Failed to soft-remove episodes for show [TMDB ID ${media.tmdbId}] season ${season.seasonNumber}.`, + { + errorMessage: e.message, + label: 'AvailabilitySync', + } + ); + } + } } return seasonExists; diff --git a/server/lib/scanners/baseScanner.ts b/server/lib/scanners/baseScanner.ts index 286a8b5c44..8b97919739 100644 --- a/server/lib/scanners/baseScanner.ts +++ b/server/lib/scanners/baseScanner.ts @@ -5,6 +5,7 @@ import { MediaType, } from '@server/constants/media'; import { getRepository } from '@server/datasource'; +import Episode from '@server/entity/Episode'; import Media from '@server/entity/Media'; import MediaRequest from '@server/entity/MediaRequest'; import Season from '@server/entity/Season'; @@ -12,6 +13,7 @@ import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import AsyncLock from '@server/utils/asyncLock'; import { randomUUID } from 'crypto'; +import { In } from 'typeorm'; // Default scan rates (can be overidden) const BUNDLE_SIZE = 20; @@ -49,6 +51,11 @@ interface ProcessOptions { hasFile?: boolean; } +export interface ProcessableEpisode { + episodeNumber: number; + hasFile: boolean; +} + export interface ProcessableSeason { seasonNumber: number; totalEpisodes: number; @@ -56,6 +63,7 @@ export interface ProcessableSeason { episodes4k: number; is4kOverride?: boolean; processing?: boolean; + episodeDetails?: ProcessableEpisode[]; } class BaseScanner { @@ -566,6 +574,7 @@ class BaseScanner { ? MediaStatus.DELETED : MediaStatus.UNKNOWN; await mediaRepository.save(media); + await this.syncEpisodeDetails(seasons, media.seasons, is4k); this.log(`Updating existing title: ${title}`); if ( @@ -677,11 +686,87 @@ class BaseScanner { : MediaStatus.UNKNOWN, }); await mediaRepository.save(newMedia); + await this.syncEpisodeDetails(seasons, newMedia.seasons, is4k); this.log(`Saved ${title}`); } }); } + private async syncEpisodeDetails( + seasons: ProcessableSeason[], + dbSeasons: Season[], + is4k: boolean + ): Promise { + const seasonsWithDetails = seasons.filter( + (season) => season.episodeDetails && season.episodeDetails.length > 0 + ); + if (seasonsWithDetails.length === 0) { + return; + } + + const seasonByNumber = new Map( + dbSeasons.map((season) => [season.seasonNumber, season]) + ); + const targetSeasonIds = seasonsWithDetails + .map((season) => seasonByNumber.get(season.seasonNumber)?.id) + .filter((id): id is number => id != null); + if (targetSeasonIds.length === 0) { + return; + } + + const episodeRepository = getRepository(Episode); + const existingEpisodes = await episodeRepository.find({ + where: { season: { id: In(targetSeasonIds) } }, + relations: ['season'], + }); + + const existingBySeasonAndNumber = new Map(); + for (const episode of existingEpisodes) { + const episodeSeason = await episode.season; + if (!episodeSeason) { + continue; + } + existingBySeasonAndNumber.set( + `${episodeSeason.id}-${episode.episodeNumber}`, + episode + ); + } + + const toSave: Episode[] = []; + for (const season of seasonsWithDetails) { + const dbSeason = seasonByNumber.get(season.seasonNumber); + if (!dbSeason?.id || !season.episodeDetails) { + continue; + } + + for (const episodeDetail of season.episodeDetails) { + const key = `${dbSeason.id}-${episodeDetail.episodeNumber}`; + const existingEpisode = existingBySeasonAndNumber.get(key); + + if (existingEpisode) { + if (episodeDetail.hasFile) { + existingEpisode[is4k ? 'status4k' : 'status'] = + MediaStatus.AVAILABLE; + toSave.push(existingEpisode); + } + } else if (episodeDetail.hasFile) { + const newEpisode = new Episode({ + episodeNumber: episodeDetail.episodeNumber, + status: is4k ? MediaStatus.UNKNOWN : MediaStatus.AVAILABLE, + status4k: is4k ? MediaStatus.AVAILABLE : MediaStatus.UNKNOWN, + season: Promise.resolve(dbSeason), + }); + toSave.push(newEpisode); + existingBySeasonAndNumber.set(key, newEpisode); + } + } + } + + if (toSave.length > 0) { + await episodeRepository.save(toSave); + } + } + /** * Declines APPROVED requests bound to media that has been orphaned before completion. * DECLINED clears the duplicate-request guard so the user can re-request it. diff --git a/server/lib/scanners/sonarr/index.ts b/server/lib/scanners/sonarr/index.ts index 9ede74097b..f9ef85d12b 100644 --- a/server/lib/scanners/sonarr/index.ts +++ b/server/lib/scanners/sonarr/index.ts @@ -12,13 +12,14 @@ import { MediaStatus, MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import type { + ProcessableEpisode, ProcessableSeason, RunnableScanner, StatusBase, } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; import type { SonarrSettings } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import { uniqWith } from 'lodash'; type SyncStatus = StatusBase & { @@ -188,9 +189,10 @@ class SonarrScanner } const tmdbId = tvShow.id; - const metadataProvider = tvShow.keywords.results.some( + const isAnime = tvShow.keywords.results.some( (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID - ) + ); + const metadataProvider = isAnime ? await getMetadataProvider('anime') : await getMetadataProvider('tv'); @@ -199,6 +201,36 @@ class SonarrScanner } const settings = getSettings(); + const shouldTrackEpisodes = + settings.main.enableEpisodeAvailability && + (isAnime + ? settings.metadataSettings.anime === MetadataProviderType.TVDB + : settings.metadataSettings.tv === MetadataProviderType.TVDB); + + let episodesBySeason = new Map(); + if (shouldTrackEpisodes && sonarrSeries.id != null) { + try { + const episodes = await this.sonarrApi.getEpisodes(sonarrSeries.id); + episodesBySeason = episodes.reduce((map, episode) => { + const seasonEpisodes = map.get(episode.seasonNumber) ?? []; + seasonEpisodes.push({ + episodeNumber: episode.episodeNumber, + hasFile: episode.hasFile, + }); + map.set(episode.seasonNumber, seasonEpisodes); + return map; + }, new Map()); + } catch (e) { + this.log( + 'Failed to fetch Sonarr episodes for availability', + 'error', + { + errorMessage: e.message, + title: sonarrSeries.title, + } + ); + } + } const filteredSeasons = tvShow.seasons .filter( @@ -233,6 +265,7 @@ class SonarrScanner totalEpisodes: season.statistics?.totalEpisodeCount ?? 0, processing: season.monitored && totalAvailableEpisodes === 0, is4kOverride: server4k, + episodeDetails: episodesBySeason.get(season.seasonNumber), }); } diff --git a/server/lib/scanners/sonarr/sonarr.test.ts b/server/lib/scanners/sonarr/sonarr.test.ts index 7d350e6e07..2d735c89f4 100644 --- a/server/lib/scanners/sonarr/sonarr.test.ts +++ b/server/lib/scanners/sonarr/sonarr.test.ts @@ -1,4 +1,4 @@ -import type { SonarrSeries } from '@server/api/servarr/sonarr'; +import type { EpisodeResult, SonarrSeries } from '@server/api/servarr/sonarr'; import SonarrAPI from '@server/api/servarr/sonarr'; import TheMovieDb from '@server/api/themoviedb'; import type { @@ -11,13 +11,14 @@ import { MediaType, } from '@server/constants/media'; import { getRepository } from '@server/datasource'; +import Episode from '@server/entity/Episode'; import Media from '@server/entity/Media'; import MediaRequest from '@server/entity/MediaRequest'; import Season from '@server/entity/Season'; import { User } from '@server/entity/User'; import { sonarrScanner } from '@server/lib/scanners/sonarr'; import type { SonarrSettings } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import { setupTestDb } from '@server/test/db'; import { runWithMockTimers } from '@server/test/runWithMockTimers'; import assert from 'node:assert/strict'; @@ -43,6 +44,17 @@ Object.defineProperty(SonarrAPI.prototype, 'getLibrarySeriesByTvdbId', { configurable: true, }); +let getEpisodesImpl: ( + seriesId: number +) => Promise = async () => []; +Object.defineProperty(SonarrAPI.prototype, 'getEpisodes', { + set() {}, + get() { + return async (seriesId: number) => getEpisodesImpl(seriesId); + }, + configurable: true, +}); + function fakeTmdbShow( tmdbId: number, seasons: TmdbTvSeasonResult[] = [ @@ -200,8 +212,15 @@ describe('Sonarr Scanner', () => { beforeEach(() => { getSeriesImpl = async () => []; getLibrarySeriesByTvdbIdImpl = async () => []; + getEpisodesImpl = async () => []; getShowByTvdbIdImpl = async () => fakeTmdbShow(1); getTvShowImpl = async () => fakeTmdbShow(1); + const settings = getSettings(); + settings.main.enableEpisodeAvailability = false; + settings.metadataSettings = { + tv: MetadataProviderType.TMDB, + anime: MetadataProviderType.TMDB, + }; }); describe('orphaned show cleanup', () => { @@ -1059,4 +1078,121 @@ describe('Sonarr Scanner', () => { assert.strictEqual(updated.status, MediaRequestStatus.APPROVED); }); }); + + describe('episode availability tracking', () => { + it('persists AVAILABLE episodes when tracking is enabled with TVDB', async () => { + const mediaRepository = getRepository(Media); + const episodeRepository = getRepository(Episode); + const settings = getSettings(); + settings.main.enableEpisodeAvailability = true; + settings.metadataSettings = { + tv: MetadataProviderType.TVDB, + anime: MetadataProviderType.TMDB, + }; + + configureSonarr([{ syncEnabled: true }]); + getSeriesImpl = async () => [ + fakeSonarrSeries({ + tvdbId: 700, + id: 42, + seasons: [ + { + seasonNumber: 1, + monitored: true, + statistics: { + episodeFileCount: 2, + totalEpisodeCount: 2, + episodeCount: 2, + percentOfEpisodes: 100, + sizeOnDisk: 0, + previousAiring: undefined, + }, + }, + ], + }), + ]; + getEpisodesImpl = async () => + [ + { + seriesId: 42, + seasonNumber: 1, + episodeNumber: 1, + hasFile: true, + }, + { + seriesId: 42, + seasonNumber: 1, + episodeNumber: 2, + hasFile: true, + }, + { + seriesId: 42, + seasonNumber: 1, + episodeNumber: 3, + hasFile: false, + }, + ] as EpisodeResult[]; + + getShowByTvdbIdImpl = async () => + fakeTmdbShow(3001, [ + { + id: 1, + air_date: '2024-01-01', + episode_count: 3, + name: 'Season 1', + overview: '', + season_number: 1, + }, + ]); + getTvShowImpl = async () => + fakeTmdbShow(3001, [ + { + id: 1, + air_date: '2024-01-01', + episode_count: 3, + name: 'Season 1', + overview: '', + season_number: 1, + }, + ]); + + await sonarrScanner.run(); + + const media = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3001 }, + relations: ['seasons'], + }); + const season = media.seasons.find((s) => s.seasonNumber === 1); + assert.ok(season); + + const episodes = await episodeRepository.find({ + where: { season: { id: season.id } }, + order: { episodeNumber: 'ASC' }, + }); + + assert.strictEqual(episodes.length, 2); + assert.strictEqual(episodes[0].status, MediaStatus.AVAILABLE); + assert.strictEqual(episodes[1].status, MediaStatus.AVAILABLE); + }); + + it('does not fetch or persist episodes when tracking is disabled', async () => { + const episodeRepository = getRepository(Episode); + let getEpisodesCalled = false; + getEpisodesImpl = async () => { + getEpisodesCalled = true; + return []; + }; + + configureSonarr([{ syncEnabled: true }]); + getSeriesImpl = async () => [fakeSonarrSeries({ tvdbId: 701, id: 43 })]; + getShowByTvdbIdImpl = async () => fakeTmdbShow(3002); + getTvShowImpl = async () => fakeTmdbShow(3002); + + await sonarrScanner.run(); + + assert.strictEqual(getEpisodesCalled, false); + const episodeCount = await episodeRepository.count(); + assert.strictEqual(episodeCount, 0); + }); + }); }); diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index a52f8cf4c6..bc81769343 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -155,6 +155,7 @@ export interface MainSettings { mediaServerType: number; partialRequestsEnabled: boolean; enableSpecialEpisodes: boolean; + enableEpisodeAvailability: boolean; locale: string; youtubeUrl: string; versionCheck: boolean; @@ -433,6 +434,7 @@ class Settings { mediaServerType: MediaServerType.NOT_CONFIGURED, partialRequestsEnabled: true, enableSpecialEpisodes: false, + enableEpisodeAvailability: false, locale: 'en', youtubeUrl: '', versionCheck: true, diff --git a/server/migration/postgres/1790426669998-AddEpisodeTable.ts b/server/migration/postgres/1790426669998-AddEpisodeTable.ts new file mode 100644 index 0000000000..8f3cab5540 --- /dev/null +++ b/server/migration/postgres/1790426669998-AddEpisodeTable.ts @@ -0,0 +1,27 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeTable1790426669998 implements MigrationInterface { + name = 'AddEpisodeTable1790426669998'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `CREATE TABLE "episode" ("id" SERIAL NOT NULL, "episodeNumber" integer NOT NULL, "status" integer NOT NULL DEFAULT '1', "status4k" integer NOT NULL DEFAULT '1', "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "seasonId" integer, CONSTRAINT "UQ_619ebf32ab6d66ecab8cc9ba7b3" UNIQUE ("seasonId", "episodeNumber"), CONSTRAINT "PK_7258b95d6d2bf7f621845a0e143" PRIMARY KEY ("id"))` + ); + await queryRunner.query( + `CREATE INDEX "IDX_e73d28c1e5e3c85125163f7c9c" ON "episode" ("seasonId") ` + ); + await queryRunner.query( + `ALTER TABLE "episode" ADD CONSTRAINT "FK_e73d28c1e5e3c85125163f7c9cd" FOREIGN KEY ("seasonId") REFERENCES "season"("id") ON DELETE CASCADE ON UPDATE NO ACTION` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "episode" DROP CONSTRAINT "FK_e73d28c1e5e3c85125163f7c9cd"` + ); + await queryRunner.query( + `DROP INDEX "public"."IDX_e73d28c1e5e3c85125163f7c9c"` + ); + await queryRunner.query(`DROP TABLE "episode"`); + } +} diff --git a/server/migration/sqlite/1790426648839-AddEpisodeTable.ts b/server/migration/sqlite/1790426648839-AddEpisodeTable.ts new file mode 100644 index 0000000000..8be9e810cf --- /dev/null +++ b/server/migration/sqlite/1790426648839-AddEpisodeTable.ts @@ -0,0 +1,47 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeTable1790426648839 implements MigrationInterface { + name = 'AddEpisodeTable1790426648839'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `CREATE TABLE "episode" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "episodeNumber" integer NOT NULL, "status" integer NOT NULL DEFAULT (1), "status4k" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "updatedAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "seasonId" integer, CONSTRAINT "UQ_619ebf32ab6d66ecab8cc9ba7b3" UNIQUE ("seasonId", "episodeNumber"))` + ); + await queryRunner.query( + `CREATE INDEX "IDX_e73d28c1e5e3c85125163f7c9c" ON "episode" ("seasonId") ` + ); + await queryRunner.query(`DROP INDEX "IDX_e73d28c1e5e3c85125163f7c9c"`); + await queryRunner.query( + `CREATE TABLE "temporary_episode" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "episodeNumber" integer NOT NULL, "status" integer NOT NULL DEFAULT (1), "status4k" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "updatedAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "seasonId" integer, CONSTRAINT "UQ_619ebf32ab6d66ecab8cc9ba7b3" UNIQUE ("seasonId", "episodeNumber"), CONSTRAINT "FK_e73d28c1e5e3c85125163f7c9cd" FOREIGN KEY ("seasonId") REFERENCES "season" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)` + ); + await queryRunner.query( + `INSERT INTO "temporary_episode"("id", "episodeNumber", "status", "status4k", "createdAt", "updatedAt", "seasonId") SELECT "id", "episodeNumber", "status", "status4k", "createdAt", "updatedAt", "seasonId" FROM "episode"` + ); + await queryRunner.query(`DROP TABLE "episode"`); + await queryRunner.query( + `ALTER TABLE "temporary_episode" RENAME TO "episode"` + ); + await queryRunner.query( + `CREATE INDEX "IDX_e73d28c1e5e3c85125163f7c9c" ON "episode" ("seasonId") ` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP INDEX "IDX_e73d28c1e5e3c85125163f7c9c"`); + await queryRunner.query( + `ALTER TABLE "episode" RENAME TO "temporary_episode"` + ); + await queryRunner.query( + `CREATE TABLE "episode" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "episodeNumber" integer NOT NULL, "status" integer NOT NULL DEFAULT (1), "status4k" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "updatedAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "seasonId" integer, CONSTRAINT "UQ_619ebf32ab6d66ecab8cc9ba7b3" UNIQUE ("seasonId", "episodeNumber"))` + ); + await queryRunner.query( + `INSERT INTO "episode"("id", "episodeNumber", "status", "status4k", "createdAt", "updatedAt", "seasonId") SELECT "id", "episodeNumber", "status", "status4k", "createdAt", "updatedAt", "seasonId" FROM "temporary_episode"` + ); + await queryRunner.query(`DROP TABLE "temporary_episode"`); + await queryRunner.query( + `CREATE INDEX "IDX_e73d28c1e5e3c85125163f7c9c" ON "episode" ("seasonId") ` + ); + await queryRunner.query(`DROP INDEX "IDX_e73d28c1e5e3c85125163f7c9c"`); + await queryRunner.query(`DROP TABLE "episode"`); + } +} diff --git a/server/models/Tv.ts b/server/models/Tv.ts index ef676e4a8d..7dd9d7b642 100644 --- a/server/models/Tv.ts +++ b/server/models/Tv.ts @@ -38,6 +38,8 @@ interface Episode { stillPath?: string; voteAverage: number; voteCount: number; + available?: boolean; + available4k?: boolean; } interface Season { @@ -114,7 +116,11 @@ export interface TvDetails { onUserWatchlist?: boolean; } -const mapEpisodeResult = (episode: TmdbTvEpisodeResult): Episode => ({ +const mapEpisodeResult = ( + episode: TmdbTvEpisodeResult, + availableMap?: Record, + available4kMap?: Record +): Episode => ({ id: episode.id, airDate: episode.air_date, episodeNumber: episode.episode_number, @@ -126,6 +132,12 @@ const mapEpisodeResult = (episode: TmdbTvEpisodeResult): Episode => ({ voteAverage: episode.vote_average, voteCount: episode.vote_count, stillPath: episode.still_path, + available: availableMap + ? (availableMap[episode.episode_number] ?? false) + : undefined, + available4k: available4kMap + ? (available4kMap[episode.episode_number] ?? false) + : undefined, }); const mapSeasonResult = (season: TmdbTvSeasonResult): Season => ({ @@ -139,10 +151,14 @@ const mapSeasonResult = (season: TmdbTvSeasonResult): Season => ({ }); export const mapSeasonWithEpisodes = ( - season: TmdbSeasonWithEpisodes + season: TmdbSeasonWithEpisodes, + availableMap?: Record, + available4kMap?: Record ): SeasonWithEpisodes => ({ airDate: season.air_date, - episodes: season.episodes.map(mapEpisodeResult), + episodes: season.episodes.map((episode) => + mapEpisodeResult(episode, availableMap, available4kMap) + ), externalIds: mapExternalIds(season.external_ids), id: season.id, name: season.name, diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 865564ba66..ffa822a79b 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -3,10 +3,12 @@ import RottenTomatoes from '@server/api/rating/rottentomatoes'; import TheMovieDb from '@server/api/themoviedb'; import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants'; import type { TmdbKeyword } from '@server/api/themoviedb/interfaces'; -import { MediaType } from '@server/constants/media'; +import { MediaStatus, MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; +import Season from '@server/entity/Season'; import { Watchlist } from '@server/entity/Watchlist'; +import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import { mapTvResult } from '@server/models/Search'; import { mapSeasonWithEpisodes, mapTvDetails } from '@server/models/Tv'; @@ -84,7 +86,69 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { language: (req.query.language as string) ?? req.locale, }); - return res.status(200).json(mapSeasonWithEpisodes(season)); + let availableMap: Record | undefined; + let available4kMap: Record | undefined; + + const settings = getSettings(); + const shouldTrackEpisodes = settings.main.enableEpisodeAvailability; + + if (shouldTrackEpisodes) { + const dbSeason = await getRepository(Season).findOne({ + where: { + seasonNumber: Number(req.params.seasonNumber), + media: { + tmdbId: Number(req.params.id), + mediaType: MediaType.TV, + }, + }, + relations: { + episodes: true, + }, + }); + + if (dbSeason) { + const trackedEpisodes = (dbSeason.episodes ?? []).filter( + (episode) => + episode.status === MediaStatus.AVAILABLE || + episode.status4k === MediaStatus.AVAILABLE + ); + const metadataEpisodeNumbers = new Set( + season.episodes.map((episode) => episode.episode_number) + ); + + if (trackedEpisodes.length > 0 && metadataEpisodeNumbers.size > 0) { + const hasEpisodeNumberMismatch = trackedEpisodes.some( + (episode) => !metadataEpisodeNumbers.has(episode.episodeNumber) + ); + + if (hasEpisodeNumberMismatch) { + logger.warn( + 'Skipping episode availability due to episode number mismatch', + { + label: 'API', + tvId: req.params.id, + seasonNumber: req.params.seasonNumber, + metadataEpisodeCount: metadataEpisodeNumbers.size, + trackedEpisodeCount: trackedEpisodes.length, + } + ); + } else { + availableMap = {}; + available4kMap = {}; + for (const episode of trackedEpisodes) { + availableMap[episode.episodeNumber] = + episode.status === MediaStatus.AVAILABLE; + available4kMap[episode.episodeNumber] = + episode.status4k === MediaStatus.AVAILABLE; + } + } + } + } + } + + return res + .status(200) + .json(mapSeasonWithEpisodes(season, availableMap, available4kMap)); } catch (e) { logger.debug('Something went wrong retrieving season', { label: 'API', diff --git a/src/components/Settings/SettingsMain/index.tsx b/src/components/Settings/SettingsMain/index.tsx index 42b38e84d0..2694509508 100644 --- a/src/components/Settings/SettingsMain/index.tsx +++ b/src/components/Settings/SettingsMain/index.tsx @@ -73,6 +73,9 @@ const messages = defineMessages('components.Settings.SettingsMain', { validationApplicationUrlTrailingSlash: 'URL must not end in a trailing slash', partialRequestsEnabled: 'Allow Partial Series Requests', enableSpecialEpisodes: 'Allow Special Episodes Requests', + enableEpisodeAvailability: 'Enable Episode Availability Tracking', + enableEpisodeAvailabilityTip: + "Track individual episode availability. Match Seerr's metadata provider to your library agent (TMDB or TVDB).", locale: 'Display Language', youtubeUrl: 'YouTube URL', youtubeUrlTip: @@ -92,6 +95,7 @@ const SettingsMain = () => { error, mutate: revalidate, } = useSWR('/api/v1/settings/main'); + const { data: userData } = useSWR( currentUser ? `/api/v1/user/${currentUser.id}/settings/main` : null ); @@ -180,6 +184,7 @@ const SettingsMain = () => { blocklistedTagsLimit: data?.blocklistedTagsLimit || 50, partialRequestsEnabled: data?.partialRequestsEnabled, enableSpecialEpisodes: data?.enableSpecialEpisodes, + enableEpisodeAvailability: data?.enableEpisodeAvailability, cacheImages: data?.cacheImages, youtubeUrl: data?.youtubeUrl, versionCheck: data?.versionCheck, @@ -204,6 +209,7 @@ const SettingsMain = () => { blocklistedTagsLimit: values.blocklistedTagsLimit, partialRequestsEnabled: values.partialRequestsEnabled, enableSpecialEpisodes: values.enableSpecialEpisodes, + enableEpisodeAvailability: values.enableEpisodeAvailability, cacheImages: values.cacheImages, youtubeUrl: values.youtubeUrl, versionCheck: values?.versionCheck, @@ -606,6 +612,34 @@ const SettingsMain = () => { /> +
+ +
+ { + setFieldValue( + 'enableEpisodeAvailability', + !values.enableEpisodeAvailability + ); + }} + /> +
+
{episode.overview &&

{episode.overview}

} diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 4238256aad..a955115373 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -1030,6 +1030,8 @@ "components.Settings.SettingsMain.cacheImagesTip": "Cache externally sourced images (requires a significant amount of disk space)", "components.Settings.SettingsMain.discoverRegion": "Discover Region", "components.Settings.SettingsMain.discoverRegionTip": "Filter content by regional availability", + "components.Settings.SettingsMain.enableEpisodeAvailability": "Enable Episode Availability Tracking", + "components.Settings.SettingsMain.enableEpisodeAvailabilityTip": "Track individual episode availability. Match Seerr's metadata provider to your library agent (TMDB or TVDB).", "components.Settings.SettingsMain.enableSpecialEpisodes": "Allow Special Episodes Requests", "components.Settings.SettingsMain.general": "General", "components.Settings.SettingsMain.generalsettings": "General Settings", @@ -1368,6 +1370,7 @@ "components.TitleCard.watchlistSuccess": "{title} added to watchlist successfully!", "components.TvDetails.Season.noepisodes": "Episode list unavailable.", "components.TvDetails.Season.somethingwentwrong": "Something went wrong while retrieving season data.", + "components.TvDetails.Season.status4k": "4K {status}", "components.TvDetails.TvCast.fullseriescast": "Full Series Cast", "components.TvDetails.TvCrew.fullseriescrew": "Full Series Crew", "components.TvDetails.addtowatchlist": "Add To Watchlist",