diff --git a/README.md b/README.md index 406d92e1ee..932f956ded 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ For local MCP access, see the [SnapeTech MCP integration guide](./docs/integrati - Labeled movie and TV request destinations across multiple Radarr and Sonarr instances, with per-user access and availability tracked for each destination. - Managers can approve a one-time movie or TV request exception when a user's quota is full; optional Slack actions use a mapped account and the same request permissions as the web app. - Automation service integration with Radarr, Sonarr, Lidarr, and Bookshelf/Readarr-compatible APIs. +- Optional per-instance Radarr/Sonarr tag exclusions for library scans, with existing request history preserved and non-excluded service copies still counted. - Sonarr v5 support alongside v3/v4, including metadata-language and season-order options with explicit season mapping for recovery. - An optional TV request gate that checks whether the previous regular season was watched through a linked Plex, Jellyfin, or Emby account. - Admin-configured Prowlarr connection, per-indexer diagnostics, category coverage, and format-aware manual search across movies, TV, music, books, comics, magazines, ROMs, and PC games, with title-prefilled search links from media details; approved requests still go through their configured acquisition providers. @@ -179,6 +180,9 @@ Recent repository updates include: - **Sonarr:** v5 API support alongside v3/v4, metadata-language and season-order choices, and request recovery scoped to the selected service, quality, and season order. +- **Radarr/Sonarr sync:** administrators can omit tagged library entries from + an instance's scan without losing existing SeerrNG requests or hiding a + matching copy found on another non-excluded service. - **Integrations:** MusicBrainz and Cover Art Archive connectivity checks with bounded artwork traffic controls, plus a preview-first BookshelfNG to ChaptarrNG database migration helper for single-database setups. diff --git a/docs/fork-rationale.md b/docs/fork-rationale.md index dc2acf459e..570075c757 100644 --- a/docs/fork-rationale.md +++ b/docs/fork-rationale.md @@ -5,7 +5,7 @@ description: Public checklist for the behavior and release evidence needed befor # What upstream needs before SeerrNG can disappear -**Last reviewed: October 16, 2026.** +**Last reviewed: November 1, 2026.** SeerrNG is maintained as a separate fork so it can add cross-media workflows and adapt selected Seerr changes for its users. This matrix records what a @@ -38,6 +38,7 @@ required migration and operator path have been checked. | Sonarr anime profiles | Administrators can set and review an anime quality profile. If that profile is missing or cannot be checked at dispatch time, an approved anime request can use the standard profile on the same Sonarr service. Source context includes Seerr [issue #3159](https://github.com/seerr-team/seerr/issues/3159) and [PR #3160](https://github.com/seerr-team/seerr/pull/3160). | Checks cover profile creation and edits, missing or unavailable profiles, recovery at dispatch, and isolation across multiple Sonarr services. | | Sonarr future-season monitoring | Administrators can choose All, None, or Latest Season Requested. The last mode monitors future seasons only when a request includes the latest regular season; specials and older-only requests do not qualify. Automatic search remains separate. Source context includes Seerr [issue #3152](https://github.com/seerr-team/seerr/issues/3152) and [PR #3157](https://github.com/seerr-team/seerr/pull/3157). | Checks cover latest, older-only, special-only, and missing-season metadata, and confirm the setting round-trips while automatic-search behavior remains independent. | | Sonarr API and season orders | Sonarr v3/v4 and v5 remain supported. For v5, metadata language and season order are explicit request choices; manual season repair verifies standard seasons against TVDB and alternate orders against the selected Sonarr series. | Checks cover version detection, per-endpoint fallback, focused updates that preserve Sonarr-owned metadata, and mappings isolated by service, quality, and season order. | +| Radarr/Sonarr scan tag exclusions | Administrators can exclude tagged library entries from one Radarr or Sonarr scan without treating an excluded copy as available on that instance. Existing SeerrNG media records and requests remain intact; title-wide availability is cleared only when the excluded instance was its recorded source and no alternate copy is known. Source context includes Seerr [PR #1884](https://github.com/seerr-team/seerr/pull/1884), which closed without merging. | Checks cover optional settings round-trip and validation, legacy settings, complete scans where every item is excluded, destination and title-wide status reconciliation without request loss, safe orphan cleanup, duplicate endpoint settings, and matching items on non-excluded instances. Media-server availability remains governed by its own recorded identity. | | Request destinations and variants | Movie and series requests can target labeled Radarr and Sonarr instances. Per-user grants, quality choices, destination-specific availability, and request history stay attached to the selected service. Other media preserve selected book format, game platform, and other request variants. Source context includes Seerr [PR #3560](https://github.com/seerr-team/seerr/pull/3560). | Checks cover permission enforcement, duplicate prevention, multiple services, scans, retries, and availability on each selected destination. | | Previous-season watch gate | Administrators can require playback of the immediately previous regular TV season before later seasons are requested. The requester’s linked Plex, Jellyfin, or Emby watch history is used; uncertain playback state fails closed, and authorized managers can override the gate. Source context includes Seerr [issue #3590](https://github.com/seerr-team/seerr/issues/3590). | Checks cover partial and full-season requests, specials and empty seasons, missing library or playback data, watch-state changes, and permission-checked overrides. | | Watchlist filters and ordering | Local watchlists support title search, media-type filters, and stable sorting. Combined Plex lists retain Plex order and do not claim that remote pages were fully filtered or sorted. Deliberate Plex Watchlist removals do not trigger repeated auto-requests while the item remains removed. Source context includes Seerr [PR #3506](https://github.com/seerr-team/seerr/pull/3506). | Checks cover user isolation, pagination, local ordering, combined Plex results, and the remove/re-add auto-request cycle. | diff --git a/docs/using-seerr/settings/services.md b/docs/using-seerr/settings/services.md index cf2cf8044e..5f6f9e3b59 100644 --- a/docs/using-seerr/settings/services.md +++ b/docs/using-seerr/settings/services.md @@ -147,6 +147,23 @@ If the hostname or IP address you configured above is not accessible outside you Enable this setting if you would like to scan your Radarr/Sonarr server for existing media/request status. It is recommended that you enable this setting, so that users cannot submit requests for media which has already been requested or is already available. +#### Exclude Tags from Scan (optional) + +After testing the connection, select any Radarr or Sonarr tags whose matching +movies or series should be omitted from that service's SeerrNG scan. A matching +item is marked unknown for that instance, so it will not block a request to the +same destination. Existing SeerrNG media records and requests are retained. If +that instance was the only recorded source, its title-wide availability is also +cleared; a matching copy on another non-excluded service can still count as +available. If the same endpoint is configured more than once, its active +entries share one scan and their excluded tags are combined. + +This setting only changes the Radarr or Sonarr scan. Other configured services +can still report the same media as available, including in Discover's Recently +Added shelf when a media-server integration reports it. Existing settings +files need no migration; an omitted exclusion list behaves as empty. The +feature is inactive until **Enable Scan** is selected. + #### Enable Automatic Search (optional) Enable this setting to have Radarr/Sonarr to automatically search for media upon approval of a request. diff --git a/release-notes/2026-11-01-radarr-sonarr-sync-tag-exclusions.md b/release-notes/2026-11-01-radarr-sonarr-sync-tag-exclusions.md new file mode 100644 index 0000000000..bab8f18119 --- /dev/null +++ b/release-notes/2026-11-01-radarr-sonarr-sync-tag-exclusions.md @@ -0,0 +1,9 @@ +--- +category: changed +audience: users, operators +area: servarr +action: none +breaking: false +--- + +Administrators can exclude tagged Radarr or Sonarr library entries from scans while SeerrNG preserves existing requests and still recognizes non-excluded copies on other configured services. diff --git a/seerr-api.yml b/seerr-api.yml index c7aca427e3..1502d23bd8 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -3254,6 +3254,14 @@ components: syncEnabled: type: boolean example: false + syncExcludedTags: + type: array + maxItems: 100 + items: + type: integer + minimum: 0 + maximum: 1000000 + description: Servarr tag IDs excluded from this Radarr library scan. preventSearch: type: boolean example: false @@ -3763,6 +3771,14 @@ components: syncEnabled: type: boolean example: false + syncExcludedTags: + type: array + maxItems: 100 + items: + type: integer + minimum: 0 + maximum: 1000000 + description: Servarr tag IDs excluded from this Sonarr library scan. preventSearch: type: boolean example: false diff --git a/server/lib/externalRuntimeConfig.ts b/server/lib/externalRuntimeConfig.ts index 72a69b9f5d..d12534fcd2 100644 --- a/server/lib/externalRuntimeConfig.ts +++ b/server/lib/externalRuntimeConfig.ts @@ -83,11 +83,39 @@ const normalizeServarrServices = ( ); } + const supportsSyncExcludedTags = + service === 'radarr' || service === 'sonarr'; + const syncExcludedTags = settings.syncExcludedTags; + if ( + supportsSyncExcludedTags && + syncExcludedTags !== undefined && + (!Array.isArray(syncExcludedTags) || + syncExcludedTags.length > 100 || + syncExcludedTags.some( + (tagId) => + typeof tagId !== 'number' || + !Number.isSafeInteger(tagId) || + tagId < 0 || + tagId > 1_000_000 + )) + ) { + throw new Error( + `SEERR_EXTERNAL_CONFIG.${service}[${index}].syncExcludedTags is invalid` + ); + } + return { ...settings, // Older settings files omitted this field or stored it as null. Both // representations mean the standard (non-4K) service. is4k: settings.is4k === true, + ...(supportsSyncExcludedTags + ? { + syncExcludedTags: Array.isArray(syncExcludedTags) + ? [...new Set(syncExcludedTags)] + : [], + } + : {}), }; }); }; diff --git a/server/lib/scanners/excludedServarrAvailability.ts b/server/lib/scanners/excludedServarrAvailability.ts new file mode 100644 index 0000000000..99970cecd5 --- /dev/null +++ b/server/lib/scanners/excludedServarrAvailability.ts @@ -0,0 +1,169 @@ +import { MediaStatus, MediaType } from '@server/constants/media'; +import dataSource from '@server/datasource'; +import Media from '@server/entity/Media'; +import MediaServiceStatus, { + type VideoRequestServiceType, +} from '@server/entity/MediaServiceStatus'; +import { In } from 'typeorm'; + +export type ExcludedServarrAvailabilitySource = { + mediaId: number; + serverId: number; + format: 'standard' | '4k'; +}; + +const libraryAvailabilityStatuses = new Set([ + MediaStatus.AVAILABLE, + MediaStatus.PARTIALLY_AVAILABLE, + MediaStatus.PROCESSING, +]); + +const reportedAvailabilityStatuses = new Set([ + MediaStatus.AVAILABLE, + MediaStatus.PARTIALLY_AVAILABLE, +]); + +export const reconcileExcludedServarrAvailability = async ( + serviceType: Extract, + sources: readonly ExcludedServarrAvailabilitySource[] +): Promise => { + const sourcesByMedia = new Map>>(); + const statusUpdates = new Map< + string, + { serverId: number; format: 'standard' | '4k'; mediaIds: Set } + >(); + + for (const source of sources) { + const formats = sourcesByMedia.get(source.mediaId) ?? new Map(); + const serverIds = formats.get(source.format) ?? new Set(); + serverIds.add(source.serverId); + formats.set(source.format, serverIds); + sourcesByMedia.set(source.mediaId, formats); + + const key = `${source.serverId}:${source.format}`; + const update = statusUpdates.get(key) ?? { + serverId: source.serverId, + format: source.format, + mediaIds: new Set(), + }; + update.mediaIds.add(source.mediaId); + statusUpdates.set(key, update); + } + + if (sourcesByMedia.size === 0) { + return; + } + + await dataSource.transaction(async (manager) => { + const serviceStatusRepository = manager.getRepository(MediaServiceStatus); + for (const { serverId, format, mediaIds } of statusUpdates.values()) { + await serviceStatusRepository.update( + { + mediaId: In([...mediaIds]), + serviceType, + serverId, + format, + }, + { + status: MediaStatus.UNKNOWN, + externalServiceId: null, + externalServiceSlug: null, + seasonStatuses: null, + } + ); + } + + const mediaRepository = manager.getRepository(Media); + const mediaItems = await mediaRepository.find({ + where: { id: In([...sourcesByMedia.keys()]) }, + relations: { seasons: true, serviceStatuses: true }, + }); + + for (const media of mediaItems) { + let changed = false; + const sourcesByFormat = sourcesByMedia.get(media.id); + if (!sourcesByFormat) continue; + + for (const format of ['standard', '4k'] as const) { + const excludedServerIds = sourcesByFormat.get(format); + if (!excludedServerIds?.size) continue; + + const is4k = format === '4k'; + const serviceIdField = is4k ? 'serviceId4k' : 'serviceId'; + const currentServiceId = media[serviceIdField]; + if ( + currentServiceId == null || + !excludedServerIds.has(currentServiceId) + ) { + continue; + } + + const formatStatuses = (media.serviceStatuses ?? []).filter( + (status) => + status.serviceType === serviceType && + status.format === format && + !excludedServerIds.has(status.serverId) + ); + const alternativeAvailability = formatStatuses + .filter((status) => reportedAvailabilityStatuses.has(status.status)) + .sort((left, right) => { + const rank = (status: MediaStatus): number => + status === MediaStatus.AVAILABLE ? 0 : 1; + return rank(left.status) - rank(right.status); + })[0]; + const hasMediaServerCopy = is4k + ? Boolean(media.ratingKey4k || media.jellyfinMediaId4k) + : Boolean(media.ratingKey || media.jellyfinMediaId); + const statusField = is4k ? 'status4k' : 'status'; + + if (!hasMediaServerCopy) { + if (alternativeAvailability) { + if ( + media[statusField] !== MediaStatus.BLOCKLISTED && + media[statusField] !== MediaStatus.DELETED && + media[statusField] !== MediaStatus.PENDING + ) { + media[statusField] = alternativeAvailability.status; + } + } else if (libraryAvailabilityStatuses.has(media[statusField])) { + media[statusField] = MediaStatus.UNKNOWN; + } + + if (media.mediaType === MediaType.TV) { + for (const season of media.seasons ?? []) { + const nextStatus = alternativeAvailability + ? (alternativeAvailability.seasonStatuses?.[ + season.seasonNumber + ] ?? MediaStatus.UNKNOWN) + : MediaStatus.UNKNOWN; + if (season[statusField] !== nextStatus) { + season[statusField] = nextStatus; + } + } + } + } + + if (alternativeAvailability) { + const externalServiceIdField = is4k + ? 'externalServiceId4k' + : 'externalServiceId'; + const externalServiceSlugField = is4k + ? 'externalServiceSlug4k' + : 'externalServiceSlug'; + media[serviceIdField] = alternativeAvailability.serverId; + media[externalServiceIdField] = + alternativeAvailability.externalServiceId ?? null; + media[externalServiceSlugField] = + alternativeAvailability.externalServiceSlug ?? null; + } else { + media.resetServiceDataForResolution(is4k, true); + } + changed = true; + } + + if (changed) { + await mediaRepository.save(media); + } + } + }); +}; diff --git a/server/lib/scanners/radarr/index.ts b/server/lib/scanners/radarr/index.ts index e86e64adca..1909d40a88 100644 --- a/server/lib/scanners/radarr/index.ts +++ b/server/lib/scanners/radarr/index.ts @@ -3,6 +3,7 @@ import RadarrAPI from '@server/api/servarr/radarr'; import { MediaStatus, MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; +import { runWithRequestAdmission } from '@server/entity/MediaRequest'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { runMediaEntityMutation } from '@server/lib/mediaMutation'; import { upsertMediaSearchMetadata } from '@server/lib/mediaSearchMetadata'; @@ -11,7 +12,16 @@ import type { StatusBase, } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; +import { + reconcileExcludedServarrAvailability, + type ExcludedServarrAvailabilitySource, +} from '@server/lib/scanners/excludedServarrAvailability'; import { forEachMediaCleanupBatch } from '@server/lib/scanners/mediaCleanupBatches'; +import { + getServarrSyncExcludedTagsForEndpoint, + getServarrSyncServerIdsForEndpoint, + partitionServarrItemsBySyncExcludedTags, +} from '@server/lib/scanners/servarrTagFilters'; import { ServarrServiceAuthorityChangedError, runWithServarrServiceSnapshot, @@ -21,6 +31,7 @@ import { getSettings, type RadarrSettings } from '@server/lib/settings'; import { is4kResolution } from '@server/lib/videoResolution'; import { getHttpErrorDetails } from '@server/utils/httpError'; import { uniqWith } from 'lodash'; +import { In } from 'typeorm'; type SyncStatus = StatusBase & { currentServer: RadarrSettings; @@ -36,6 +47,11 @@ class RadarrScanner private radarrApi: RadarrAPI; private scannedTmdbIds: Set = new Set(); private scanned4kTmdbIds: Set = new Set(); + private excludedMovies: { + tmdbId: number; + serverId: number; + format: 'standard' | '4k'; + }[] = []; private didScanStandard = false; private didScan4k = false; private serverReturnedEmpty = false; @@ -64,6 +80,7 @@ class RadarrScanner } this.scannedTmdbIds.clear(); this.scanned4kTmdbIds.clear(); + this.excludedMovies = []; this.didScanStandard = false; this.didScan4k = false; this.serverReturnedEmpty = false; @@ -71,18 +88,22 @@ class RadarrScanner try { const fourKEnabled = getSettings().main.enable4k !== false; - this.servers = uniqWith( - structuredClone( - settings.radarr.filter((server) => fourKEnabled || !server.is4k) - ), - (radarrA, radarrB) => { - return ( - radarrA.hostname === radarrB.hostname && - radarrA.port === radarrB.port && - radarrA.baseUrl === radarrB.baseUrl - ); - } + const configuredServers = structuredClone( + settings.radarr.filter((server) => fourKEnabled || !server.is4k) ); + this.servers = uniqWith(configuredServers, (radarrA, radarrB) => { + return ( + radarrA.hostname === radarrB.hostname && + radarrA.port === radarrB.port && + radarrA.baseUrl === radarrB.baseUrl + ); + }).map((server) => ({ + ...server, + syncExcludedTags: getServarrSyncExcludedTagsForEndpoint( + server, + configuredServers + ), + })); this.resolutionAwareSingleServer = fourKEnabled && this.servers.filter((server) => server.syncEnabled).length === 1 && @@ -103,7 +124,7 @@ class RadarrScanner 'info' ); - this.items = await runWithServarrServiceSnapshot( + const serverItems = await runWithServarrServiceSnapshot( 'radarr', server, async (current) => { @@ -118,7 +139,7 @@ class RadarrScanner if ( fourKEnabled && this.resolutionAwareSingleServer && - this.items.some( + serverItems.some( (movie) => movie.hasFile && is4kResolution(movie.movieFile?.mediaInfo.resolution) === true @@ -130,6 +151,52 @@ class RadarrScanner const server4k = this.enable4kMovie && server.is4k; const scansBothResolutions = this.resolutionAwareSingleServer && this.enable4kMovie; + + // Keep the provider response separate: excluded results still prove + // that a scan completed and should not trigger the empty-library + // safety path below. + const { included, excluded } = + partitionServarrItemsBySyncExcludedTags( + serverItems, + server.syncExcludedTags + ); + this.items = included; + for (const movie of excluded) { + if (!Number.isSafeInteger(movie.tmdbId) || movie.tmdbId <= 0) { + continue; + } + + // One resolution-aware endpoint owns both availability tracks; + // retain the media identity so neither request track is orphaned. + if (this.resolutionAwareSingleServer) { + this.scannedTmdbIds.add(movie.tmdbId); + this.scanned4kTmdbIds.add(movie.tmdbId); + } else { + const is4k = this.getMovieIs4k(movie, server); + (is4k ? this.scanned4kTmdbIds : this.scannedTmdbIds).add( + movie.tmdbId + ); + } + + const format = scansBothResolutions + ? this.getMovieIs4k(movie, server) + ? '4k' + : 'standard' + : server4k + ? '4k' + : 'standard'; + for (const serverId of getServarrSyncServerIdsForEndpoint( + server, + configuredServers + )) { + this.excludedMovies.push({ + tmdbId: movie.tmdbId, + serverId, + format, + }); + } + } + if (scansBothResolutions) { this.didScanStandard = true; this.didScan4k = true; @@ -139,7 +206,7 @@ class RadarrScanner this.didScanStandard = true; } - if (this.items.length === 0) { + if (serverItems.length === 0) { if (server4k) { this.server4kReturnedEmpty = true; } else { @@ -157,10 +224,10 @@ class RadarrScanner await this.loop(this.processRadarrMovie.bind(this), { sessionId }); - const hasCompleteMediaIdentity = this.items.every( + const hasCompleteMediaIdentity = serverItems.every( (movie) => Number.isSafeInteger(movie.tmdbId) && movie.tmdbId > 0 ); - if (this.items.length > 0 && hasCompleteMediaIdentity) { + if (serverItems.length > 0 && hasCompleteMediaIdentity) { const qualityTmdbIds = { standard: new Set(), '4k': new Set(), @@ -191,6 +258,11 @@ class RadarrScanner } } + await this.clearExcludedMovieAvailability( + configuredServers, + fourKEnabled + ); + // Only run cleanup if all servers of this profile type have sync enabled. // If any server is skipped, we can't distinguish truly orphaned media from // media that exists on an unscanned server (e.g. separate instances for @@ -334,6 +406,69 @@ class RadarrScanner return this.enable4kMovie && server.is4k; } + private async clearExcludedMovieAvailability( + configuredServers: RadarrSettings[], + fourKEnabled: boolean + ): Promise { + if (this.excludedMovies.length === 0) return; + + const excludedTmdbIds = [ + ...new Set(this.excludedMovies.map(({ tmdbId }) => tmdbId)), + ]; + const mediaItems: Media[] = []; + for (let offset = 0; offset < excludedTmdbIds.length; offset += 500) { + mediaItems.push( + ...(await getRepository(Media).find({ + where: { + mediaType: MediaType.MOVIE, + tmdbId: In(excludedTmdbIds.slice(offset, offset + 500)), + }, + })) + ); + } + const mediaIdsByTmdbId = new Map( + mediaItems.map((media) => [media.tmdbId, media.id]) + ); + const sources: ExcludedServarrAvailabilitySource[] = []; + + for (const excluded of this.excludedMovies) { + const mediaId = mediaIdsByTmdbId.get(excluded.tmdbId); + if (mediaId !== undefined) { + sources.push({ + mediaId, + serverId: excluded.serverId, + format: excluded.format, + }); + } + } + + for (let offset = 0; offset < mediaItems.length; offset += 50) { + const batch = mediaItems.slice(offset, offset + 50); + const batchIds = new Set(batch.map(({ id }) => id)); + const batchSources = sources.filter((source) => + batchIds.has(source.mediaId) + ); + if (batchSources.length === 0) continue; + + await runWithRequestAdmission( + batch.map( + (media) => `request-media:${MediaType.MOVIE}:${media.tmdbId}` + ), + () => + runWithServarrServiceSnapshots( + 'radarr', + configuredServers.filter((server) => server.syncEnabled), + () => reconcileExcludedServarrAvailability('radarr', batchSources), + { + requireExactAuthoritySet: true, + includeCurrent: (server) => + server.syncEnabled && (fourKEnabled || !server.is4k), + } + ) + ); + } + } + private async existsInAnyServer( tmdbId: number, is4k: boolean diff --git a/server/lib/scanners/servarrTagFilters.ts b/server/lib/scanners/servarrTagFilters.ts new file mode 100644 index 0000000000..5a566da0ab --- /dev/null +++ b/server/lib/scanners/servarrTagFilters.ts @@ -0,0 +1,74 @@ +type ServarrInstance = { + id: number; + hostname: string; + port: number; + baseUrl?: string; + syncEnabled: boolean; + syncExcludedTags?: number[]; +}; + +type TaggedItem = { + tags?: readonly number[] | null; +}; + +export const getServarrSyncExcludedTagsForEndpoint = < + T extends ServarrInstance, +>( + instance: T, + instances: readonly T[] +): number[] => { + const excludedTags = new Set(); + + for (const candidate of instances) { + if ( + !candidate.syncEnabled || + candidate.hostname !== instance.hostname || + candidate.port !== instance.port || + candidate.baseUrl !== instance.baseUrl + ) { + continue; + } + + for (const tagId of candidate.syncExcludedTags ?? []) { + excludedTags.add(tagId); + } + } + + return [...excludedTags]; +}; + +export const getServarrSyncServerIdsForEndpoint = ( + instance: T, + instances: readonly T[] +): number[] => + instances + .filter( + (candidate) => + candidate.syncEnabled && + candidate.hostname === instance.hostname && + candidate.port === instance.port && + candidate.baseUrl === instance.baseUrl + ) + .map(({ id }) => id); + +export const partitionServarrItemsBySyncExcludedTags = ( + items: readonly T[], + excludedTagIds: readonly number[] | undefined +): { included: T[]; excluded: T[] } => { + const excludedTags = new Set(excludedTagIds ?? []); + const included: T[] = []; + const excluded: T[] = []; + + for (const item of items) { + if ( + Array.isArray(item.tags) && + item.tags.some((tagId) => excludedTags.has(tagId)) + ) { + excluded.push(item); + } else { + included.push(item); + } + } + + return { included, excluded }; +}; diff --git a/server/lib/scanners/sonarr/index.ts b/server/lib/scanners/sonarr/index.ts index f1719218b0..5d5c76e62f 100644 --- a/server/lib/scanners/sonarr/index.ts +++ b/server/lib/scanners/sonarr/index.ts @@ -19,7 +19,9 @@ import Media from '@server/entity/Media'; import MediaIdentifier, { MediaIdentifierProvider, } from '@server/entity/MediaIdentifier'; -import MediaRequest from '@server/entity/MediaRequest'; +import MediaRequest, { + runWithRequestAdmission, +} from '@server/entity/MediaRequest'; import Season from '@server/entity/Season'; import SeasonRequest, { isActiveSeasonRequest, @@ -33,7 +35,16 @@ import type { StatusBase, } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; +import { + reconcileExcludedServarrAvailability, + type ExcludedServarrAvailabilitySource, +} from '@server/lib/scanners/excludedServarrAvailability'; import { forEachMediaCleanupBatch } from '@server/lib/scanners/mediaCleanupBatches'; +import { + getServarrSyncExcludedTagsForEndpoint, + getServarrSyncServerIdsForEndpoint, + partitionServarrItemsBySyncExcludedTags, +} from '@server/lib/scanners/servarrTagFilters'; import { externalSeasonNumberFor, findMediaForTvdbId, @@ -48,7 +59,7 @@ import { getSettings, type SonarrSettings } from '@server/lib/settings'; import { is4kResolution } from '@server/lib/videoResolution'; import { getHttpErrorDetails } from '@server/utils/httpError'; import { uniqWith } from 'lodash'; -import type { FindOptionsWhere } from 'typeorm'; +import { In, type FindOptionsWhere } from 'typeorm'; type SyncStatus = StatusBase & { currentServer: SonarrSettings; @@ -66,6 +77,13 @@ class SonarrScanner private scanned4kTvdbIds: Set = new Set(); private scannedTmdbIds: Set = new Set(); private scanned4kTmdbIds: Set = new Set(); + private excludedTvdbIds: Set = new Set(); + private excluded4kTvdbIds: Set = new Set(); + private excludedSeries: { + tvdbId: number; + serverId: number; + format: 'standard' | '4k'; + }[] = []; private currentServiceTvdbIds: Set = new Set(); private currentServiceTmdbIds: Set = new Set(); private currentService4kTvdbIds: Set = new Set(); @@ -100,6 +118,9 @@ class SonarrScanner this.scanned4kTvdbIds.clear(); this.scannedTmdbIds.clear(); this.scanned4kTmdbIds.clear(); + this.excludedTvdbIds.clear(); + this.excluded4kTvdbIds.clear(); + this.excludedSeries = []; this.didScanStandard = false; this.didScan4k = false; this.serverReturnedEmpty = false; @@ -107,15 +128,22 @@ class SonarrScanner try { const fourKEnabled = getSettings().main.enable4k !== false; + const configuredServers = structuredClone( + settings.sonarr.filter((server) => fourKEnabled || !server.is4k) + ); this.servers = uniqWith( - structuredClone( - settings.sonarr.filter((server) => fourKEnabled || !server.is4k) - ), + configuredServers, (sonarrA, sonarrB) => sonarrA.hostname === sonarrB.hostname && sonarrA.port === sonarrB.port && sonarrA.baseUrl === sonarrB.baseUrl - ); + ).map((server) => ({ + ...server, + syncExcludedTags: getServarrSyncExcludedTagsForEndpoint( + server, + configuredServers + ), + })); this.resolutionAwareSingleServer = fourKEnabled && this.servers.filter((server) => server.syncEnabled).length === 1 && @@ -147,7 +175,7 @@ class SonarrScanner 'info' ); - this.items = await runWithServarrServiceSnapshot( + const serverItems = await runWithServarrServiceSnapshot( 'sonarr', server, async (current) => { @@ -159,9 +187,56 @@ class SonarrScanner } ); + // Keep the provider response separate: excluded results still prove + // that a scan completed and should not trigger the empty-library + // safety path below. + const { included, excluded } = + partitionServarrItemsBySyncExcludedTags( + serverItems, + server.syncExcludedTags + ); + this.items = included; + const server4k = this.enable4kShow && server.is4k; const scansBothResolutions = this.resolutionAwareSingleServer && this.enable4kShow; + for (const series of excluded) { + if (!Number.isSafeInteger(series.tvdbId) || series.tvdbId <= 0) { + continue; + } + + // One resolution-aware endpoint owns both availability tracks; + // retain the series identity so neither request track is orphaned. + if (this.resolutionAwareSingleServer) { + this.scannedTvdbIds.add(series.tvdbId); + this.scanned4kTvdbIds.add(series.tvdbId); + this.excludedTvdbIds.add(series.tvdbId); + this.excluded4kTvdbIds.add(series.tvdbId); + } else if (server4k) { + this.scanned4kTvdbIds.add(series.tvdbId); + this.excluded4kTvdbIds.add(series.tvdbId); + } else { + this.scannedTvdbIds.add(series.tvdbId); + this.excludedTvdbIds.add(series.tvdbId); + } + + const formats = scansBothResolutions + ? (['standard', '4k'] as const) + : ([server4k ? '4k' : 'standard'] as const); + for (const serverId of getServarrSyncServerIdsForEndpoint( + server, + configuredServers + )) { + for (const format of formats) { + this.excludedSeries.push({ + tvdbId: series.tvdbId, + serverId, + format, + }); + } + } + } + if (scansBothResolutions) { this.didScanStandard = true; this.didScan4k = true; @@ -171,7 +246,7 @@ class SonarrScanner this.didScanStandard = true; } - if (this.items.length === 0) { + if (serverItems.length === 0) { if (server4k) { this.server4kReturnedEmpty = true; } else { @@ -189,10 +264,10 @@ class SonarrScanner await this.loop(this.processSonarrSeries.bind(this), { sessionId }); - const hasCompleteMediaIdentity = this.items.every( + const hasCompleteMediaIdentity = serverItems.every( (series) => Number.isSafeInteger(series.tvdbId) && series.tvdbId > 0 ); - if (this.items.length > 0 && hasCompleteMediaIdentity) { + if (serverItems.length > 0 && hasCompleteMediaIdentity) { const formats = scansBothResolutions ? ([ { @@ -231,6 +306,11 @@ class SonarrScanner } } + await this.clearExcludedSeriesAvailability( + configuredServers, + fourKEnabled + ); + // Only run cleanup if all servers of this profile type have sync enabled. // If any server is skipped, we can't distinguish truly orphaned media from // media that exists on an unscanned server (e.g. separate instances for @@ -382,6 +462,95 @@ class SonarrScanner } } + private async clearExcludedSeriesAvailability( + configuredServers: SonarrSettings[], + fourKEnabled: boolean + ): Promise { + if (this.excludedSeries.length === 0) return; + + const excludedTvdbIds = [ + ...new Set(this.excludedSeries.map(({ tvdbId }) => tvdbId)), + ]; + const canonicalMedia: Media[] = []; + const matchingIdentifiers: MediaIdentifier[] = []; + for (let offset = 0; offset < excludedTvdbIds.length; offset += 500) { + const tvdbIdBatch = excludedTvdbIds.slice(offset, offset + 500); + const [canonicalBatch, identifierBatch] = await Promise.all([ + getRepository(Media).find({ + where: { mediaType: MediaType.TV, tvdbId: In(tvdbIdBatch) }, + }), + getRepository(MediaIdentifier).find({ + where: { + provider: MediaIdentifierProvider.TVDB, + value: In(tvdbIdBatch.map(String)), + media: { mediaType: MediaType.TV }, + }, + relations: { media: true }, + }), + ]); + canonicalMedia.push(...canonicalBatch); + matchingIdentifiers.push(...identifierBatch); + } + const mediaIdsByTvdbId = new Map>(); + const mediaItemsById = new Map(); + const addMediaId = (tvdbId: number, mediaId: number): void => { + const mediaIds = mediaIdsByTvdbId.get(tvdbId) ?? new Set(); + mediaIds.add(mediaId); + mediaIdsByTvdbId.set(tvdbId, mediaIds); + }; + + for (const media of canonicalMedia) { + mediaItemsById.set(media.id, media); + if (media.tvdbId != null) addMediaId(media.tvdbId, media.id); + } + for (const identifier of matchingIdentifiers) { + const tvdbId = Number(identifier.value); + if (identifier.media && Number.isSafeInteger(tvdbId) && tvdbId > 0) { + mediaItemsById.set(identifier.media.id, identifier.media); + addMediaId(tvdbId, identifier.media.id); + } + } + + const sources: ExcludedServarrAvailabilitySource[] = []; + for (const excluded of this.excludedSeries) { + for (const mediaId of mediaIdsByTvdbId.get(excluded.tvdbId) ?? []) { + sources.push({ + mediaId, + serverId: excluded.serverId, + format: excluded.format, + }); + } + } + + const mediaItems = [...new Set(sources.map(({ mediaId }) => mediaId))] + .map((mediaId) => mediaItemsById.get(mediaId)) + .filter((media): media is Media => media !== undefined); + + for (let offset = 0; offset < mediaItems.length; offset += 50) { + const batch = mediaItems.slice(offset, offset + 50); + const batchIds = new Set(batch.map(({ id }) => id)); + const batchSources = sources.filter((source) => + batchIds.has(source.mediaId) + ); + if (batchSources.length === 0) continue; + + await runWithRequestAdmission( + batch.map((media) => `request-media:${MediaType.TV}:${media.tmdbId}`), + () => + runWithServarrServiceSnapshots( + 'sonarr', + configuredServers.filter((server) => server.syncEnabled), + () => reconcileExcludedServarrAvailability('sonarr', batchSources), + { + requireExactAuthoritySet: true, + includeCurrent: (server) => + server.syncEnabled && (fourKEnabled || !server.is4k), + } + ) + ); + } + } + private async processSonarrSeriesForMedia( sonarrSeries: SonarrSeries, media: Media | undefined, @@ -972,16 +1141,30 @@ class SonarrScanner const visitedMedia = new Set(); const scannedTvdbIds = is4k ? this.scanned4kTvdbIds : this.scannedTvdbIds; const scannedTmdbIds = is4k ? this.scanned4kTmdbIds : this.scannedTmdbIds; + const excludedTvdbIds = is4k + ? this.excluded4kTvdbIds + : this.excludedTvdbIds; + const hasExcludedTvdbIds = excludedTvdbIds.size > 0; await forEachMediaCleanupBatch( where, async (media) => { if (visitedMedia.has(media.id)) return; visitedMedia.add(media.id); + const hasExcludedTvdbIdentifier = + hasExcludedTvdbIds && + Boolean( + media.identifiers?.some( + (identifier) => + identifier.provider === MediaIdentifierProvider.TVDB && + excludedTvdbIds.has(Number(identifier.value)) + ) + ); if ( !media.tvdbId || scannedTvdbIds.has(media.tvdbId) || - scannedTmdbIds.has(media.tmdbId) + scannedTmdbIds.has(media.tmdbId) || + hasExcludedTvdbIdentifier ) { return; } @@ -994,7 +1177,13 @@ class SonarrScanner ); } }, - { relations: { seasons: true, requests: { seasons: true } } } + { + relations: { + seasons: true, + requests: { seasons: true }, + ...(hasExcludedTvdbIds ? { identifiers: true } : {}), + }, + } ); } diff --git a/server/lib/serviceAdmission.ts b/server/lib/serviceAdmission.ts index 5e9158ae5e..38c5601738 100644 --- a/server/lib/serviceAdmission.ts +++ b/server/lib/serviceAdmission.ts @@ -56,8 +56,23 @@ export type ServarrServiceAuthority = Pick< 'id' | 'hostname' | 'port' | 'useSsl' | 'baseUrl' | 'apiKey' > & Partial> & + Partial<{ syncExcludedTags: number[] }> & Partial>; +const hasSameSyncExcludedTags = ( + current: readonly number[] | undefined, + snapshot: readonly number[] | undefined +): boolean => { + const currentTags = [...(current ?? [])].sort((left, right) => left - right); + const snapshotTags = [...(snapshot ?? [])].sort( + (left, right) => left - right + ); + return ( + currentTags.length === snapshotTags.length && + currentTags.every((tagId, index) => tagId === snapshotTags[index]) + ); +}; + export const hasSameServarrServiceAuthority = ( current: ServarrServiceAuthority, snapshot: ServarrServiceAuthority @@ -70,6 +85,10 @@ export const hasSameServarrServiceAuthority = ( current.apiKey === snapshot.apiKey && current.syncEnabled === snapshot.syncEnabled && Boolean(current.is4k) === Boolean(snapshot.is4k) && + hasSameSyncExcludedTags( + current.syncExcludedTags, + snapshot.syncExcludedTags + ) && (current.backend ?? 'readarr') === (snapshot.backend ?? 'readarr') && (current.serviceType ?? 'ebook') === (snapshot.serviceType ?? 'ebook'); diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index 50ffbe71a8..8ec5d91cdc 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -386,6 +386,8 @@ export interface ServiceRequestButtonSettings { export interface RadarrSettings extends DVRSettings, ServiceRequestButtonSettings { minimumAvailability: string; + /** Tags that exclude matching library entries from synchronization. */ + syncExcludedTags?: number[]; } /** Whisparr's scene-focused v3 API uses Radarr-shaped service settings. */ @@ -405,6 +407,8 @@ export interface SonarrSettings animeTags?: number[]; enableSeasonFolders: boolean; monitorNewItems: 'all' | 'none' | 'latest'; + /** Tags that exclude matching library entries from synchronization. */ + syncExcludedTags?: number[]; } export interface SportarrSettings { diff --git a/server/utils/servarrSettings.ts b/server/utils/servarrSettings.ts index 19ab8215a6..3824c29939 100644 --- a/server/utils/servarrSettings.ts +++ b/server/utils/servarrSettings.ts @@ -429,11 +429,20 @@ export const parseRadarrSettings = ( ); if ('error' in minimumAvailability) return minimumAvailability; + const syncExcludedTags = parseNumberArray( + settings.syncExcludedTags === undefined + ? (current?.syncExcludedTags ?? []) + : settings.syncExcludedTags, + 'syncExcludedTags' + ); + if ('error' in syncExcludedTags) return syncExcludedTags; + return { value: { ...parsed.value, ...requestButton.value, minimumAvailability: minimumAvailability.value, + syncExcludedTags: syncExcludedTags.value, }, }; }; @@ -479,6 +488,13 @@ export const parseSonarrSettings = ( const animeTags = parseNumberArray(settings.animeTags, 'animeTags'); if ('error' in animeTags) return animeTags; + const syncExcludedTags = parseNumberArray( + settings.syncExcludedTags === undefined + ? (current?.syncExcludedTags ?? []) + : settings.syncExcludedTags, + 'syncExcludedTags' + ); + if ('error' in syncExcludedTags) return syncExcludedTags; const activeAnimeProfileId = parseOptionalServiceId( settings.activeAnimeProfileId, 'activeAnimeProfileId' @@ -539,6 +555,7 @@ export const parseSonarrSettings = ( defaultMetadataLanguageId: defaultMetadataLanguageId.value, defaultSeasonType, animeTags: animeTags.value, + syncExcludedTags: syncExcludedTags.value, enableSeasonFolders: enableSeasonFolders.value, monitorNewItems, }, diff --git a/src/components/Settings/RadarrModal/index.tsx b/src/components/Settings/RadarrModal/index.tsx index eff4f20ee3..3861325678 100644 --- a/src/components/Settings/RadarrModal/index.tsx +++ b/src/components/Settings/RadarrModal/index.tsx @@ -4,6 +4,7 @@ import Field, { default as SettingsField, } from '@app/components/Settings/SettingsField'; import type { RadarrTestResponse } from '@app/components/Settings/SettingsServices'; +import SyncExcludedTagsField from '@app/components/Settings/SyncExcludedTagsField'; import { useSetupConnectionSuggestion } from '@app/context/SetupConnectionsContext'; import useToasts from '@app/hooks/useToasts'; import globalMessages from '@app/i18n/globalMessages'; @@ -93,6 +94,10 @@ const messages = defineMessages('components.Settings.RadarrModal', { 'For clickable links on media pages when the hostname is not reachable from outside your network.', syncEnabledHelp: 'Scan Radarr for existing media and request status so users cannot request content already available.', + syncExcludedTags: 'Exclude Tags from Scan', + syncExcludedTagsHelp: + 'Skip matching movies during this Radarr scan. Existing requests stay in SeerrNG, and a copy on another Radarr instance can still count as available.', + selectSyncExcludedTags: 'Select tags to exclude', enableSearchHelp: 'Automatically trigger a search in Radarr when a request is approved.', }); @@ -248,6 +253,7 @@ const RadarrModal = ({ onClose, radarr, onSave }: RadarrModalProps) => { rootFolder: radarr?.activeDirectory, minimumAvailability: radarr?.minimumAvailability ?? 'released', tags: radarr?.tags ?? [], + syncExcludedTags: radarr?.syncExcludedTags ?? [], isDefault: radarr?.isDefault ?? false, is4k: radarr?.is4k ?? false, externalUrl: radarr?.externalUrl, @@ -277,6 +283,7 @@ const RadarrModal = ({ onClose, radarr, onSave }: RadarrModalProps) => { is4k: values.is4k, minimumAvailability: values.minimumAvailability, tags: values.tags, + syncExcludedTags: values.syncExcludedTags, isDefault: values.isDefault, externalUrl: values.externalUrl, syncEnabled: values.syncEnabled, @@ -757,6 +764,26 @@ const RadarrModal = ({ onClose, radarr, onSave }: RadarrModalProps) => { {intl.formatMessage(messages.syncEnabledHelp)} + + setFieldValue('syncExcludedTags', tagIds) + } + />
+ + setFieldValue('syncExcludedTags', tagIds) + } + />