From 5a9a2da5d893f5f6b9f63482eab1add44979823b Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:36:48 +0200 Subject: [PATCH 01/53] feat(episodes): add episode availability tracking and sync This allows Jellyseerr to track the availability status of individual episodes, enabling better status reporting for partially available seasons. --- server/api/servarr/sonarr.ts | 15 ++++ server/entity/Episode.ts | 43 ++++++++++ server/entity/Media.ts | 20 ++++- server/entity/Season.ts | 8 ++ server/lib/availabilitySync.ts | 78 +++++++++++++++++++ .../postgres/1747690625482-AddEpisodeTable.ts | 21 +++++ .../sqlite/1747690625482-AddEpisodeTable.ts | 34 ++++++++ server/models/Tv.ts | 16 +++- server/routes/tv.ts | 28 ++++++- src/components/TvDetails/Season/index.tsx | 9 +++ 10 files changed, 265 insertions(+), 7 deletions(-) create mode 100644 server/entity/Episode.ts create mode 100755 server/migration/postgres/1747690625482-AddEpisodeTable.ts create mode 100755 server/migration/sqlite/1747690625482-AddEpisodeTable.ts diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts index 29679d0e51..cfe9f3f756 100644 --- a/server/api/servarr/sonarr.ts +++ b/server/api/servarr/sonarr.ts @@ -481,6 +481,21 @@ class SonarrAPI extends ServarrBase<{ }); } }; + + public async getEpisodesBySeriesId( + seriesId: number + ): Promise { + try { + const response = await this.axios.get(`/episode`, { + params: { seriesId }, + }); + return response.data; + } catch (e) { + throw new Error( + `[Sonarr] Failed to retrieve episodes for series: ${e.message}` + ); + } + } } export default SonarrAPI; diff --git a/server/entity/Episode.ts b/server/entity/Episode.ts new file mode 100644 index 0000000000..9a32788473 --- /dev/null +++ b/server/entity/Episode.ts @@ -0,0 +1,43 @@ +import { MediaStatus } from '@server/constants/media'; +import { DbAwareColumn } from '@server/utils/DbColumnHelper'; +import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; +import Season from './Season'; + +@Entity() +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; + + @ManyToOne(() => Season, (season: Season) => season.episodes, { + onDelete: 'CASCADE', + nullable: true, + }) + public season?: Promise; + + @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) + public createdAt: Date; + + @DbAwareColumn({ + type: 'datetime', + default: () => 'CURRENT_TIMESTAMP', + onUpdate: 'CURRENT_TIMESTAMP', + }) + public updatedAt: Date; + + constructor(init?: Partial) { + if (init) { + Object.assign(this, init); + } + } +} + +export default Episode; diff --git a/server/entity/Media.ts b/server/entity/Media.ts index 3709e363e1..76fb5a5417 100644 --- a/server/entity/Media.ts +++ b/server/entity/Media.ts @@ -102,9 +102,27 @@ class Media { const mediaRepository = getRepository(Media); try { + const relations: { + requests: boolean; + issues: boolean; + seasons?: { + episodes: boolean; + }; + } = { + requests: true, + issues: true, + }; + + // Only load seasons for TV shows + if (mediaType === MediaType.TV) { + relations.seasons = { + episodes: true, + }; + } + const media = await mediaRepository.findOne({ where: { tmdbId: id, mediaType: mediaType }, - relations: { requests: true, issues: true }, + relations, }); return media ?? undefined; diff --git a/server/entity/Season.ts b/server/entity/Season.ts index f1e5a11d3e..07860ecbc4 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,12 @@ class Season { @Index() public media: Promise; + @OneToMany(() => Episode, (episode) => episode.season, { + cascade: true, + eager: true, + }) + public episodes: Episode[]; + @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) public createdAt: Date; diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 4a700ef355..f2bb9c7781 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -13,6 +13,7 @@ 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'; @@ -833,6 +834,7 @@ class AvailabilitySync { is4k: boolean ): Promise { let seasonExists = false; + const episodeRepository = getRepository(Episode); // Check each sonarr instance to see if the media still exists // If found, we will assume the media exists and prevent removal @@ -861,6 +863,82 @@ class AvailabilitySync { if (seasonIsAvailable && sonarrSeasons) { seasonExists = true; + + const sonarrApi = new SonarrAPI({ + url: SonarrAPI.buildUrl(server, '/api/v3'), + apiKey: server.apiKey, + }); + + try { + const serviceId = is4k + ? media.externalServiceId4k + : media.externalServiceId; + + if (!serviceId) { + logger.error('Missing service ID for episode sync', { + label: 'Availability Sync', + tvId: media.tmdbId, + seasonNumber: season.seasonNumber, + is4k, + }); + return seasonExists; + } + + const episodes = await sonarrApi.getEpisodesBySeriesId(serviceId); + + for (const ep of episodes) { + if (ep.seasonNumber === season.seasonNumber) { + const existingEpisode = await episodeRepository.findOne({ + where: { + episodeNumber: ep.episodeNumber, + season: { id: season.id }, + }, + relations: ['season'], + }); + + if (existingEpisode) { + existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN; + await episodeRepository.save(existingEpisode); + } else { + const newEpisode = new Episode(); + newEpisode.episodeNumber = ep.episodeNumber; + newEpisode.status = is4k + ? MediaStatus.UNKNOWN + : ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN; + newEpisode.status4k = is4k + ? ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN + : MediaStatus.UNKNOWN; + newEpisode.season = Promise.resolve(season); + + try { + await episodeRepository.save(newEpisode); + } catch (saveError) { + logger.error('Failed to save new episode', { + label: 'Availability Sync', + errorMessage: saveError.message, + tvId: media.tmdbId, + seasonNumber: season.seasonNumber, + episodeNumber: ep.episodeNumber, + }); + } + } + } + } + } catch (err) { + logger.error('Failed to update episode availability', { + label: 'Availability Sync', + errorMessage: err.message, + tvId: media.tmdbId, + seasonNumber: season.seasonNumber, + sonarrServerId: server.id, + }); + } } } diff --git a/server/migration/postgres/1747690625482-AddEpisodeTable.ts b/server/migration/postgres/1747690625482-AddEpisodeTable.ts new file mode 100755 index 0000000000..3af000c511 --- /dev/null +++ b/server/migration/postgres/1747690625482-AddEpisodeTable.ts @@ -0,0 +1,21 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeTable1747690625482 implements MigrationInterface { + name = 'AddEpisodeTable1747690625482'; + + 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 "PK_7258b95d6d2bf7f621845a0e143" PRIMARY KEY ("id"))` + ); + 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 TABLE "episode"`); + } +} diff --git a/server/migration/sqlite/1747690625482-AddEpisodeTable.ts b/server/migration/sqlite/1747690625482-AddEpisodeTable.ts new file mode 100755 index 0000000000..7e6cb416d1 --- /dev/null +++ b/server/migration/sqlite/1747690625482-AddEpisodeTable.ts @@ -0,0 +1,34 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeTable1747690625482 implements MigrationInterface { + name = 'AddEpisodeTable1747690625482'; + + 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)` + ); + 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 "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"` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + 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)` + ); + 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"`); + } +} diff --git a/server/models/Tv.ts b/server/models/Tv.ts index ef676e4a8d..9c254a1421 100644 --- a/server/models/Tv.ts +++ b/server/models/Tv.ts @@ -38,6 +38,7 @@ interface Episode { stillPath?: string; voteAverage: number; voteCount: number; + available?: boolean; } interface Season { @@ -114,7 +115,10 @@ export interface TvDetails { onUserWatchlist?: boolean; } -const mapEpisodeResult = (episode: TmdbTvEpisodeResult): Episode => ({ +const mapEpisodeResult = ( + episode: TmdbTvEpisodeResult, + availableMap?: Record +): Episode => ({ id: episode.id, airDate: episode.air_date, episodeNumber: episode.episode_number, @@ -126,6 +130,9 @@ 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, }); const mapSeasonResult = (season: TmdbTvSeasonResult): Season => ({ @@ -139,10 +146,13 @@ const mapSeasonResult = (season: TmdbTvSeasonResult): Season => ({ }); export const mapSeasonWithEpisodes = ( - season: TmdbSeasonWithEpisodes + season: TmdbSeasonWithEpisodes, + availableMap?: Record ): SeasonWithEpisodes => ({ airDate: season.air_date, - episodes: season.episodes.map(mapEpisodeResult), + episodes: season.episodes.map((episode) => + mapEpisodeResult(episode, availableMap) + ), 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..8d2f8d8ff5 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -3,7 +3,7 @@ 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 { Watchlist } from '@server/entity/Watchlist'; @@ -28,7 +28,6 @@ tvRoutes.get('/:id', async (req, res, next) => { : await getMetadataProvider('tv'); const tv = await metadataProvider.getTvShow({ tvId: Number(req.params.id), - language: (req.query.language as string) ?? req.locale, }); const media = await Media.getMedia(tv.id, MediaType.TV); @@ -84,7 +83,30 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { language: (req.query.language as string) ?? req.locale, }); - return res.status(200).json(mapSeasonWithEpisodes(season)); + const media = await Media.getMedia(Number(req.params.id), MediaType.TV); + const availableMap: Record = {}; + + if (media?.seasons) { + const dbSeason = media.seasons.find( + (s) => s.seasonNumber === Number(req.params.seasonNumber) + ); + if (dbSeason) { + if (dbSeason.status === MediaStatus.AVAILABLE) { + for (const episode of season.episodes) { + availableMap[episode.episode_number] = true; + } + } else if (dbSeason.status === MediaStatus.PARTIALLY_AVAILABLE) { + if (dbSeason.episodes) { + for (const episode of dbSeason.episodes) { + availableMap[episode.episodeNumber] = + episode.status === MediaStatus.AVAILABLE; + } + } + } + } + } + + return res.status(200).json(mapSeasonWithEpisodes(season, availableMap)); } catch (e) { logger.debug('Something went wrong retrieving season', { label: 'API', diff --git a/src/components/TvDetails/Season/index.tsx b/src/components/TvDetails/Season/index.tsx index 95137cfdfe..ed4ee4875d 100644 --- a/src/components/TvDetails/Season/index.tsx +++ b/src/components/TvDetails/Season/index.tsx @@ -1,6 +1,8 @@ import AirDateBadge from '@app/components/AirDateBadge'; +import Badge from '@app/components/Common/Badge'; import CachedImage from '@app/components/Common/CachedImage'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; import type { SeasonWithEpisodes } from '@server/models/Tv'; import { useIntl } from 'react-intl'; @@ -52,6 +54,13 @@ const Season = ({ seasonNumber, tvId }: SeasonProps) => { {episode.airDate && ( )} + + {intl.formatMessage( + episode.available + ? globalMessages.available + : globalMessages.unavailable + )} + {episode.overview &&

{episode.overview}

} From 139967c57eed0dc4c06a42b651c8e59977b26710 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Wed, 3 Sep 2025 23:19:59 +0200 Subject: [PATCH 02/53] chore(tv): removed the wrong parameter. The PR should not fix the issue reported in recent tvdb PR. Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/routes/tv.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 8d2f8d8ff5..d549da877f 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -28,6 +28,7 @@ tvRoutes.get('/:id', async (req, res, next) => { : await getMetadataProvider('tv'); const tv = await metadataProvider.getTvShow({ tvId: Number(req.params.id), + language: (req.query.language as string) ?? req.locale, }); const media = await Media.getMedia(tv.id, MediaType.TV); @@ -80,7 +81,6 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { const season = await metadataProvider.getTvSeason({ tvId: Number(req.params.id), seasonNumber: Number(req.params.seasonNumber), - language: (req.query.language as string) ?? req.locale, }); const media = await Media.getMedia(Number(req.params.id), MediaType.TV); From e66049c3cb90cce9e99aeb30227f16f00859f728 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:40 +0200 Subject: [PATCH 03/53] feat(settings): make the feature optionnal Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- cypress/config/settings.cypress.json | 3 +- seerr-api.yml | 3 + server/interfaces/api/settingsInterfaces.ts | 1 + server/lib/availabilitySync.ts | 86 ++++++++++--------- server/lib/settings/index.ts | 4 + .../Settings/SettingsMain/index.tsx | 34 ++++++++ src/context/SettingsContext.tsx | 1 + src/i18n/locale/en.json | 2 + src/pages/_app.tsx | 1 + 9 files changed, 95 insertions(+), 40 deletions(-) diff --git a/cypress/config/settings.cypress.json b/cypress/config/settings.cypress.json index f485424fcc..b2661e9d8b 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": { @@ -202,4 +203,4 @@ "forceMaxTtl": -1 } } -} +} \ No newline at end of file diff --git a/seerr-api.yml b/seerr-api.yml index ae1fdc254f..7a2e404721 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 diff --git a/server/interfaces/api/settingsInterfaces.ts b/server/interfaces/api/settingsInterfaces.ts index 678a9d07aa..d3d90eb42a 100644 --- a/server/interfaces/api/settingsInterfaces.ts +++ b/server/interfaces/api/settingsInterfaces.ts @@ -42,6 +42,7 @@ export interface PublicSettingsResponse { mediaServerType: number; partialRequestsEnabled: boolean; enableSpecialEpisodes: boolean; + enableEpisodeAvailability: boolean; cacheImages: boolean; vapidPublic: string; enablePushRegistration: boolean; diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index f2bb9c7781..365d255c5e 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -19,7 +19,7 @@ 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'; @@ -836,6 +836,12 @@ class AvailabilitySync { let seasonExists = false; const episodeRepository = getRepository(Episode); + const settings = getSettings(); + const shouldTrackEpisodes = + settings.main.enableEpisodeAvailability && + (settings.metadataSettings.tv === MetadataProviderType.TVDB || + settings.metadataSettings.anime === MetadataProviderType.TVDB); + // Check each sonarr instance to see if the media still exists // If found, we will assume the media exists and prevent removal // We can use the cache we built when we fetched the series with mediaExistsInSonarr @@ -884,48 +890,50 @@ class AvailabilitySync { return seasonExists; } - const episodes = await sonarrApi.getEpisodesBySeriesId(serviceId); + if (shouldTrackEpisodes) { + const episodes = await sonarrApi.getEpisodesBySeriesId(serviceId); - for (const ep of episodes) { - if (ep.seasonNumber === season.seasonNumber) { - const existingEpisode = await episodeRepository.findOne({ - where: { - episodeNumber: ep.episodeNumber, - season: { id: season.id }, - }, - relations: ['season'], - }); + for (const ep of episodes) { + if (ep.seasonNumber === season.seasonNumber) { + const existingEpisode = await episodeRepository.findOne({ + where: { + episodeNumber: ep.episodeNumber, + season: { id: season.id }, + }, + relations: ['season'], + }); - if (existingEpisode) { - existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN; - await episodeRepository.save(existingEpisode); - } else { - const newEpisode = new Episode(); - newEpisode.episodeNumber = ep.episodeNumber; - newEpisode.status = is4k - ? MediaStatus.UNKNOWN - : ep.hasFile + if (existingEpisode) { + existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile ? MediaStatus.AVAILABLE : MediaStatus.UNKNOWN; - newEpisode.status4k = is4k - ? ep.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN - : MediaStatus.UNKNOWN; - newEpisode.season = Promise.resolve(season); - - try { - await episodeRepository.save(newEpisode); - } catch (saveError) { - logger.error('Failed to save new episode', { - label: 'Availability Sync', - errorMessage: saveError.message, - tvId: media.tmdbId, - seasonNumber: season.seasonNumber, - episodeNumber: ep.episodeNumber, - }); + await episodeRepository.save(existingEpisode); + } else { + const newEpisode = new Episode(); + newEpisode.episodeNumber = ep.episodeNumber; + newEpisode.status = is4k + ? MediaStatus.UNKNOWN + : ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN; + newEpisode.status4k = is4k + ? ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN + : MediaStatus.UNKNOWN; + newEpisode.season = Promise.resolve(season); + + try { + await episodeRepository.save(newEpisode); + } catch (saveError) { + logger.error('Failed to save new episode', { + label: 'Availability Sync', + errorMessage: saveError.message, + tvId: media.tmdbId, + seasonNumber: season.seasonNumber, + episodeNumber: ep.episodeNumber, + }); + } } } } diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index a52f8cf4c6..e112fd8a81 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; @@ -209,6 +210,7 @@ interface FullPublicSettings extends PublicSettings { jellyfinServerName?: string; partialRequestsEnabled: boolean; enableSpecialEpisodes: boolean; + enableEpisodeAvailability: boolean; cacheImages: boolean; vapidPublic: string; enablePushRegistration: boolean; @@ -433,6 +435,7 @@ class Settings { mediaServerType: MediaServerType.NOT_CONFIGURED, partialRequestsEnabled: true, enableSpecialEpisodes: false, + enableEpisodeAvailability: false, locale: 'en', youtubeUrl: '', versionCheck: true, @@ -734,6 +737,7 @@ class Settings { mediaServerType: this.main.mediaServerType, partialRequestsEnabled: this.data.main.partialRequestsEnabled, enableSpecialEpisodes: this.data.main.enableSpecialEpisodes, + enableEpisodeAvailability: this.data.main.enableEpisodeAvailability, cacheImages: this.data.main.cacheImages, vapidPublic: this.vapidPublic, enablePushRegistration: this.data.notifications.agents.webpush.enabled, diff --git a/src/components/Settings/SettingsMain/index.tsx b/src/components/Settings/SettingsMain/index.tsx index 42b38e84d0..87fd6d836d 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 status (requires TVDB as metadata provider for TV shows or anime)', 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}

} From c21c29e46ebba50cbdaa1d0d7093e00c3cc9167e Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:45 +0200 Subject: [PATCH 05/53] fix(api): only mark episode as available if provider is tvdb Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/routes/tv.ts | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/server/routes/tv.ts b/server/routes/tv.ts index d549da877f..9bffae2d22 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -7,6 +7,7 @@ import { MediaStatus, MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import { Watchlist } from '@server/entity/Watchlist'; +import { getSettings, MetadataProviderType } from '@server/lib/settings'; import logger from '@server/logger'; import { mapTvResult } from '@server/models/Search'; import { mapSeasonWithEpisodes, mapTvDetails } from '@server/models/Tv'; @@ -83,23 +84,34 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { seasonNumber: Number(req.params.seasonNumber), }); - const media = await Media.getMedia(Number(req.params.id), MediaType.TV); const availableMap: Record = {}; - if (media?.seasons) { - const dbSeason = media.seasons.find( - (s) => s.seasonNumber === Number(req.params.seasonNumber) - ); - if (dbSeason) { - if (dbSeason.status === MediaStatus.AVAILABLE) { - for (const episode of season.episodes) { - availableMap[episode.episode_number] = true; - } - } else if (dbSeason.status === MediaStatus.PARTIALLY_AVAILABLE) { - if (dbSeason.episodes) { - for (const episode of dbSeason.episodes) { - availableMap[episode.episodeNumber] = - episode.status === MediaStatus.AVAILABLE; + const settings = await getSettings(); + const isAnime = tmdbTv.keywords.results.some( + (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID + ); + const isTvdbProvider = isAnime + ? settings.metadataSettings.anime === MetadataProviderType.TVDB + : settings.metadataSettings.tv === MetadataProviderType.TVDB; + + if (isTvdbProvider) { + const media = await Media.getMedia(Number(req.params.id), MediaType.TV); + + if (media?.seasons) { + const dbSeason = media.seasons.find( + (s) => s.seasonNumber === Number(req.params.seasonNumber) + ); + if (dbSeason) { + if (dbSeason.status === MediaStatus.AVAILABLE) { + for (const episode of season.episodes) { + availableMap[episode.episode_number] = true; + } + } else if (dbSeason.status === MediaStatus.PARTIALLY_AVAILABLE) { + if (dbSeason.episodes) { + for (const episode of dbSeason.episodes) { + availableMap[episode.episodeNumber] = + episode.status === MediaStatus.AVAILABLE; + } } } } From 7c16d7363187d128a0332cd9dd5f3b0e826c341f Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:49 +0200 Subject: [PATCH 06/53] fix(cypress): add missing newline Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- cypress/config/settings.cypress.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cypress/config/settings.cypress.json b/cypress/config/settings.cypress.json index b2661e9d8b..5d7dd37029 100644 --- a/cypress/config/settings.cypress.json +++ b/cypress/config/settings.cypress.json @@ -203,4 +203,4 @@ "forceMaxTtl": -1 } } -} \ No newline at end of file +} From 117590d39bc8c5ff12132a80f4192bddd783af46 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:51 +0200 Subject: [PATCH 07/53] fix(tv): rely on provider type instead of setting Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- src/components/TvDetails/Season/index.tsx | 24 ++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/components/TvDetails/Season/index.tsx b/src/components/TvDetails/Season/index.tsx index cb15e1dc0d..51198e8417 100644 --- a/src/components/TvDetails/Season/index.tsx +++ b/src/components/TvDetails/Season/index.tsx @@ -2,10 +2,11 @@ import AirDateBadge from '@app/components/AirDateBadge'; import Badge from '@app/components/Common/Badge'; import CachedImage from '@app/components/Common/CachedImage'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; -import useSettings from '@app/hooks/useSettings'; +import { MetadataProviderType } from '@app/components/MetadataSelector'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; -import type { SeasonWithEpisodes } from '@server/models/Tv'; +import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants'; +import type { SeasonWithEpisodes, TvDetails } from '@server/models/Tv'; import { useIntl } from 'react-intl'; import useSWR from 'swr'; @@ -21,10 +22,14 @@ type SeasonProps = { const Season = ({ seasonNumber, tvId }: SeasonProps) => { const intl = useIntl(); - const settings = useSettings(); const { data, error } = useSWR( `/api/v1/tv/${tvId}/season/${seasonNumber}` ); + const { data: tvData } = useSWR(`/api/v1/tv/${tvId}`); + const { data: metadataSettings } = useSWR<{ + tv: MetadataProviderType; + anime: MetadataProviderType; + }>('/api/v1/settings/metadatas'); if (!data && !error) { return ; @@ -34,6 +39,15 @@ const Season = ({ seasonNumber, tvId }: SeasonProps) => { return
{intl.formatMessage(messages.somethingwentwrong)}
; } + const isAnime = tvData?.keywords.some( + (keyword) => keyword.id === ANIME_KEYWORD_ID + ); + const isTvdbProvider = metadataSettings + ? isAnime + ? metadataSettings.anime === MetadataProviderType.TVDB + : metadataSettings.tv === MetadataProviderType.TVDB + : false; + return (
{data.episodes.length === 0 ? ( @@ -56,10 +70,10 @@ const Season = ({ seasonNumber, tvId }: SeasonProps) => { {episode.airDate && ( )} - {settings.currentSettings.enableEpisodeAvailability && + {isTvdbProvider && episode.airDate && new Date(episode.airDate) <= new Date() && - episode.available && ( + episode.available === true && ( {intl.formatMessage(globalMessages.available)} From b30d353e11ad2d0c7f55591215c28b55d7c936fc Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:54 +0200 Subject: [PATCH 08/53] feat(settings): add metadata settings for TV and anime Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/interfaces/api/settingsInterfaces.ts | 4 ++++ server/lib/settings/index.ts | 2 ++ 2 files changed, 6 insertions(+) diff --git a/server/interfaces/api/settingsInterfaces.ts b/server/interfaces/api/settingsInterfaces.ts index d3d90eb42a..9db9c7b657 100644 --- a/server/interfaces/api/settingsInterfaces.ts +++ b/server/interfaces/api/settingsInterfaces.ts @@ -51,6 +51,10 @@ export interface PublicSettingsResponse { newPlexLogin: boolean; youtubeUrl: string; versionCheck: boolean; + metadataSettings: { + tv: string; + anime: string; + }; plexClientIdentifier: string; } diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index e112fd8a81..7271c25cdc 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -220,6 +220,7 @@ interface FullPublicSettings extends PublicSettings { newPlexLogin: boolean; youtubeUrl: string; versionCheck: boolean; + metadataSettings: MetadataSettings; plexClientIdentifier: string; } @@ -748,6 +749,7 @@ class Settings { newPlexLogin: this.data.main.newPlexLogin, youtubeUrl: this.data.main.youtubeUrl, versionCheck: this.data.main.versionCheck, + metadataSettings: this.data.metadataSettings, plexClientIdentifier: this.data.clientId, }; } From 0403ed6f98b3aab3673eac92114d722129314008 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:56 +0200 Subject: [PATCH 09/53] refactor(tv): simplify episode availability checks Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/routes/tv.ts | 12 +++++------ src/components/TvDetails/Season/index.tsx | 26 +++++++++-------------- 2 files changed, 15 insertions(+), 23 deletions(-) diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 9bffae2d22..5947a85c06 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -87,14 +87,12 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { const availableMap: Record = {}; const settings = await getSettings(); - const isAnime = tmdbTv.keywords.results.some( - (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID - ); - const isTvdbProvider = isAnime - ? settings.metadataSettings.anime === MetadataProviderType.TVDB - : settings.metadataSettings.tv === MetadataProviderType.TVDB; + const shouldTrackEpisodes = + settings.main.enableEpisodeAvailability && + (settings.metadataSettings.tv === MetadataProviderType.TVDB || + settings.metadataSettings.anime === MetadataProviderType.TVDB); - if (isTvdbProvider) { + if (shouldTrackEpisodes) { const media = await Media.getMedia(Number(req.params.id), MediaType.TV); if (media?.seasons) { diff --git a/src/components/TvDetails/Season/index.tsx b/src/components/TvDetails/Season/index.tsx index 51198e8417..c6e071e213 100644 --- a/src/components/TvDetails/Season/index.tsx +++ b/src/components/TvDetails/Season/index.tsx @@ -3,10 +3,10 @@ import Badge from '@app/components/Common/Badge'; import CachedImage from '@app/components/Common/CachedImage'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import { MetadataProviderType } from '@app/components/MetadataSelector'; +import useSettings from '@app/hooks/useSettings'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; -import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants'; -import type { SeasonWithEpisodes, TvDetails } from '@server/models/Tv'; +import type { SeasonWithEpisodes } from '@server/models/Tv'; import { useIntl } from 'react-intl'; import useSWR from 'swr'; @@ -22,14 +22,10 @@ type SeasonProps = { const Season = ({ seasonNumber, tvId }: SeasonProps) => { const intl = useIntl(); + const settings = useSettings(); const { data, error } = useSWR( `/api/v1/tv/${tvId}/season/${seasonNumber}` ); - const { data: tvData } = useSWR(`/api/v1/tv/${tvId}`); - const { data: metadataSettings } = useSWR<{ - tv: MetadataProviderType; - anime: MetadataProviderType; - }>('/api/v1/settings/metadatas'); if (!data && !error) { return ; @@ -39,14 +35,12 @@ const Season = ({ seasonNumber, tvId }: SeasonProps) => { return
{intl.formatMessage(messages.somethingwentwrong)}
; } - const isAnime = tvData?.keywords.some( - (keyword) => keyword.id === ANIME_KEYWORD_ID - ); - const isTvdbProvider = metadataSettings - ? isAnime - ? metadataSettings.anime === MetadataProviderType.TVDB - : metadataSettings.tv === MetadataProviderType.TVDB - : false; + const showEpisodeAvailability = + settings.currentSettings.enableEpisodeAvailability && + (settings.currentSettings.metadataSettings.tv === + MetadataProviderType.TVDB || + settings.currentSettings.metadataSettings.anime === + MetadataProviderType.TVDB); return (
@@ -70,7 +64,7 @@ const Season = ({ seasonNumber, tvId }: SeasonProps) => { {episode.airDate && ( )} - {isTvdbProvider && + {showEpisodeAvailability && episode.airDate && new Date(episode.airDate) <= new Date() && episode.available === true && ( From a0dba2dbdfbc828081d5a6b404c99adc77757fc4 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:37:58 +0200 Subject: [PATCH 10/53] fix(settings): missing metadata settings Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- src/context/SettingsContext.tsx | 4 ++++ src/pages/_app.tsx | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/context/SettingsContext.tsx b/src/context/SettingsContext.tsx index 3602e0ca71..36c69c2de2 100644 --- a/src/context/SettingsContext.tsx +++ b/src/context/SettingsContext.tsx @@ -34,6 +34,10 @@ const defaultSettings = { newPlexLogin: true, youtubeUrl: '', versionCheck: true, + metadataSettings: { + tv: 'tmdb', + anime: 'tmdb', + }, plexClientIdentifier: '', }; diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx index 74b4b2f199..630114fab1 100644 --- a/src/pages/_app.tsx +++ b/src/pages/_app.tsx @@ -264,6 +264,10 @@ CoreApp.getInitialProps = async (initialProps) => { newPlexLogin: true, youtubeUrl: '', versionCheck: true, + metadataSettings: { + tv: 'tmdb', + anime: 'tmdb', + }, plexClientIdentifier: '', }; From 001d723d3b9b1592f0b84fa5c3f22c4601ebcc6f Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:01 +0200 Subject: [PATCH 11/53] feat(availability): implement episode caching Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/api/servarr/sonarr.ts | 2 +- server/lib/availabilitySync.ts | 152 +++++++++++++++++++-------------- 2 files changed, 91 insertions(+), 63 deletions(-) diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts index cfe9f3f756..1f3076af91 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/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 365d255c5e..27cdccceb1 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -3,7 +3,11 @@ import JellyfinAPI from '@server/api/jellyfin'; import type { PlexMetadata } from '@server/api/plexapi'; import PlexAPI from '@server/api/plexapi'; import RadarrAPI, { type RadarrMovie } 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 { @@ -34,6 +38,7 @@ class AvailabilitySync { private jellyfinEpisodeExistsCache: Record; private sonarrSeasonsCache: Record; + private sonarrEpisodesCache: Record; private radarrServers: RadarrSettings[]; private sonarrServers: SonarrSettings[]; private enable4kMovie: boolean; @@ -50,6 +55,7 @@ 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); @@ -746,6 +752,12 @@ class AvailabilitySync { let existsInSonarr = false; let preventSeasonSearch = false; + const settings = getSettings(); + const shouldTrackEpisodes = + settings.main.enableEpisodeAvailability && + (settings.metadataSettings.tv === MetadataProviderType.TVDB || + settings.metadataSettings.anime === MetadataProviderType.TVDB); + // Check for availability in all of the available sonarr servers // If any find the media, we will assume the media exists for (const server of this.sonarrServers.filter((server) => { @@ -758,26 +770,44 @@ class AvailabilitySync { try { let sonarr: SonarrSeries | undefined; + let serviceId: number | undefined; if (media.externalServiceId && !is4k) { sonarr = await sonarrAPI.getSeriesById(media.externalServiceId); + serviceId = media.externalServiceId; } if (media.externalServiceId4k && is4k) { sonarr = await sonarrAPI.getSeriesById(media.externalServiceId4k); + serviceId = media.externalServiceId4k; } if (sonarr && media.tvdbId != null && sonarr.tvdbId !== media.tvdbId) { continue; } - if (sonarr) { - const externalServiceId = is4k - ? media.externalServiceId4k - : media.externalServiceId; - this.sonarrSeasonsCache[`${server.id}-${externalServiceId}`] = + if (sonarr && serviceId) { + this.sonarrSeasonsCache[`${server.id}-${serviceId}`] = sonarr.seasons; + if ( + shouldTrackEpisodes && + sonarr.statistics.episodeFileCount > 0 + ) { + try { + const episodes = await sonarrAPI.getEpisodesBySeriesId(serviceId); + this.sonarrEpisodesCache[`${server.id}-${serviceId}`] = + episodes; + } catch (err) { + logger.error('Failed to fetch episodes for caching', { + label: 'Availability Sync', + errorMessage: err.message, + tvId: media.tmdbId, + sonarrServerId: server.id, + }); + } + } + if (sonarr.statistics.episodeFileCount > 0) { existsInSonarr = true; } @@ -870,12 +900,7 @@ class AvailabilitySync { if (seasonIsAvailable && sonarrSeasons) { seasonExists = true; - const sonarrApi = new SonarrAPI({ - url: SonarrAPI.buildUrl(server, '/api/v3'), - apiKey: server.apiKey, - }); - - try { + if (shouldTrackEpisodes) { const serviceId = is4k ? media.externalServiceId4k : media.externalServiceId; @@ -887,65 +912,68 @@ class AvailabilitySync { seasonNumber: season.seasonNumber, is4k, }); - return seasonExists; + continue; } - if (shouldTrackEpisodes) { - const episodes = await sonarrApi.getEpisodesBySeriesId(serviceId); - - for (const ep of episodes) { - if (ep.seasonNumber === season.seasonNumber) { - const existingEpisode = await episodeRepository.findOne({ - where: { - episodeNumber: ep.episodeNumber, - season: { id: season.id }, - }, - relations: ['season'], - }); - - if (existingEpisode) { - existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN; - await episodeRepository.save(existingEpisode); - } else { - const newEpisode = new Episode(); - newEpisode.episodeNumber = ep.episodeNumber; - newEpisode.status = is4k - ? MediaStatus.UNKNOWN - : ep.hasFile + const cacheKey = `${server.id}-${serviceId}`; + const episodes = this.sonarrEpisodesCache[cacheKey]; + + if (episodes) { + try { + for (const ep of episodes) { + if (ep.seasonNumber === season.seasonNumber) { + const existingEpisode = await episodeRepository.findOne({ + where: { + episodeNumber: ep.episodeNumber, + season: { id: season.id }, + }, + relations: ['season'], + }); + + if (existingEpisode) { + existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile ? MediaStatus.AVAILABLE : MediaStatus.UNKNOWN; - newEpisode.status4k = is4k - ? ep.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN - : MediaStatus.UNKNOWN; - newEpisode.season = Promise.resolve(season); - - try { - await episodeRepository.save(newEpisode); - } catch (saveError) { - logger.error('Failed to save new episode', { - label: 'Availability Sync', - errorMessage: saveError.message, - tvId: media.tmdbId, - seasonNumber: season.seasonNumber, - episodeNumber: ep.episodeNumber, - }); + await episodeRepository.save(existingEpisode); + } else { + const newEpisode = new Episode(); + newEpisode.episodeNumber = ep.episodeNumber; + newEpisode.status = is4k + ? MediaStatus.UNKNOWN + : ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN; + newEpisode.status4k = is4k + ? ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN + : MediaStatus.UNKNOWN; + newEpisode.season = Promise.resolve(season); + + try { + await episodeRepository.save(newEpisode); + } catch (saveError) { + logger.error('Failed to save new episode', { + label: 'Availability Sync', + errorMessage: saveError.message, + tvId: media.tmdbId, + seasonNumber: season.seasonNumber, + episodeNumber: ep.episodeNumber, + }); + } } } } + } catch (err) { + logger.error('Failed to update episode availability', { + label: 'Availability Sync', + errorMessage: err.message, + tvId: media.tmdbId, + seasonNumber: season.seasonNumber, + sonarrServerId: server.id, + }); } } - } catch (err) { - logger.error('Failed to update episode availability', { - label: 'Availability Sync', - errorMessage: err.message, - tvId: media.tmdbId, - seasonNumber: season.seasonNumber, - sonarrServerId: server.id, - }); } } } From c6284863f5ef75b0a913d0f7d5445708df8e6412 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:03 +0200 Subject: [PATCH 12/53] refactor(season): make episodes property optional and remove eager loading Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/entity/Season.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/entity/Season.ts b/server/entity/Season.ts index 07860ecbc4..d45de8a9a0 100644 --- a/server/entity/Season.ts +++ b/server/entity/Season.ts @@ -34,9 +34,8 @@ class Season { @OneToMany(() => Episode, (episode) => episode.season, { cascade: true, - eager: true, }) - public episodes: Episode[]; + public episodes?: Episode[]; @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) public createdAt: Date; From 75f0697b06a99ee848a74763cef6d1ed4250e3e8 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:05 +0200 Subject: [PATCH 13/53] refactor(api): remove getEpisodesBySeriesId method and update availabilitySync to use getEpisodes Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me> --- server/api/servarr/sonarr.ts | 14 -------------- server/lib/availabilitySync.ts | 13 ++++--------- 2 files changed, 4 insertions(+), 23 deletions(-) diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts index 1f3076af91..11ff09e1ff 100644 --- a/server/api/servarr/sonarr.ts +++ b/server/api/servarr/sonarr.ts @@ -482,20 +482,6 @@ class SonarrAPI extends ServarrBase<{ } }; - public async getEpisodesBySeriesId( - seriesId: number - ): Promise { - try { - const response = await this.axios.get(`/episode`, { - params: { seriesId }, - }); - return response.data; - } catch (e) { - throw new Error( - `[Sonarr] Failed to retrieve episodes for series: ${e.message}` - ); - } - } } export default SonarrAPI; diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 27cdccceb1..80fd2ae35f 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -787,17 +787,12 @@ class AvailabilitySync { } if (sonarr && serviceId) { - this.sonarrSeasonsCache[`${server.id}-${serviceId}`] = - sonarr.seasons; + this.sonarrSeasonsCache[`${server.id}-${serviceId}`] = sonarr.seasons; - if ( - shouldTrackEpisodes && - sonarr.statistics.episodeFileCount > 0 - ) { + if (shouldTrackEpisodes && sonarr.statistics.episodeFileCount > 0) { try { - const episodes = await sonarrAPI.getEpisodesBySeriesId(serviceId); - this.sonarrEpisodesCache[`${server.id}-${serviceId}`] = - episodes; + const episodes = await sonarrAPI.getEpisodes(serviceId); + this.sonarrEpisodesCache[`${server.id}-${serviceId}`] = episodes; } catch (err) { logger.error('Failed to fetch episodes for caching', { label: 'Availability Sync', From 346051e5befc89c74750cf4814ba073b5947a6ec Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:08 +0200 Subject: [PATCH 14/53] chore: apply linting --- bin/duplicate-detector/detect.mjs | 4 +++- server/api/servarr/sonarr.ts | 1 - server/routes/tv.ts | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/bin/duplicate-detector/detect.mjs b/bin/duplicate-detector/detect.mjs index aa9fde31ea..651a8c466b 100644 --- a/bin/duplicate-detector/detect.mjs +++ b/bin/duplicate-detector/detect.mjs @@ -190,7 +190,9 @@ function formatComment(candidates) { '', 'A maintainer will review this. If this is **not** a duplicate, no action is needed.', '', - `` + `` ); return lines.join('\n'); diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts index 11ff09e1ff..36c5577b04 100644 --- a/server/api/servarr/sonarr.ts +++ b/server/api/servarr/sonarr.ts @@ -481,7 +481,6 @@ class SonarrAPI extends ServarrBase<{ }); } }; - } export default SonarrAPI; diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 5947a85c06..514482b379 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -7,7 +7,7 @@ import { MediaStatus, MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import { Watchlist } from '@server/entity/Watchlist'; -import { getSettings, MetadataProviderType } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import { mapTvResult } from '@server/models/Search'; import { mapSeasonWithEpisodes, mapTvDetails } from '@server/models/Tv'; From 4b4d180fafb97731a17434c8a6874c52ba519d4a Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:11 +0200 Subject: [PATCH 15/53] refactor(tv): change getSettings to synchronous call --- server/routes/tv.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 514482b379..b665e74215 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -86,7 +86,7 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { const availableMap: Record = {}; - const settings = await getSettings(); + const settings = getSettings(); const shouldTrackEpisodes = settings.main.enableEpisodeAvailability && (settings.metadataSettings.tv === MetadataProviderType.TVDB || From 2ce899f912680d5c57542e37ff9301e0c9209710 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:13 +0200 Subject: [PATCH 16/53] refactor(availability): enhance episode tracking logic in availability sync --- server/lib/availabilitySync.ts | 109 ++++++++++++++++----------------- 1 file changed, 52 insertions(+), 57 deletions(-) diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 80fd2ae35f..924cdb9322 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -60,6 +60,10 @@ class AvailabilitySync { this.sonarrServers = settings.sonarr; this.enable4kMovie = this.radarrServers.some((server) => server.is4k); this.enable4kShow = this.sonarrServers.some((server) => server.is4k); + const shouldTrackEpisodes = + settings.main.enableEpisodeAvailability && + (settings.metadataSettings.tv === MetadataProviderType.TVDB || + settings.metadataSettings.anime === MetadataProviderType.TVDB); try { logger.info(`Starting availability sync...`, { @@ -254,11 +258,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) { @@ -747,17 +751,12 @@ class AvailabilitySync { private async mediaExistsInSonarr( media: Media, - is4k: boolean + is4k: boolean, + shouldTrackEpisodes: boolean ): Promise<{ existsInSonarr: boolean; seasonsMap: Map }> { let existsInSonarr = false; let preventSeasonSearch = false; - const settings = getSettings(); - const shouldTrackEpisodes = - settings.main.enableEpisodeAvailability && - (settings.metadataSettings.tv === MetadataProviderType.TVDB || - settings.metadataSettings.anime === MetadataProviderType.TVDB); - // Check for availability in all of the available sonarr servers // If any find the media, we will assume the media exists for (const server of this.sonarrServers.filter((server) => { @@ -841,7 +840,8 @@ class AvailabilitySync { const seasonExists = await this.seasonExistsInSonarr( media, season, - is4k + is4k, + shouldTrackEpisodes ); if (seasonExists) { @@ -856,17 +856,12 @@ class AvailabilitySync { private async seasonExistsInSonarr( media: Media, season: Season, - is4k: boolean + is4k: boolean, + shouldTrackEpisodes: boolean ): Promise { let seasonExists = false; const episodeRepository = getRepository(Episode); - const settings = getSettings(); - const shouldTrackEpisodes = - settings.main.enableEpisodeAvailability && - (settings.metadataSettings.tv === MetadataProviderType.TVDB || - settings.metadataSettings.anime === MetadataProviderType.TVDB); - // Check each sonarr instance to see if the media still exists // If found, we will assume the media exists and prevent removal // We can use the cache we built when we fetched the series with mediaExistsInSonarr @@ -915,50 +910,50 @@ class AvailabilitySync { if (episodes) { try { - for (const ep of episodes) { - if (ep.seasonNumber === season.seasonNumber) { - const existingEpisode = await episodeRepository.findOne({ - where: { - episodeNumber: ep.episodeNumber, - season: { id: season.id }, - }, - relations: ['season'], - }); - - if (existingEpisode) { - existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile + const seasonEpisodes = episodes.filter( + (ep) => ep.seasonNumber === season.seasonNumber + ); + if (seasonEpisodes.length === 0) { + continue; + } + + const existingEpisodes = await episodeRepository.find({ + where: { season: { id: season.id } }, + relations: ['season'], + }); + const existingByNumber = new Map( + existingEpisodes.map((e) => [e.episodeNumber, e]) + ); + + const toSave: Episode[] = []; + for (const ep of seasonEpisodes) { + const existingEpisode = existingByNumber.get(ep.episodeNumber); + if (existingEpisode) { + existingEpisode[is4k ? 'status4k' : 'status'] = ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN; + toSave.push(existingEpisode); + } else { + const newEpisode = new Episode(); + newEpisode.episodeNumber = ep.episodeNumber; + newEpisode.status = is4k + ? MediaStatus.UNKNOWN + : ep.hasFile ? MediaStatus.AVAILABLE : MediaStatus.UNKNOWN; - await episodeRepository.save(existingEpisode); - } else { - const newEpisode = new Episode(); - newEpisode.episodeNumber = ep.episodeNumber; - newEpisode.status = is4k - ? MediaStatus.UNKNOWN - : ep.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN; - newEpisode.status4k = is4k - ? ep.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN - : MediaStatus.UNKNOWN; - newEpisode.season = Promise.resolve(season); - - try { - await episodeRepository.save(newEpisode); - } catch (saveError) { - logger.error('Failed to save new episode', { - label: 'Availability Sync', - errorMessage: saveError.message, - tvId: media.tmdbId, - seasonNumber: season.seasonNumber, - episodeNumber: ep.episodeNumber, - }); - } - } + newEpisode.status4k = is4k + ? ep.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN + : MediaStatus.UNKNOWN; + newEpisode.season = Promise.resolve(season); + toSave.push(newEpisode); } } + + if (toSave.length > 0) { + await episodeRepository.save(toSave); + } } catch (err) { logger.error('Failed to update episode availability', { label: 'Availability Sync', From 43b13ff14395b6a3247f10f62ecae6691eb43886 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:16 +0200 Subject: [PATCH 17/53] chore: restore old changes --- bin/duplicate-detector/detect.mjs | 4 +--- server/routes/tv.ts | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/bin/duplicate-detector/detect.mjs b/bin/duplicate-detector/detect.mjs index 651a8c466b..aa9fde31ea 100644 --- a/bin/duplicate-detector/detect.mjs +++ b/bin/duplicate-detector/detect.mjs @@ -190,9 +190,7 @@ function formatComment(candidates) { '', 'A maintainer will review this. If this is **not** a duplicate, no action is needed.', '', - `` + `` ); return lines.join('\n'); diff --git a/server/routes/tv.ts b/server/routes/tv.ts index b665e74215..85aebd5c81 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -82,6 +82,7 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { const season = await metadataProvider.getTvSeason({ tvId: Number(req.params.id), seasonNumber: Number(req.params.seasonNumber), + language: (req.query.language as string) ?? req.locale, }); const availableMap: Record = {}; From f527d91e4af5b30f433b793eac31866c1ea8539d Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:18 +0200 Subject: [PATCH 18/53] chore: reapply linting --- server/lib/availabilitySync.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 924cdb9322..7655748fe5 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -954,6 +954,7 @@ class AvailabilitySync { if (toSave.length > 0) { await episodeRepository.save(toSave); } + break; } catch (err) { logger.error('Failed to update episode availability', { label: 'Availability Sync', From 8f9d1db84d87838be4049b0441d650247e7ba39e Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:20 +0200 Subject: [PATCH 19/53] feat(migration): add episode table migrations --- ...le.ts => 1771451593380-AddEpisodeTable.ts} | 14 ++- .../sqlite/1747690625482-AddEpisodeTable.ts | 34 ------- .../sqlite/1771451593380-AddEpisodeTable.ts | 91 +++++++++++++++++++ 3 files changed, 103 insertions(+), 36 deletions(-) rename server/migration/postgres/{1747690625482-AddEpisodeTable.ts => 1771451593380-AddEpisodeTable.ts} (65%) mode change 100755 => 100644 delete mode 100755 server/migration/sqlite/1747690625482-AddEpisodeTable.ts create mode 100644 server/migration/sqlite/1771451593380-AddEpisodeTable.ts diff --git a/server/migration/postgres/1747690625482-AddEpisodeTable.ts b/server/migration/postgres/1771451593380-AddEpisodeTable.ts old mode 100755 new mode 100644 similarity index 65% rename from server/migration/postgres/1747690625482-AddEpisodeTable.ts rename to server/migration/postgres/1771451593380-AddEpisodeTable.ts index 3af000c511..a4583a7960 --- a/server/migration/postgres/1747690625482-AddEpisodeTable.ts +++ b/server/migration/postgres/1771451593380-AddEpisodeTable.ts @@ -1,12 +1,18 @@ import type { MigrationInterface, QueryRunner } from 'typeorm'; -export class AddEpisodeTable1747690625482 implements MigrationInterface { - name = 'AddEpisodeTable1747690625482'; +export class AddEpisodeTable1771451593380 implements MigrationInterface { + name = 'AddEpisodeTable1771451593380'; 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 "PK_7258b95d6d2bf7f621845a0e143" PRIMARY KEY ("id"))` ); + await queryRunner.query( + `CREATE SEQUENCE IF NOT EXISTS "blocklist_id_seq" OWNED BY "blocklist"."id"` + ); + await queryRunner.query( + `ALTER TABLE "blocklist" ALTER COLUMN "id" SET DEFAULT nextval('"blocklist_id_seq"')` + ); await queryRunner.query( `ALTER TABLE "episode" ADD CONSTRAINT "FK_e73d28c1e5e3c85125163f7c9cd" FOREIGN KEY ("seasonId") REFERENCES "season"("id") ON DELETE CASCADE ON UPDATE NO ACTION` ); @@ -16,6 +22,10 @@ export class AddEpisodeTable1747690625482 implements MigrationInterface { await queryRunner.query( `ALTER TABLE "episode" DROP CONSTRAINT "FK_e73d28c1e5e3c85125163f7c9cd"` ); + await queryRunner.query( + `ALTER TABLE "blocklist" ALTER COLUMN "id" DROP DEFAULT` + ); + await queryRunner.query(`DROP SEQUENCE "blocklist_id_seq"`); await queryRunner.query(`DROP TABLE "episode"`); } } diff --git a/server/migration/sqlite/1747690625482-AddEpisodeTable.ts b/server/migration/sqlite/1747690625482-AddEpisodeTable.ts deleted file mode 100755 index 7e6cb416d1..0000000000 --- a/server/migration/sqlite/1747690625482-AddEpisodeTable.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { MigrationInterface, QueryRunner } from 'typeorm'; - -export class AddEpisodeTable1747690625482 implements MigrationInterface { - name = 'AddEpisodeTable1747690625482'; - - 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)` - ); - 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 "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"` - ); - } - - public async down(queryRunner: QueryRunner): Promise { - 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)` - ); - 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"`); - } -} diff --git a/server/migration/sqlite/1771451593380-AddEpisodeTable.ts b/server/migration/sqlite/1771451593380-AddEpisodeTable.ts new file mode 100644 index 0000000000..6b04cf5784 --- /dev/null +++ b/server/migration/sqlite/1771451593380-AddEpisodeTable.ts @@ -0,0 +1,91 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeTable1771451593380 implements MigrationInterface { + name = 'AddEpisodeTable1771451593380'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP INDEX "IDX_03f7958328e311761b0de675fb"`); + await queryRunner.query( + `CREATE TABLE "temporary_user_push_subscription" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "endpoint" varchar NOT NULL, "p256dh" varchar NOT NULL, "auth" varchar NOT NULL, "userId" integer, "userAgent" varchar, "createdAt" datetime DEFAULT (CURRENT_TIMESTAMP), CONSTRAINT "UQ_f90ab5a4ed54905a4bb51a7148b" UNIQUE ("auth"), CONSTRAINT "UQ_6427d07d9a171a3a1ab87480005" UNIQUE ("endpoint", "userId"), CONSTRAINT "FK_03f7958328e311761b0de675fbe" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)` + ); + await queryRunner.query( + `INSERT INTO "temporary_user_push_subscription"("id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt") SELECT "id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt" FROM "user_push_subscription"` + ); + await queryRunner.query(`DROP TABLE "user_push_subscription"`); + await queryRunner.query( + `ALTER TABLE "temporary_user_push_subscription" RENAME TO "user_push_subscription"` + ); + await queryRunner.query( + `CREATE INDEX "IDX_03f7958328e311761b0de675fb" ON "user_push_subscription" ("userId") ` + ); + 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)` + ); + await queryRunner.query(`DROP INDEX "IDX_03f7958328e311761b0de675fb"`); + await queryRunner.query( + `CREATE TABLE "temporary_user_push_subscription" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "endpoint" varchar NOT NULL, "p256dh" varchar NOT NULL, "auth" varchar NOT NULL, "userId" integer, "userAgent" varchar, "createdAt" datetime DEFAULT (CURRENT_TIMESTAMP), CONSTRAINT "UQ_f90ab5a4ed54905a4bb51a7148b" UNIQUE ("auth"), CONSTRAINT "UQ_6427d07d9a171a3a1ab87480005" UNIQUE ("endpoint", "userId"), CONSTRAINT "FK_03f7958328e311761b0de675fbe" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)` + ); + await queryRunner.query( + `INSERT INTO "temporary_user_push_subscription"("id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt") SELECT "id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt" FROM "user_push_subscription"` + ); + await queryRunner.query(`DROP TABLE "user_push_subscription"`); + await queryRunner.query( + `ALTER TABLE "temporary_user_push_subscription" RENAME TO "user_push_subscription"` + ); + await queryRunner.query( + `CREATE INDEX "IDX_03f7958328e311761b0de675fb" ON "user_push_subscription" ("userId") ` + ); + 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 "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"` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + 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)` + ); + 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(`DROP INDEX "IDX_03f7958328e311761b0de675fb"`); + await queryRunner.query( + `ALTER TABLE "user_push_subscription" RENAME TO "temporary_user_push_subscription"` + ); + await queryRunner.query( + `CREATE TABLE "user_push_subscription" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "endpoint" varchar NOT NULL, "p256dh" varchar NOT NULL, "auth" varchar NOT NULL, "userId" integer, "userAgent" varchar, "createdAt" datetime DEFAULT (CURRENT_TIMESTAMP), CONSTRAINT "UQ_f90ab5a4ed54905a4bb51a7148b" UNIQUE ("auth"), CONSTRAINT "UQ_6427d07d9a171a3a1ab87480005" UNIQUE ("endpoint", "userId"), CONSTRAINT "FK_03f7958328e311761b0de675fbe" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)` + ); + await queryRunner.query( + `INSERT INTO "user_push_subscription"("id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt") SELECT "id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt" FROM "temporary_user_push_subscription"` + ); + await queryRunner.query(`DROP TABLE "temporary_user_push_subscription"`); + await queryRunner.query( + `CREATE INDEX "IDX_03f7958328e311761b0de675fb" ON "user_push_subscription" ("userId") ` + ); + await queryRunner.query(`DROP TABLE "episode"`); + await queryRunner.query(`DROP INDEX "IDX_03f7958328e311761b0de675fb"`); + await queryRunner.query( + `ALTER TABLE "user_push_subscription" RENAME TO "temporary_user_push_subscription"` + ); + await queryRunner.query( + `CREATE TABLE "user_push_subscription" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "endpoint" varchar NOT NULL, "p256dh" varchar NOT NULL, "auth" varchar NOT NULL, "userId" integer, "userAgent" varchar, "createdAt" datetime DEFAULT (CURRENT_TIMESTAMP), CONSTRAINT "UQ_f90ab5a4ed54905a4bb51a7148b" UNIQUE ("auth"), CONSTRAINT "UQ_6427d07d9a171a3a1ab87480005" UNIQUE ("endpoint", "userId"), CONSTRAINT "FK_03f7958328e311761b0de675fbe" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)` + ); + await queryRunner.query( + `INSERT INTO "user_push_subscription"("id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt") SELECT "id", "endpoint", "p256dh", "auth", "userId", "userAgent", "createdAt" FROM "temporary_user_push_subscription"` + ); + await queryRunner.query(`DROP TABLE "temporary_user_push_subscription"`); + await queryRunner.query( + `CREATE INDEX "IDX_03f7958328e311761b0de675fb" ON "user_push_subscription" ("userId") ` + ); + } +} From c221ca57463ec955a17b118f379b04fdad8bcd7c Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:23 +0200 Subject: [PATCH 20/53] feat(episode): add index on season --- server/entity/Episode.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/server/entity/Episode.ts b/server/entity/Episode.ts index 9a32788473..474414c2d8 100644 --- a/server/entity/Episode.ts +++ b/server/entity/Episode.ts @@ -1,9 +1,16 @@ import { MediaStatus } from '@server/constants/media'; import { DbAwareColumn } from '@server/utils/DbColumnHelper'; -import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; +import { + Column, + Entity, + Index, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; import Season from './Season'; @Entity() +@Index(['season']) class Episode { @PrimaryGeneratedColumn() public id: number; From f3758f50c24fb390fae5ccc4460abd93d0c006ce Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 25 Apr 2026 09:38:26 +0200 Subject: [PATCH 21/53] feat(settings): add warning for episode availability without TVDB set --- src/components/Settings/SettingsMain/index.tsx | 16 ++++++++++++++++ src/i18n/locale/en.json | 1 + 2 files changed, 17 insertions(+) diff --git a/src/components/Settings/SettingsMain/index.tsx b/src/components/Settings/SettingsMain/index.tsx index 87fd6d836d..72493082a4 100644 --- a/src/components/Settings/SettingsMain/index.tsx +++ b/src/components/Settings/SettingsMain/index.tsx @@ -1,4 +1,5 @@ import BlocklistedTagsSelector from '@app/components/BlocklistedTagsSelector'; +import Alert from '@app/components/Common/Alert'; import Button from '@app/components/Common/Button'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import PageTitle from '@app/components/Common/PageTitle'; @@ -9,6 +10,7 @@ import CopyButton from '@app/components/Settings/CopyButton'; import SettingsBadge from '@app/components/Settings/SettingsBadge'; import { availableLanguages } from '@app/context/LanguageContext'; import useLocale from '@app/hooks/useLocale'; +import useSettings from '@app/hooks/useSettings'; import useToasts from '@app/hooks/useToasts'; import { Permission, useUser } from '@app/hooks/useUser'; import globalMessages from '@app/i18n/globalMessages'; @@ -76,6 +78,8 @@ const messages = defineMessages('components.Settings.SettingsMain', { enableEpisodeAvailability: 'Enable Episode Availability Tracking', enableEpisodeAvailabilityTip: 'Track individual episode availability status (requires TVDB as metadata provider for TV shows or anime)', + enableEpisodeAvailabilityNoTvdbWarning: + 'This setting has no effect because neither TV shows nor anime use TVDB as the metadata provider.', locale: 'Display Language', youtubeUrl: 'YouTube URL', youtubeUrlTip: @@ -90,6 +94,7 @@ const SettingsMain = () => { const { user: currentUser, hasPermission: userHasPermission } = useUser(); const intl = useIntl(); const { setLocale } = useLocale(); + const { currentSettings } = useSettings(); const { data, error, @@ -639,6 +644,17 @@ const SettingsMain = () => { }} />
+ {values.enableEpisodeAvailability && + currentSettings.metadataSettings?.tv !== 'tvdb' && + currentSettings.metadataSettings?.anime !== 'tvdb' && ( +
+ + {intl.formatMessage( + messages.enableEpisodeAvailabilityNoTvdbWarning + )} + +
+ )}
- {values.enableEpisodeAvailability && - metadataSettings && - metadataSettings.tv !== MetadataProviderType.TVDB && - metadataSettings.anime !== MetadataProviderType.TVDB && ( -
- - {intl.formatMessage( - messages.enableEpisodeAvailabilityNoTvdbWarning - )} - -
- )}
{episode.overview &&

{episode.overview}

} diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 7d18670e2f..a955115373 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -1370,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", From e8f038418fc934d8fbec78bb7f18496089bff7f6 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Fri, 18 Sep 2026 23:43:51 +0200 Subject: [PATCH 48/53] fix(tv): restore warn for gated episode mismatches --- server/lib/availabilitySync.ts | 39 +++++++++++++++++----------------- server/routes/tv.ts | 7 +++--- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index cf19dfb091..4a700ef355 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -227,25 +227,6 @@ class AvailabilitySync { let showExists = false; let showExists4k = false; - // Fetch TMDB details once for 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 { existsInPlex, seasonsMap: plexSeasonsMap = new Map() } = @@ -382,6 +363,26 @@ class AvailabilitySync { ...sonarrSeasonsMap4k, ]); } + + // 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) => { diff --git a/server/routes/tv.ts b/server/routes/tv.ts index d77d759ea6..80db58395c 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -74,10 +74,9 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { const tmdbTv = await tmdb.getTvShow({ tvId: Number(req.params.id), }); - const isAnime = tmdbTv.keywords.results.some( + const metadataProvider = tmdbTv.keywords.results.some( (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID - ); - const metadataProvider = isAnime + ) ? await getMetadataProvider('anime') : await getMetadataProvider('tv'); @@ -119,7 +118,7 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { ); if (hasEpisodeNumberMismatch) { - logger.debug( + logger.warn( 'Skipping episode availability due to episode number mismatch', { label: 'API', From 202601eab36787bb6099acd098081f10c28140cf Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 26 Sep 2026 14:45:49 +0200 Subject: [PATCH 49/53] chore: regenerate AddEpisodeTable migrations after #3510 --- ...48-AddEpisodeTable.ts => 1790426669998-AddEpisodeTable.ts} | 4 ++-- ...77-AddEpisodeTable.ts => 1790426648839-AddEpisodeTable.ts} | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename server/migration/postgres/{1788195170748-AddEpisodeTable.ts => 1790426669998-AddEpisodeTable.ts} (92%) rename server/migration/sqlite/{1788195151277-AddEpisodeTable.ts => 1790426648839-AddEpisodeTable.ts} (96%) diff --git a/server/migration/postgres/1788195170748-AddEpisodeTable.ts b/server/migration/postgres/1790426669998-AddEpisodeTable.ts similarity index 92% rename from server/migration/postgres/1788195170748-AddEpisodeTable.ts rename to server/migration/postgres/1790426669998-AddEpisodeTable.ts index 6cc44314c8..8f3cab5540 100644 --- a/server/migration/postgres/1788195170748-AddEpisodeTable.ts +++ b/server/migration/postgres/1790426669998-AddEpisodeTable.ts @@ -1,7 +1,7 @@ import type { MigrationInterface, QueryRunner } from 'typeorm'; -export class AddEpisodeTable1788195170748 implements MigrationInterface { - name = 'AddEpisodeTable1788195170748'; +export class AddEpisodeTable1790426669998 implements MigrationInterface { + name = 'AddEpisodeTable1790426669998'; public async up(queryRunner: QueryRunner): Promise { await queryRunner.query( diff --git a/server/migration/sqlite/1788195151277-AddEpisodeTable.ts b/server/migration/sqlite/1790426648839-AddEpisodeTable.ts similarity index 96% rename from server/migration/sqlite/1788195151277-AddEpisodeTable.ts rename to server/migration/sqlite/1790426648839-AddEpisodeTable.ts index 18adadac30..8be9e810cf 100644 --- a/server/migration/sqlite/1788195151277-AddEpisodeTable.ts +++ b/server/migration/sqlite/1790426648839-AddEpisodeTable.ts @@ -1,7 +1,7 @@ import type { MigrationInterface, QueryRunner } from 'typeorm'; -export class AddEpisodeTable1788195151277 implements MigrationInterface { - name = 'AddEpisodeTable1788195151277'; +export class AddEpisodeTable1790426648839 implements MigrationInterface { + name = 'AddEpisodeTable1790426648839'; public async up(queryRunner: QueryRunner): Promise { await queryRunner.query( From 0c74fdbe17c703e4bb174fc897414ddc128434d8 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Tue, 18 Aug 2026 21:19:59 +0200 Subject: [PATCH 50/53] feat: wire episode availability to Sonarr scanner --- server/lib/availabilitySync.test.ts | 430 +++++++++++++++++++++- server/lib/availabilitySync.ts | 175 ++++++++- server/lib/scanners/baseScanner.ts | 93 +++++ server/lib/scanners/sonarr/index.ts | 39 +- server/lib/scanners/sonarr/sonarr.test.ts | 141 ++++++- 5 files changed, 864 insertions(+), 14 deletions(-) diff --git a/server/lib/availabilitySync.test.ts b/server/lib/availabilitySync.test.ts index 7e861e38c5..8d2366a94c 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,407 @@ 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 mark an episode DELETED when Sonarr reports hasFile false or omits it', 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[0]?.status, MediaStatus.AVAILABLE); + assert.strictEqual(episodes[1]?.status, MediaStatus.DELETED); + assert.strictEqual(episodes[2]?.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..8c3721462a 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -3,9 +3,14 @@ import JellyfinAPI from '@server/api/jellyfin'; import type { PlexMetadata } from '@server/api/plexapi'; import PlexAPI from '@server/api/plexapi'; import RadarrAPI, { type RadarrMovie } 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 { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants'; import type { TmdbTvDetails, TmdbTvScanDetails, @@ -13,14 +18,16 @@ 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'; class AvailabilitySync { public running = false; @@ -33,6 +40,7 @@ class AvailabilitySync { private jellyfinEpisodeExistsCache: Record; private sonarrSeasonsCache: Record; + private sonarrEpisodesCache: Record; private radarrServers: RadarrSettings[]; private sonarrServers: SonarrSettings[]; private enable4kMovie: boolean; @@ -49,10 +57,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...`, { @@ -229,6 +239,15 @@ class AvailabilitySync { //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 +266,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) { @@ -613,6 +632,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 +643,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 +790,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; @@ -777,6 +828,22 @@ class AvailabilitySync { this.sonarrSeasonsCache[`${server.id}-${externalServiceId}`] = sonarr.seasons; + if (shouldTrackEpisodes && externalServiceId) { + try { + const episodes = await sonarrAPI.getEpisodes(externalServiceId); + this.sonarrEpisodesCache[`${server.id}-${externalServiceId}`] = + episodes; + } catch (e) { + logger.error( + `Failed to fetch episodes for show [TMDB ID ${media.tmdbId}] from Sonarr.`, + { + errorMessage: e.message, + label: 'AvailabilitySync', + } + ); + } + } + if (sonarr.statistics.episodeFileCount > 0) { existsInSonarr = true; } @@ -811,11 +878,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) { @@ -830,9 +932,13 @@ class AvailabilitySync { 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 +947,20 @@ class AvailabilitySync { (server) => server.is4k === is4k )) { let sonarrSeasons: SonarrSeason[] | undefined; + let sonarrEpisodes: EpisodeResult[] | 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 +973,56 @@ 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[] = []; + + for (const existingEpisode of existingEpisodes) { + const hasFile = episodeHasFileByNumber.get( + existingEpisode.episodeNumber + ); + const currentStatus = existingEpisode[is4k ? 'status4k' : 'status']; + + if ( + hasFile !== true && + currentStatus !== MediaStatus.DELETED && + currentStatus !== MediaStatus.UNKNOWN + ) { + existingEpisode[is4k ? 'status4k' : 'status'] = MediaStatus.DELETED; + toSave.push(existingEpisode); + } + } + + if (toSave.length > 0) { + try { + await getRepository(Episode).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..ada5a41b3d 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,95 @@ 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 { + const newEpisode = new Episode({ + episodeNumber: episodeDetail.episodeNumber, + status: is4k + ? MediaStatus.UNKNOWN + : episodeDetail.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN, + status4k: is4k + ? episodeDetail.hasFile + ? MediaStatus.AVAILABLE + : MediaStatus.UNKNOWN + : 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..5f0c5bd00c 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,122 @@ 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, 3); + assert.strictEqual(episodes[0].status, MediaStatus.AVAILABLE); + assert.strictEqual(episodes[1].status, MediaStatus.AVAILABLE); + assert.strictEqual(episodes[2].status, MediaStatus.UNKNOWN); + }); + + 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); + }); + }); }); From a55c87b25b79351c6a743b4f56fd895eb6ccea43 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Tue, 18 Aug 2026 21:30:03 +0200 Subject: [PATCH 51/53] fix(episodes): avoid stale Sonarr episode rows breaking season badges --- server/lib/availabilitySync.test.ts | 6 +- server/lib/availabilitySync.ts | 90 ++++++++++++++++------- server/lib/scanners/baseScanner.ts | 14 +--- server/lib/scanners/sonarr/sonarr.test.ts | 3 +- server/routes/tv.ts | 4 +- 5 files changed, 76 insertions(+), 41 deletions(-) diff --git a/server/lib/availabilitySync.test.ts b/server/lib/availabilitySync.test.ts index 8d2366a94c..c2b0a6a109 100644 --- a/server/lib/availabilitySync.test.ts +++ b/server/lib/availabilitySync.test.ts @@ -2488,7 +2488,7 @@ describe('AvailabilitySync', () => { assert.strictEqual(season2Episodes[0]?.status, MediaStatus.AVAILABLE); }); - it('should mark an episode DELETED when Sonarr reports hasFile false or omits it', async () => { + it('should soft-delete episodes without a file and hard-delete omitted numbers', async () => { configurePlex(); configureSonarr([{ syncEnabled: true }]); enableEpisodeTracking(); @@ -2617,9 +2617,11 @@ describe('AvailabilitySync', () => { 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); - assert.strictEqual(episodes[2]?.status, MediaStatus.DELETED); }); it('should still mark Sonarr episodes DELETED when TMDB show lookup fails', async () => { diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 8c3721462a..6e0084c5a8 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -3,11 +3,7 @@ import JellyfinAPI from '@server/api/jellyfin'; import type { PlexMetadata } from '@server/api/plexapi'; import PlexAPI from '@server/api/plexapi'; import RadarrAPI, { type RadarrMovie } from '@server/api/servarr/radarr'; -import type { - EpisodeResult, - SonarrSeason, - SonarrSeries, -} from '@server/api/servarr/sonarr'; +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'; @@ -29,6 +25,12 @@ 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; private plexClient: PlexAPI; @@ -40,7 +42,7 @@ class AvailabilitySync { private jellyfinEpisodeExistsCache: Record; private sonarrSeasonsCache: Record; - private sonarrEpisodesCache: Record; + private sonarrEpisodesCache: Record; private radarrServers: RadarrSettings[]; private sonarrServers: SonarrSettings[]; private enable4kMovie: boolean; @@ -828,24 +830,28 @@ class AvailabilitySync { this.sonarrSeasonsCache[`${server.id}-${externalServiceId}`] = sonarr.seasons; - if (shouldTrackEpisodes && externalServiceId) { - try { - const episodes = await sonarrAPI.getEpisodes(externalServiceId); - this.sonarrEpisodesCache[`${server.id}-${externalServiceId}`] = - episodes; - } catch (e) { - logger.error( - `Failed to fetch episodes for show [TMDB ID ${media.tmdbId}] from Sonarr.`, - { - errorMessage: e.message, - label: '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) { @@ -926,6 +932,17 @@ 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 }; } @@ -947,7 +964,7 @@ class AvailabilitySync { (server) => server.is4k === is4k )) { let sonarrSeasons: SonarrSeason[] | undefined; - let sonarrEpisodes: EpisodeResult[] | undefined; + let sonarrEpisodes: CachedSonarrEpisode[] | undefined; if (media.externalServiceId && !is4k) { sonarrSeasons = @@ -993,6 +1010,7 @@ class AvailabilitySync { if (shouldTrackEpisodes && hasEpisodeCache) { const existingEpisodes = dbEpisodesBySeasonId.get(season.id) ?? []; const toSave: Episode[] = []; + const toRemove: Episode[] = []; for (const existingEpisode of existingEpisodes) { const hasFile = episodeHasFileByNumber.get( @@ -1000,7 +1018,9 @@ class AvailabilitySync { ); const currentStatus = existingEpisode[is4k ? 'status4k' : 'status']; - if ( + if (!episodeHasFileByNumber.has(existingEpisode.episodeNumber)) { + toRemove.push(existingEpisode); + } else if ( hasFile !== true && currentStatus !== MediaStatus.DELETED && currentStatus !== MediaStatus.UNKNOWN @@ -1010,9 +1030,29 @@ class AvailabilitySync { } } + 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 getRepository(Episode).save(toSave); + await episodeRepository.save(toSave); } catch (e) { logger.error( `Failed to soft-remove episodes for show [TMDB ID ${media.tmdbId}] season ${season.seasonNumber}.`, diff --git a/server/lib/scanners/baseScanner.ts b/server/lib/scanners/baseScanner.ts index ada5a41b3d..8b97919739 100644 --- a/server/lib/scanners/baseScanner.ts +++ b/server/lib/scanners/baseScanner.ts @@ -749,19 +749,11 @@ class BaseScanner { MediaStatus.AVAILABLE; toSave.push(existingEpisode); } - } else { + } else if (episodeDetail.hasFile) { const newEpisode = new Episode({ episodeNumber: episodeDetail.episodeNumber, - status: is4k - ? MediaStatus.UNKNOWN - : episodeDetail.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN, - status4k: is4k - ? episodeDetail.hasFile - ? MediaStatus.AVAILABLE - : MediaStatus.UNKNOWN - : MediaStatus.UNKNOWN, + status: is4k ? MediaStatus.UNKNOWN : MediaStatus.AVAILABLE, + status4k: is4k ? MediaStatus.AVAILABLE : MediaStatus.UNKNOWN, season: Promise.resolve(dbSeason), }); toSave.push(newEpisode); diff --git a/server/lib/scanners/sonarr/sonarr.test.ts b/server/lib/scanners/sonarr/sonarr.test.ts index 5f0c5bd00c..2d735c89f4 100644 --- a/server/lib/scanners/sonarr/sonarr.test.ts +++ b/server/lib/scanners/sonarr/sonarr.test.ts @@ -1170,10 +1170,9 @@ describe('Sonarr Scanner', () => { order: { episodeNumber: 'ASC' }, }); - assert.strictEqual(episodes.length, 3); + assert.strictEqual(episodes.length, 2); assert.strictEqual(episodes[0].status, MediaStatus.AVAILABLE); assert.strictEqual(episodes[1].status, MediaStatus.AVAILABLE); - assert.strictEqual(episodes[2].status, MediaStatus.UNKNOWN); }); it('does not fetch or persist episodes when tracking is disabled', async () => { diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 80db58395c..73fb3d9d5c 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -107,7 +107,9 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { }); if (dbSeason) { - const trackedEpisodes = dbSeason.episodes ?? []; + const trackedEpisodes = (dbSeason.episodes ?? []).filter( + (episode) => episode.status !== MediaStatus.DELETED + ); const metadataEpisodeNumbers = new Set( season.episodes.map((episode) => episode.episode_number) ); From e996a094fa314b3261ec75c0fe4d481ebc5671c3 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Fri, 18 Sep 2026 23:50:34 +0200 Subject: [PATCH 52/53] fix(availability): fetch TMDB show before episode tracking gate --- server/lib/availabilitySync.ts | 38 +++++++++++++++++----------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 6e0084c5a8..b941953022 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -239,6 +239,25 @@ 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( @@ -385,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) => { From 839a59a4e9c28a96bc11af5eb681ed67abdfd330 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Sat, 10 Oct 2026 22:22:39 +0200 Subject: [PATCH 53/53] fix(availability): make episode removal logic based on active status --- server/lib/availabilitySync.ts | 18 +++++++++++++++++- server/routes/tv.ts | 4 +++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index b941953022..819085f11c 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -1017,9 +1017,25 @@ class AvailabilitySync { 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)) { - toRemove.push(existingEpisode); + // 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 && diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 73fb3d9d5c..ffa822a79b 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -108,7 +108,9 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { if (dbSeason) { const trackedEpisodes = (dbSeason.episodes ?? []).filter( - (episode) => episode.status !== MediaStatus.DELETED + (episode) => + episode.status === MediaStatus.AVAILABLE || + episode.status4k === MediaStatus.AVAILABLE ); const metadataEpisodeNumbers = new Set( season.episodes.map((episode) => episode.episode_number)