diff --git a/docs/using-seerr/settings/general.md b/docs/using-seerr/settings/general.md index 24bf19daa9..0c6d53f17d 100644 --- a/docs/using-seerr/settings/general.md +++ b/docs/using-seerr/settings/general.md @@ -84,3 +84,24 @@ This setting is **disabled** by default. When enabled, users will be able to submit requests for specific seasons of TV series. If disabled, users will only be able to submit requests for all unavailable seasons. This setting is **enabled** by default. + +## Ignored Path Patterns + +:::warning +**This is an advanced setting.** An incorrect pattern could cause wanted media to be excluded from scans. +::: + +Media whose file paths match any of the configured patterns will be skipped during library scans and availability checks, for both Plex and Jellyfin. + +If an item has multiple files or versions, only the matching ones are excluded. The item is only skipped entirely when every one of its files matches a pattern. + +Patterns are case-insensitive regular expressions matched against the full file path. Path separators are normalized to forward slashes, so patterns work across operating systems. To add a pattern, type it into the input field and press **Enter**. Invalid regex patterns are rejected with a warning and will not be saved. + +**Examples:** + +| Pattern | Effect | +| --------------- | --------------------------------------------------- | +| `placeholders/` | Ignores all files inside a `placeholders` directory | +| `.*trailers/.*` | Ignores all files inside any `trailers` directory | + +This setting is empty by default (no paths are ignored). diff --git a/package.json b/package.json index 3527768c28..73be37a9e1 100644 --- a/package.json +++ b/package.json @@ -92,6 +92,7 @@ "react-truncate-markup": "5.1.2", "react-use-clipboard": "1.0.9", "reflect-metadata": "^0.2.2", + "safe-regex": "2.1.1", "semver": "7.7.4", "sharp": "^0.35.5", "sqlite3": "^6.0.1", @@ -135,6 +136,7 @@ "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "@types/react-transition-group": "4.4.12", + "@types/safe-regex": "^1.1.6", "@types/semver": "7.7.1", "@types/supertest": "^7.2.0", "@types/swagger-ui-express": "4.1.8", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1565af9a0d..aacb0d6b6d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -187,6 +187,9 @@ importers: reflect-metadata: specifier: ^0.2.2 version: 0.2.2 + safe-regex: + specifier: 2.1.1 + version: 2.1.1 semver: specifier: 7.7.4 version: 7.7.4 @@ -311,6 +314,9 @@ importers: '@types/react-transition-group': specifier: 4.4.12 version: 4.4.12(@types/react@19.2.14) + '@types/safe-regex': + specifier: ^1.1.6 + version: 1.1.6 '@types/semver': specifier: 7.7.1 version: 7.7.1 @@ -2448,6 +2454,9 @@ packages: '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + '@types/safe-regex@1.1.6': + resolution: {integrity: sha512-CQ/uPB9fLOPKwDsrTeVbNIkwfUthTWOx0l6uIGwVFjZxv7e68pCW5gtTYFzdJi3EBJp8h8zYhJbTasAbX7gEMQ==} + '@types/semver@7.7.1': resolution: {integrity: sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==} @@ -6046,6 +6055,10 @@ packages: regenerate@1.5.0: resolution: {integrity: sha512-1s+CxXjJ71i7LNVy8nYwg47XV4y6lAnOEhsMtSKq3WpmPfhl9LuKlTqKIn/3yUpE8lBz+W+TT88Bxyhnr0U4yw==} + regexp-tree@0.1.27: + resolution: {integrity: sha512-iETxpjK6YoRWJG5o6hXLwvjYAoW+FEZn9os0PD/b6AP6xQwsa/Y7lCVgIixBbUPMfhu+i2LtdeAqVTgGlQarfA==} + hasBin: true + regexp.prototype.flags@1.5.4: resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} engines: {node: '>= 0.4'} @@ -6164,6 +6177,9 @@ packages: resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} engines: {node: '>= 0.4'} + safe-regex@2.1.1: + resolution: {integrity: sha512-rx+x8AMzKb5Q5lQ95Zoi6ZbJqwCLkqi3XuJXp5P3rT8OEc6sZCJG5AE5dU3lsgRr/F4Bs31jSlVN+j5KrsGu9A==} + safe-stable-stringify@2.5.0: resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} engines: {node: '>=10'} @@ -9329,6 +9345,8 @@ snapshots: dependencies: csstype: 3.2.4 + '@types/safe-regex@1.1.6': {} + '@types/semver@7.7.1': {} '@types/send@1.2.1': @@ -13529,6 +13547,8 @@ snapshots: regenerate@1.5.0: {} + regexp-tree@0.1.27: {} + regexp.prototype.flags@1.5.4: dependencies: call-bind: 1.0.9 @@ -13674,6 +13694,10 @@ snapshots: es-errors: 1.3.0 is-regex: 1.2.1 + safe-regex@2.1.1: + dependencies: + regexp-tree: 0.1.27 + safe-stable-stringify@2.5.0: {} safer-buffer@2.1.2: {} diff --git a/server/api/plexapi.ts b/server/api/plexapi.ts index 0837569b03..cd2e26467b 100644 --- a/server/api/plexapi.ts +++ b/server/api/plexapi.ts @@ -85,6 +85,7 @@ interface Media { container: string; videoFrameRate: string; videoProfile: string; + Part?: { file: string }[]; } interface PlexMetadataResponse { diff --git a/server/lib/availabilitySync.test.ts b/server/lib/availabilitySync.test.ts index 7e861e38c5..49855dde22 100644 --- a/server/lib/availabilitySync.test.ts +++ b/server/lib/availabilitySync.test.ts @@ -4,6 +4,7 @@ import { beforeEach, describe, it } from 'node:test'; import type { JellyfinLibraryItem, JellyfinLibraryItemExtended, + JellyfinMediaSource, } from '@server/api/jellyfin'; import JellyfinAPI from '@server/api/jellyfin'; import type { PlexMetadata } from '@server/api/plexapi'; @@ -45,7 +46,8 @@ let getSeasonsImpl: ( ) => Promise = async () => []; let getEpisodesImpl: ( seriesID: string, - seasonID: string + seasonID: string, + options?: { includeMediaInfo?: boolean } ) => Promise = async () => []; Object.defineProperty(JellyfinAPI.prototype, 'getSystemInfo', { @@ -74,8 +76,11 @@ Object.defineProperty(JellyfinAPI.prototype, 'getSeasons', { Object.defineProperty(JellyfinAPI.prototype, 'getEpisodes', { get() { - return async (seriesID: string, seasonID: string) => - getEpisodesImpl(seriesID, seasonID); + return async ( + seriesID: string, + seasonID: string, + options?: { includeMediaInfo?: boolean } + ) => getEpisodesImpl(seriesID, seasonID, options); }, set() {}, configurable: true, @@ -345,6 +350,23 @@ function fakeJellyfinShow( }; } +function fakeJellyfinMovie( + id: string, + tmdbId: string, + mediaSources?: JellyfinMediaSource[] +): JellyfinLibraryItemExtended { + return { + Name: 'Test Movie', + Id: id, + Type: 'Movie', + HasSubtitles: false, + LocationType: 'FileSystem', + MediaType: 'Video', + ProviderIds: { Tmdb: tmdbId }, + MediaSources: mediaSources, + }; +} + // --- Plex helpers --- function fakePlexSeason(seasonNumber: number, ratingKey: string): PlexMetadata { return { @@ -410,6 +432,70 @@ function fakePlexShow(ratingKey: string): PlexMetadata { }; } +function fakePlexMovie( + ratingKey: string, + media: PlexMetadata['Media'] +): PlexMetadata { + return { + ratingKey, + guid: `plex://movie/${ratingKey}`, + type: 'movie', + title: 'Test Movie', + Guid: [], + index: 1, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 0, + updatedAt: 0, + Media: media, + }; +} + +function fakePlexMedia( + file: string, + width: number, + videoResolution: string +): PlexMetadata['Media'][number] { + return { + id: width, + duration: 2400, + bitrate: 4000, + width, + height: width >= 2000 ? 2160 : 1080, + aspectRatio: 1.78, + audioChannels: 2, + audioCodec: 'aac', + videoCodec: 'h264', + videoResolution, + container: 'mkv', + videoFrameRate: '24p', + videoProfile: 'high', + Part: [{ file }], + }; +} + +function fakeJellyfinMediaSource( + path: string, + width: number +): JellyfinMediaSource { + return { + Protocol: 'File', + Id: `${path}-${width}`, + Path: path, + Type: 'Default', + VideoType: 'VideoFile', + MediaStreams: [ + { + Codec: 'h264', + Type: 'Video', + Width: width, + Height: width >= 2000 ? 2160 : 1080, + DisplayTitle: `${width}p`, + }, + ], + }; +} + // --- Sonarr helpers --- function fakeSonarrSeasons( totalSeasons: number, @@ -469,6 +555,7 @@ describe('AvailabilitySync', () => { season_number: i + 1, })) ); + getSettings().main.ignoredPathPatterns = []; const userRepository = getRepository(User); const existingAdmin = await userRepository.findOne({ where: { id: 1 } }); @@ -2315,4 +2402,532 @@ describe('AvailabilitySync', () => { ); }); }); + + describe('ignored 4K path handling', () => { + it('removes stale Plex 4K movie availability when only ignored 4K media remains', async () => { + configurePlex(); + getSettings().main.ignoredPathPatterns = ['placeholders/']; + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 3000; + media.mediaType = MediaType.MOVIE; + media.status = MediaStatus.UNKNOWN; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey4k = 'plex-mixed-movie-rk'; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-mixed-movie-rk') { + return fakePlexMovie('plex-mixed-movie-rk', [ + fakePlexMedia( + '/library/movies/Test Movie (2024)/movie.mkv', + 1920, + '1080' + ), + fakePlexMedia( + '/library/movies/placeholders/Test Movie (2024)-4k.mkv', + 3840, + '4k' + ), + ]); + } + + throw new Error('404'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3000 }, + }); + + assert.strictEqual(updated.status4k, MediaStatus.DELETED); + assert.strictEqual(updated.ratingKey4k, null); + }); + + it('removes stale Plex 4K season availability when only ignored 4K media remains', async () => { + configurePlex(); + getSettings().main.ignoredPathPatterns = ['placeholders/']; + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 3004; + media.mediaType = MediaType.TV; + media.status = MediaStatus.UNKNOWN; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey4k = 'plex-mixed-show-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.UNKNOWN, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-mixed-show-rk') { + return fakePlexShow('plex-mixed-show-rk'); + } + + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-mixed-show-rk') { + return [fakePlexSeason(1, 'plex-mixed-show-s1-rk')]; + } + + if (key === 'plex-mixed-show-s1-rk') { + return [ + { + ratingKey: 'plex-mixed-show-s1-e1-rk', + guid: 'plex://episode/plex-mixed-show-s1-e1-rk', + type: 'movie' as const, + title: 'Episode 1', + Guid: [], + index: 1, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 0, + updatedAt: 0, + Media: [ + fakePlexMedia( + '/library/shows/Test Show/Season 01/S01E01.mkv', + 1920, + '1080' + ), + fakePlexMedia( + '/library/shows/placeholders/Test Show/Season 01/S01E01-4k.mkv', + 3840, + '4k' + ), + ], + }, + ]; + } + + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3004 }, + relations: ['seasons'], + }); + + assert.strictEqual(updated.status4k, MediaStatus.DELETED); + assert.strictEqual(updated.ratingKey4k, null); + assert.strictEqual(updated.seasons[0].status4k, MediaStatus.DELETED); + }); + + it('keeps Plex 4K show availability when another season lookup fails during 4K validation', async () => { + configurePlex(); + getSettings().main.ignoredPathPatterns = ['placeholders/']; + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 3005; + media.mediaType = MediaType.TV; + media.status = MediaStatus.UNKNOWN; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey4k = 'plex-4k-fallback-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.UNKNOWN, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-4k-fallback-rk') { + return fakePlexShow('plex-4k-fallback-rk'); + } + + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-4k-fallback-rk') { + return [ + fakePlexSeason(1, 'plex-4k-fallback-s1-rk'), + fakePlexSeason(2, 'plex-4k-fallback-s2-rk'), + ]; + } + + if (key === 'plex-4k-fallback-s1-rk') { + throw new Error('Connection refused'); + } + + if (key === 'plex-4k-fallback-s2-rk') { + return [ + { + ratingKey: 'plex-4k-fallback-s2-e1-rk', + guid: 'plex://episode/plex-4k-fallback-s2-e1-rk', + type: 'movie' as const, + title: 'Episode 1', + Guid: [], + index: 1, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 0, + updatedAt: 0, + Media: [ + fakePlexMedia( + '/library/shows/Test Show/Season 02/S02E01.mkv', + 1920, + '1080' + ), + ], + }, + ]; + } + + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3005 }, + relations: ['seasons'], + }); + + assert.strictEqual(updated.status4k, MediaStatus.AVAILABLE); + assert.strictEqual(updated.ratingKey4k, 'plex-4k-fallback-rk'); + assert.strictEqual(updated.seasons[0].status4k, MediaStatus.AVAILABLE); + }); + + it('removes stale Jellyfin 4K movie availability when only ignored 4K sources remain', async () => { + configureJellyfin(); + getSettings().main.ignoredPathPatterns = ['placeholders/']; + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 3003; + media.mediaType = MediaType.MOVIE; + media.status = MediaStatus.UNKNOWN; + media.status4k = MediaStatus.AVAILABLE; + media.jellyfinMediaId4k = 'jellyfin-mixed-movie-id'; + await mediaRepository.save(media); + + getItemDataImpl = async (id: string) => { + if (id === 'jellyfin-mixed-movie-id') { + return fakeJellyfinMovie('jellyfin-mixed-movie-id', '3003', [ + fakeJellyfinMediaSource( + '/library/movies/Test Movie (2024)/movie.mkv', + 1920 + ), + fakeJellyfinMediaSource( + '/library/movies/placeholders/Test Movie (2024)-4k.mkv', + 3840 + ), + ]); + } + + return undefined; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3003 }, + }); + + assert.strictEqual(updated.status4k, MediaStatus.DELETED); + assert.strictEqual(updated.jellyfinMediaId4k, null); + }); + + it('removes stale Jellyfin 4K season availability when only ignored 4K sources remain', async () => { + configureJellyfin(); + getSettings().main.ignoredPathPatterns = ['placeholders/']; + let includeMediaInfoRequested = false; + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 3001; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.jellyfinMediaId = 'jellyfin-mixed-show-id'; + media.jellyfinMediaId4k = 'jellyfin-mixed-show-id'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getItemDataImpl = async (id: string) => { + if (id === 'jellyfin-mixed-show-id') { + return fakeJellyfinShow('jellyfin-mixed-show-id', '3001'); + } + + return undefined; + }; + + getSeasonsImpl = async (seriesID: string) => { + if (seriesID === 'jellyfin-mixed-show-id') { + return [fakeJellyfinSeason(1, 'jellyfin-mixed-show-s1-id')]; + } + + return []; + }; + + getEpisodesImpl = async ( + _seriesID: string, + seasonID: string, + options?: { includeMediaInfo?: boolean } + ) => { + if (seasonID === 'jellyfin-mixed-show-s1-id') { + includeMediaInfoRequested = options?.includeMediaInfo === true; + + return [ + { + Name: 'Episode 1', + Id: 'jellyfin-mixed-show-s1-e1-id', + IndexNumber: 1, + Type: 'Episode' as const, + HasSubtitles: false, + LocationType: 'FileSystem' as const, + MediaType: 'Video', + MediaSources: [ + fakeJellyfinMediaSource( + '/library/shows/Test Show/Season 01/S01E01.mkv', + 1920 + ), + fakeJellyfinMediaSource( + '/library/shows/placeholders/Test Show/Season 01/S01E01-4k.mkv', + 3840 + ), + ], + } as JellyfinLibraryItemExtended, + ]; + } + + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3001 }, + relations: ['seasons'], + }); + + assert.strictEqual(updated.status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.status4k, MediaStatus.DELETED); + assert.strictEqual(updated.jellyfinMediaId4k, null); + assert.strictEqual(updated.seasons[0].status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.seasons[0].status4k, MediaStatus.DELETED); + assert.strictEqual(includeMediaInfoRequested, true); + }); + + it('keeps Jellyfin 4K season availability when an unignored 4K source remains', async () => { + configureJellyfin(); + getSettings().main.ignoredPathPatterns = ['placeholders/']; + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 3002; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.jellyfinMediaId = 'jellyfin-4k-show-id'; + media.jellyfinMediaId4k = 'jellyfin-4k-show-id'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getItemDataImpl = async (id: string) => { + if (id === 'jellyfin-4k-show-id') { + return fakeJellyfinShow('jellyfin-4k-show-id', '3002'); + } + + return undefined; + }; + + getSeasonsImpl = async (seriesID: string) => { + if (seriesID === 'jellyfin-4k-show-id') { + return [fakeJellyfinSeason(1, 'jellyfin-4k-show-s1-id')]; + } + + return []; + }; + + getEpisodesImpl = async (_seriesID: string, seasonID: string) => { + if (seasonID === 'jellyfin-4k-show-s1-id') { + return [ + { + Name: 'Episode 1', + Id: 'jellyfin-4k-show-s1-e1-id', + IndexNumber: 1, + Type: 'Episode' as const, + HasSubtitles: false, + LocationType: 'FileSystem' as const, + MediaType: 'Video', + MediaSources: [ + fakeJellyfinMediaSource( + '/library/shows/Test Show/Season 01/S01E01-4k.mkv', + 3840 + ), + fakeJellyfinMediaSource( + '/library/shows/placeholders/Test Show/Season 01/S01E01-placeholder.mkv', + 1920 + ), + ], + } as JellyfinLibraryItemExtended, + ]; + } + + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 3002 }, + relations: ['seasons'], + }); + + assert.strictEqual(updated.status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.status4k, MediaStatus.AVAILABLE); + assert.strictEqual(updated.jellyfinMediaId4k, 'jellyfin-4k-show-id'); + assert.strictEqual(updated.seasons[0].status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.seasons[0].status4k, MediaStatus.AVAILABLE); + }); + }); + + describe('season listing ambiguity handling', () => { + it('keeps Plex show existence when season metadata is non-empty but non-matching', async () => { + configurePlex(); + + const media = new Media(); + media.tmdbId = 4000; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-ambiguous-show-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + + getMetadataImpl = async (key: string) => { + if (key === 'plex-ambiguous-show-rk') { + return fakePlexShow('plex-ambiguous-show-rk'); + } + + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-ambiguous-show-rk') { + return [fakePlexSeason(2, 'plex-ambiguous-show-s2-rk')]; + } + + return []; + }; + + const sync = availabilitySync as unknown as { + plexClient: PlexAPI; + plexSeasonsCache: Record; + plexEpisodeExistsCache: Record; + mediaExistsInPlex: ( + media: Media, + is4k: boolean + ) => Promise<{ + existsInPlex: boolean; + seasonsMap?: Map; + }>; + }; + + sync.plexClient = new PlexAPI({ plexToken: 'test-plex-token' }); + sync.plexSeasonsCache = {}; + sync.plexEpisodeExistsCache = {}; + + const result = await sync.mediaExistsInPlex(media, false); + + assert.strictEqual(result.existsInPlex, true); + assert.strictEqual(result.seasonsMap?.size ?? 0, 0); + }); + + it('keeps Jellyfin show existence when season metadata is non-empty but non-matching', async () => { + configureJellyfin(); + + const media = new Media(); + media.tmdbId = 4001; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.jellyfinMediaId = 'jellyfin-ambiguous-show-id'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + + getItemDataImpl = async (id: string) => { + if (id === 'jellyfin-ambiguous-show-id') { + return fakeJellyfinShow('jellyfin-ambiguous-show-id', '4001'); + } + + return undefined; + }; + + getSeasonsImpl = async (seriesID: string) => { + if (seriesID === 'jellyfin-ambiguous-show-id') { + return [fakeJellyfinSeason(2, 'jellyfin-ambiguous-show-s2-id')]; + } + + return []; + }; + + const sync = availabilitySync as unknown as { + jellyfinClient: JellyfinAPI; + jellyfinSeasonsCache: Record; + jellyfinEpisodeExistsCache: Record; + mediaExistsInJellyfin: ( + media: Media, + is4k: boolean + ) => Promise<{ + existsInJellyfin: boolean; + seasonsMap?: Map; + }>; + }; + + sync.jellyfinClient = new JellyfinAPI( + 'http://localhost', + 'test-api-key', + 'test-device-id' + ); + sync.jellyfinSeasonsCache = {}; + sync.jellyfinEpisodeExistsCache = {}; + + const result = await sync.mediaExistsInJellyfin(media, false); + + assert.strictEqual(result.existsInJellyfin, true); + assert.strictEqual(result.seasonsMap?.size ?? 0, 0); + }); + }); }); diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 4a700ef355..5e8d57532e 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -1,4 +1,7 @@ -import type { JellyfinLibraryItem } from '@server/api/jellyfin'; +import type { + JellyfinLibraryItem, + JellyfinLibraryItemExtended, +} from '@server/api/jellyfin'; import JellyfinAPI from '@server/api/jellyfin'; import type { PlexMetadata } from '@server/api/plexapi'; import PlexAPI from '@server/api/plexapi'; @@ -21,6 +24,10 @@ import type { RadarrSettings, SonarrSettings } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import { getHostname } from '@server/utils/getHostname'; +import { + getUnignoredJellyfinMediaSources, + getUnignoredPlexMedia, +} from '@server/utils/mediaFilter'; class AvailabilitySync { public running = false; @@ -876,6 +883,7 @@ class AvailabilitySync { const ratingKey4k = media.ratingKey4k; let existsInPlex = false; let preventSeasonSearch = false; + let receivedEmptySeasonsMetadata = false; // Check each plex instance to see if the media still exists // If found, we will assume the media exists and prevent removal @@ -886,9 +894,13 @@ class AvailabilitySync { if (ratingKey && !is4k) { plexMedia = await this.plexClient?.getMetadata(ratingKey); - if (media.mediaType === 'tv') { - this.plexSeasonsCache[ratingKey] = + if (media.mediaType === 'tv' && plexMedia !== undefined) { + const seasonsMetadata = await this.plexClient?.getChildrenMetadata(ratingKey); + + this.plexSeasonsCache[ratingKey] = seasonsMetadata ?? []; + receivedEmptySeasonsMetadata = + Array.isArray(seasonsMetadata) && seasonsMetadata.length === 0; } if ( @@ -896,7 +908,9 @@ class AvailabilitySync { media.mediaType === 'movie' && this.enable4kMovie && plexMedia.Media?.length && - !plexMedia.Media.some((mediaItem) => (mediaItem.width ?? 0) < 2000) + !getUnignoredPlexMedia(plexMedia.Media).some( + (mediaItem) => (mediaItem.width ?? 0) < 2000 + ) ) { plexMedia = undefined; } @@ -905,9 +919,13 @@ class AvailabilitySync { if (ratingKey4k && is4k) { plexMedia = await this.plexClient?.getMetadata(ratingKey4k); - if (media.mediaType === 'tv') { - this.plexSeasonsCache[ratingKey4k] = + if (media.mediaType === 'tv' && plexMedia !== undefined) { + const seasonsMetadata = await this.plexClient?.getChildrenMetadata(ratingKey4k); + + this.plexSeasonsCache[ratingKey4k] = seasonsMetadata ?? []; + receivedEmptySeasonsMetadata = + Array.isArray(seasonsMetadata) && seasonsMetadata.length === 0; } if (plexMedia) { @@ -915,7 +933,9 @@ class AvailabilitySync { plexMedia && media.mediaType === 'movie' && plexMedia.Media?.length && - !plexMedia.Media.some((mediaItem) => (mediaItem.width ?? 0) >= 2000) + !getUnignoredPlexMedia(plexMedia.Media).some( + (mediaItem) => (mediaItem.width ?? 0) >= 2000 + ) ) { plexMedia = undefined; } @@ -925,6 +945,7 @@ class AvailabilitySync { if (cachedSeasons?.length) { let has4kInAnySeason = false; let verifiedAnySeason = false; + let hadSeasonLookupFailure = false; for (const season of cachedSeasons) { try { const episodes = await this.plexClient?.getChildrenMetadata( @@ -934,7 +955,7 @@ class AvailabilitySync { verifiedAnySeason = true; } const has4kEpisode = episodes?.some((episode) => - episode.Media?.some( + getUnignoredPlexMedia(episode.Media ?? []).some( (mediaItem) => (mediaItem.width ?? 0) >= 2000 ) ); @@ -943,10 +964,15 @@ class AvailabilitySync { break; } } catch { + hadSeasonLookupFailure = true; // If we can't fetch episodes for a season, continue checking other seasons } } - if (verifiedAnySeason && !has4kInAnySeason) { + if ( + verifiedAnySeason && + !hadSeasonLookupFailure && + !has4kInAnySeason + ) { plexMedia = undefined; } } @@ -954,6 +980,14 @@ class AvailabilitySync { } } + if (plexMedia && media.mediaType === 'movie' && plexMedia.Media?.length) { + const movieMedia = getUnignoredPlexMedia(plexMedia.Media); + + if (movieMedia.length === 0) { + plexMedia = undefined; + } + } + if (plexMedia) { existsInPlex = true; } @@ -978,6 +1012,16 @@ class AvailabilitySync { // we will have to prevent the season check from happening if (media.mediaType === 'tv') { const seasonsMap: Map = new Map(); + let seasonsConsidered = 0; + let allConsideredSeasonsHadMetadata = true; + + const seasonsMetadata = is4k + ? ratingKey4k + ? (this.plexSeasonsCache[ratingKey4k] ?? []) + : [] + : ratingKey + ? (this.plexSeasonsCache[ratingKey] ?? []) + : []; if (!preventSeasonSearch) { const filteredSeasons = media.seasons.filter( @@ -987,7 +1031,14 @@ class AvailabilitySync { MediaStatus.PARTIALLY_AVAILABLE ); + seasonsConsidered = filteredSeasons.length; + for (const season of filteredSeasons) { + const hasSeasonMetadata = seasonsMetadata.some( + (plexSeason) => plexSeason.index === season.seasonNumber + ); + allConsideredSeasonsHadMetadata &&= hasSeasonMetadata; + const seasonExists = await this.seasonExistsInPlex( media, season, @@ -1000,6 +1051,16 @@ class AvailabilitySync { } } + if ( + existsInPlex && + seasonsMap.size === 0 && + !preventSeasonSearch && + seasonsConsidered > 0 && + (receivedEmptySeasonsMetadata || allConsideredSeasonsHadMetadata) + ) { + existsInPlex = false; + } + return { existsInPlex, seasonsMap }; } @@ -1013,7 +1074,6 @@ class AvailabilitySync { ): Promise { const ratingKey = media.ratingKey; const ratingKey4k = media.ratingKey4k; - let seasonExistsInPlex = false; let plexSeasons: PlexMetadata[] | undefined; @@ -1029,43 +1089,49 @@ class AvailabilitySync { (plexSeason) => plexSeason.index === season.seasonNumber ); - if (seasonMeta) { - const cacheKey = `${is4k ? '4k' : 'std'}-${seasonMeta.ratingKey}`; + if (!seasonMeta) { + return false; + } - if (cacheKey in this.plexEpisodeExistsCache) { - seasonExistsInPlex = this.plexEpisodeExistsCache[cacheKey]; - } else { - try { - // Season metadata exists, but we need to verify it has actual - // episode files. Plex can keep empty season entries. - const episodes = await this.plexClient?.getChildrenMetadata( - seasonMeta.ratingKey - ); + const cacheKey = `${is4k ? '4k' : 'std'}-${seasonMeta.ratingKey}`; - const episodeVersions = - episodes?.flatMap((episode) => episode.Media ?? []) ?? []; + if (cacheKey in this.plexEpisodeExistsCache) { + return this.plexEpisodeExistsCache[cacheKey]; + } - if (is4k) { - seasonExistsInPlex = episodeVersions.some( - (mediaItem) => (mediaItem.width ?? 0) >= 2000 - ); - } else if (this.enable4kShow) { - seasonExistsInPlex = episodeVersions.some( - (mediaItem) => (mediaItem.width ?? 0) < 2000 - ); - } else { - seasonExistsInPlex = episodeVersions.length > 0; - } - } catch { - // If we can't fetch episodes, assume the season exists - // to avoid false removal - seasonExistsInPlex = true; - } + let seasonExistsInPlex = false; + + try { + // Season metadata exists, but we need to verify it has actual + // episode files. Plex can keep empty season entries. + const episodes = await this.plexClient?.getChildrenMetadata( + seasonMeta.ratingKey + ); + + const episodeVersions = + episodes?.flatMap((episode) => + getUnignoredPlexMedia(episode.Media ?? []) + ) ?? []; - this.plexEpisodeExistsCache[cacheKey] = seasonExistsInPlex; + if (is4k) { + seasonExistsInPlex = episodeVersions.some( + (mediaItem) => (mediaItem.width ?? 0) >= 2000 + ); + } else if (this.enable4kShow) { + seasonExistsInPlex = episodeVersions.some( + (mediaItem) => (mediaItem.width ?? 0) < 2000 + ); + } else { + seasonExistsInPlex = episodeVersions.length > 0; } + } catch { + // If we can't fetch episodes, assume the season exists + // to avoid false removal + seasonExistsInPlex = true; } + this.plexEpisodeExistsCache[cacheKey] = seasonExistsInPlex; + return seasonExistsInPlex; } @@ -1078,19 +1144,23 @@ class AvailabilitySync { const ratingKey4k = media.jellyfinMediaId4k; let existsInJellyfin = false; let preventSeasonSearch = false; + let receivedEmptySeasonsMetadata = false; // Check each jellyfin 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 mediaExistsInJellyfin try { - let jellyfinMedia: JellyfinLibraryItem | undefined; + let jellyfinMedia: JellyfinLibraryItemExtended | undefined; if (ratingKey && !is4k) { jellyfinMedia = await this.jellyfinClient?.getItemData(ratingKey); if (media.mediaType === 'tv' && jellyfinMedia !== undefined) { - this.jellyfinSeasonsCache[ratingKey] = + const seasonsMetadata = await this.jellyfinClient?.getSeasons(ratingKey); + + this.jellyfinSeasonsCache[ratingKey] = seasonsMetadata; + receivedEmptySeasonsMetadata = seasonsMetadata.length === 0; } } @@ -1098,8 +1168,31 @@ class AvailabilitySync { jellyfinMedia = await this.jellyfinClient?.getItemData(ratingKey4k); if (media.mediaType === 'tv' && jellyfinMedia !== undefined) { - this.jellyfinSeasonsCache[ratingKey4k] = + const seasonsMetadata = await this.jellyfinClient?.getSeasons(ratingKey4k); + + this.jellyfinSeasonsCache[ratingKey4k] = seasonsMetadata; + receivedEmptySeasonsMetadata = seasonsMetadata.length === 0; + } + } + + if (jellyfinMedia && media.mediaType === 'movie') { + const mediaSources = getUnignoredJellyfinMediaSources( + jellyfinMedia.MediaSources + ); + + if (mediaSources.length === 0) { + jellyfinMedia = undefined; + } else if ( + is4k && + !mediaSources.some((mediaSource) => + mediaSource.MediaStreams.some( + (mediaStream) => + mediaStream.Type === 'Video' && (mediaStream.Width ?? 0) > 2000 + ) + ) + ) { + jellyfinMedia = undefined; } } @@ -1127,6 +1220,16 @@ class AvailabilitySync { // we will have to prevent the season check from happening if (media.mediaType === 'tv') { const seasonsMap: Map = new Map(); + let seasonsConsidered = 0; + let allConsideredSeasonsHadMetadata = true; + + const seasonsMetadata = is4k + ? ratingKey4k + ? (this.jellyfinSeasonsCache[ratingKey4k] ?? []) + : [] + : ratingKey + ? (this.jellyfinSeasonsCache[ratingKey] ?? []) + : []; if (!preventSeasonSearch) { const filteredSeasons = media.seasons.filter( @@ -1136,7 +1239,15 @@ class AvailabilitySync { MediaStatus.PARTIALLY_AVAILABLE ); + seasonsConsidered = filteredSeasons.length; + for (const season of filteredSeasons) { + const hasSeasonMetadata = seasonsMetadata.some( + (jellyfinSeason) => + jellyfinSeason.IndexNumber === season.seasonNumber + ); + allConsideredSeasonsHadMetadata &&= hasSeasonMetadata; + const seasonExists = await this.seasonExistsInJellyfin( media, season, @@ -1149,6 +1260,16 @@ class AvailabilitySync { } } + if ( + existsInJellyfin && + seasonsMap.size === 0 && + !preventSeasonSearch && + seasonsConsidered > 0 && + (receivedEmptySeasonsMetadata || allConsideredSeasonsHadMetadata) + ) { + existsInJellyfin = false; + } + return { existsInJellyfin, seasonsMap }; } @@ -1162,7 +1283,7 @@ class AvailabilitySync { ): Promise { const ratingKey = media.jellyfinMediaId; const ratingKey4k = media.jellyfinMediaId4k; - let seasonExistsInJellyfin = false; + const activeKey = is4k ? ratingKey4k : ratingKey; let jellyfinSeasons: JellyfinLibraryItem[] | undefined; @@ -1178,38 +1299,65 @@ class AvailabilitySync { (jellyfinSeason) => jellyfinSeason.IndexNumber === season.seasonNumber ); - if (seasonMeta) { - const seriesId = is4k ? ratingKey4k : ratingKey; + if (!seasonMeta || !activeKey) { + return false; + } - if (seriesId) { - const cacheKey = `${seriesId}-${seasonMeta.Id}`; + const cacheKey = `${activeKey}-${seasonMeta.Id}`; + const hasIgnoredPatterns = + (getSettings().main.ignoredPathPatterns ?? []).length > 0; - if (cacheKey in this.jellyfinEpisodeExistsCache) { - seasonExistsInJellyfin = this.jellyfinEpisodeExistsCache[cacheKey]; - } else { - try { - // Season metadata exists, but we need to verify it has actual - // episode files. Jellyfin keeps season entries even after all - // episodes are deleted. getEpisodes already filters out - // virtual episodes. - const episodes = await this.jellyfinClient.getEpisodes( - seriesId, - seasonMeta.Id - ); - - seasonExistsInJellyfin = episodes.length > 0; - } catch { - // If we can't fetch episodes, assume the season exists - // to avoid false removal - seasonExistsInJellyfin = true; - } + if (cacheKey in this.jellyfinEpisodeExistsCache) { + if (!this.jellyfinEpisodeExistsCache[cacheKey]) { + return false; + } - this.jellyfinEpisodeExistsCache[cacheKey] = seasonExistsInJellyfin; - } + if (!hasIgnoredPatterns && !is4k) { + return true; } } - return seasonExistsInJellyfin; + try { + const episodes = await this.jellyfinClient?.getEpisodes( + activeKey, + seasonMeta.Id, + hasIgnoredPatterns || is4k ? { includeMediaInfo: true } : undefined + ); + + const hasEpisodes = (episodes?.length ?? 0) > 0; + + this.jellyfinEpisodeExistsCache[cacheKey] = hasEpisodes; + + if (!hasEpisodes || (!hasIgnoredPatterns && !is4k)) { + return hasEpisodes; + } + + return episodes.some((episode) => { + const mediaSources = + 'MediaSources' in episode + ? getUnignoredJellyfinMediaSources(episode.MediaSources) + : []; + + return is4k + ? mediaSources.some((mediaSource) => + mediaSource.MediaStreams.some( + (mediaStream) => + mediaStream.Type === 'Video' && + (mediaStream.Width ?? 0) > 2000 + ) + ) + : mediaSources.length > 0; + }); + } catch (ex) { + logger.debug( + `Failed to check ignored paths for Jellyfin season ${season.seasonNumber} [TMDB ID ${media.tmdbId}].`, + { + errorMessage: (ex as Error).message, + label: 'AvailabilitySync', + } + ); + return true; + } } } diff --git a/server/lib/scanners/jellyfin/index.ts b/server/lib/scanners/jellyfin/index.ts index f7b22f3386..7d54f2c7ee 100644 --- a/server/lib/scanners/jellyfin/index.ts +++ b/server/lib/scanners/jellyfin/index.ts @@ -24,6 +24,11 @@ import BaseScanner from '@server/lib/scanners/baseScanner'; import type { Library } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; import { getHostname } from '@server/utils/getHostname'; +import { + getJellyfinFilePaths, + getUnignoredJellyfinMediaSources, + isPathIgnored, +} from '@server/utils/mediaFilter'; import { uniqWith } from 'lodash'; interface JellyfinSyncStatus extends StatusBase { @@ -127,7 +132,18 @@ class JellyfinScanner const { tmdbId, imdbId, metadata } = extracted; - const has4k = metadata.MediaSources?.some((MediaSource) => { + const filteredSources = getUnignoredJellyfinMediaSources( + metadata.MediaSources + ); + + if (filteredSources.length === 0) { + this.log( + `Skipping movie ${metadata.Name} (file path matched ignore pattern)` + ); + return; + } + + const has4k = filteredSources.some((MediaSource) => { return MediaSource.MediaStreams.filter( (MediaStream) => MediaStream.Type === 'Video' ).some((MediaStream) => { @@ -135,7 +151,7 @@ class JellyfinScanner }); }); - const hasOtherResolution = metadata.MediaSources?.some((MediaSource) => { + const hasOtherResolution = filteredSources.some((MediaSource) => { return MediaSource.MediaStreams.filter( (MediaStream) => MediaStream.Type === 'Video' ).some((MediaStream) => { @@ -288,6 +304,9 @@ class JellyfinScanner const filteredSeasons = settings.main.enableSpecialEpisodes ? seasons : seasons.filter((sn) => sn.season_number !== 0); + const hasIgnoredPatterns = + (settings.main.ignoredPathPatterns ?? []).length > 0; + const needMediaInfo = this.enable4kShow || hasIgnoredPatterns; for (const season of filteredSeasons) { const matchedJellyfinSeason = jellyfinSeasons.find((md) => { @@ -310,47 +329,40 @@ class JellyfinScanner let totalStandard = 0; let total4k = 0; - if (!this.enable4kShow) { - const episodes = await this.jfClient.getEpisodes( - Id, - matchedJellyfinSeason.Id - ); - - for (const episode of episodes) { - let episodeCount = 1; + const allEpisodes = await this.jfClient.getEpisodes( + Id, + matchedJellyfinSeason.Id, + needMediaInfo ? { includeMediaInfo: true } : undefined + ); + + const episodes = allEpisodes.filter((episode) => { + const paths = + 'MediaSources' in episode + ? getJellyfinFilePaths(episode.MediaSources) + : []; + return !isPathIgnored(paths); + }); - // count number of combined episodes - if ( - episode.IndexNumber !== undefined && - episode.IndexNumberEnd !== undefined - ) { - episodeCount = - episode.IndexNumberEnd - episode.IndexNumber + 1; - } + for (const episode of episodes) { + let episodeCount = 1; - totalStandard += episodeCount; + if ( + episode.IndexNumber !== undefined && + episode.IndexNumberEnd !== undefined + ) { + episodeCount = episode.IndexNumberEnd - episode.IndexNumber + 1; } - } else { - // 4K detection enabled - request media info to check resolution - const episodes = await this.jfClient.getEpisodes( - Id, - matchedJellyfinSeason.Id, - { includeMediaInfo: true } - ); - for (const episode of episodes) { - let episodeCount = 1; + if (!this.enable4kShow) { + totalStandard += episodeCount; + } else { + const extEpisode = episode as JellyfinLibraryItemExtended; - // count number of combined episodes - if ( - episode.IndexNumber !== undefined && - episode.IndexNumberEnd !== undefined - ) { - episodeCount = - episode.IndexNumberEnd - episode.IndexNumber + 1; - } + const episodeFilteredSources = getUnignoredJellyfinMediaSources( + extEpisode.MediaSources + ); - const has4k = episode.MediaSources?.some((MediaSource) => + const has4k = episodeFilteredSources.some((MediaSource) => MediaSource.MediaStreams.some( (MediaStream) => MediaStream.Type === 'Video' && @@ -358,7 +370,7 @@ class JellyfinScanner ) ); - const hasStandard = episode.MediaSources?.some((MediaSource) => + const hasStandard = episodeFilteredSources.some((MediaSource) => MediaSource.MediaStreams.some( (MediaStream) => MediaStream.Type === 'Video' && @@ -411,18 +423,24 @@ class JellyfinScanner } } - await this.processShow( - tvShow.id, - tvShow.external_ids?.tvdb_id, - processableSeasons, - { - mediaAddedAt: metadata.DateCreated - ? new Date(metadata.DateCreated) - : undefined, - jellyfinMediaId: Id, - title: tvShow.name, - } + const hasAnyEpisodes = processableSeasons.some( + (s) => s.episodes > 0 || s.episodes4k > 0 ); + + if (hasAnyEpisodes || !hasIgnoredPatterns) { + await this.processShow( + tvShow.id, + tvShow.external_ids?.tvdb_id, + processableSeasons, + { + mediaAddedAt: metadata.DateCreated + ? new Date(metadata.DateCreated) + : undefined, + jellyfinMediaId: Id, + title: tvShow.name, + } + ); + } } else { this.log( `No information found for the show: ${metadata.Name}`, diff --git a/server/lib/scanners/plex/index.ts b/server/lib/scanners/plex/index.ts index f3eda4a3bc..e66936a84c 100644 --- a/server/lib/scanners/plex/index.ts +++ b/server/lib/scanners/plex/index.ts @@ -20,6 +20,7 @@ import type { import BaseScanner from '@server/lib/scanners/baseScanner'; import type { Library } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; +import { getUnignoredPlexMedia } from '@server/utils/mediaFilter'; import { uniqWith } from 'lodash'; const imdbRegex = new RegExp(/imdb:\/\/(tt[0-9]+)/); @@ -228,11 +229,17 @@ class PlexScanner } private async processPlexMovie(plexitem: PlexLibraryItem) { + const media = getUnignoredPlexMedia(plexitem.Media ?? []); + if (media.length === 0) { + this.log( + `Skipping movie ${plexitem.title} (file path matched ignore pattern)` + ); + return; + } + const mediaIds = await this.getMediaIds(plexitem); - const has4k = plexitem.Media.some( - (media) => media.videoResolution === '4k' - ); + const has4k = media.some((mediaItem) => mediaItem.videoResolution === '4k'); await this.processMovie(mediaIds.tmdbId, { is4k: has4k && this.enable4kMovie, @@ -246,9 +253,15 @@ class PlexScanner plexitem: PlexMetadata, tmdbId: number ) { - const has4k = plexitem.Media.some( - (media) => media.videoResolution === '4k' - ); + const media = getUnignoredPlexMedia(plexitem.Media ?? []); + if (media.length === 0) { + this.log( + `Skipping movie ${plexitem.title} (file path matched ignore pattern)` + ); + return; + } + + const has4k = media.some((mediaItem) => mediaItem.videoResolution === '4k'); await this.processMovie(tmdbId, { is4k: has4k && this.enable4kMovie, @@ -326,6 +339,9 @@ class PlexScanner const processableSeasons: ProcessableSeason[] = []; const settings = getSettings(); + const hasIgnoredPatterns = + (settings.main.ignoredPathPatterns ?? []).length > 0; + const filteredSeasons = settings.main.enableSpecialEpisodes ? seasons : seasons.filter((sn) => sn.season_number !== 0); @@ -337,20 +353,33 @@ class PlexScanner if (matchedPlexSeason) { // If we have a matched Plex season, get its children metadata so we can check details - const episodes = await this.plexClient.getChildrenMetadata( + const allEpisodes = await this.plexClient.getChildrenMetadata( matchedPlexSeason.ratingKey ); + + const episodes = hasIgnoredPatterns + ? allEpisodes + .map((episode) => ({ + episode, + media: getUnignoredPlexMedia(episode.Media ?? []), + })) + .filter(({ media }) => media.length > 0) + : allEpisodes.map((episode) => ({ + episode, + media: episode.Media ?? [], + })); + // Total episodes that are in standard definition (not 4k) - const totalStandard = episodes.filter((episode) => + const totalStandard = episodes.filter(({ media }) => !this.enable4kShow ? true - : episode.Media.some((media) => media.videoResolution !== '4k') + : media.some((mediaItem) => mediaItem.videoResolution !== '4k') ).length; // Total episodes that are in 4k const total4k = this.enable4kShow - ? episodes.filter((episode) => - episode.Media.some((media) => media.videoResolution === '4k') + ? episodes.filter(({ media }) => + media.some((mediaItem) => mediaItem.videoResolution === '4k') ).length : 0; @@ -370,16 +399,19 @@ class PlexScanner } } - await this.processShow( - mediaIds.tmdbId, - mediaIds.tvdbId ?? tvShow.external_ids.tvdb_id, - processableSeasons, - { + const hasAnyEpisodes = processableSeasons.some( + (s) => s.episodes > 0 || s.episodes4k > 0 + ); + + const tvdbId = mediaIds.tvdbId ?? tvShow.external_ids?.tvdb_id; + + if (hasAnyEpisodes || !hasIgnoredPatterns) { + await this.processShow(mediaIds.tmdbId, tvdbId, processableSeasons, { mediaAddedAt: new Date(metadata.addedAt * 1000), ratingKey: ratingKey, title: metadata.title, - } - ); + }); + } } private async getMediaIds(plexitem: PlexLibraryItem): Promise { @@ -547,7 +579,13 @@ class PlexScanner season.ratingKey ); if (episodes) { - await this.processPlexMovieByTmdbId(episodes[0], tmdbId); + const candidateEpisode = episodes.find( + (episode) => getUnignoredPlexMedia(episode.Media ?? []).length > 0 + ); + + if (candidateEpisode) { + await this.processPlexMovieByTmdbId(candidateEpisode, tmdbId); + } } } } @@ -563,6 +601,9 @@ class PlexScanner ); if (episodes) { for (const episode of episodes) { + if (getUnignoredPlexMedia(episode.Media ?? []).length === 0) { + continue; + } const special = animeList.getSpecialEpisode(tvdbId, episode.index); if (special) { if (special.tmdbId) { diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index a52f8cf4c6..a86ceec416 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -158,6 +158,7 @@ export interface MainSettings { locale: string; youtubeUrl: string; versionCheck: boolean; + ignoredPathPatterns: string[]; } export interface ProxySettings { @@ -436,6 +437,7 @@ class Settings { locale: 'en', youtubeUrl: '', versionCheck: true, + ignoredPathPatterns: [], }, plex: { name: '', diff --git a/server/routes/settings/index.ts b/server/routes/settings/index.ts index 5e740e341e..d78d2ddfe9 100644 --- a/server/routes/settings/index.ts +++ b/server/routes/settings/index.ts @@ -31,6 +31,7 @@ import { appDataPath } from '@server/utils/appDataVolume'; import { getAppVersion } from '@server/utils/appVersion'; import { dnsCache } from '@server/utils/dnsCache'; import { getHostname } from '@server/utils/getHostname'; +import { sanitizeIgnoredPathPatterns } from '@server/utils/ignoredPathPatterns'; import { Router } from 'express'; import rateLimit from 'express-rate-limit'; import fs from 'fs'; @@ -62,7 +63,7 @@ const filteredMainSettings = ( main: MainSettings ): Partial => { if (!user?.hasPermission(Permission.ADMIN)) { - return omit(main, 'apiKey'); + return omit(main, 'apiKey', 'ignoredPathPatterns'); } return main; @@ -81,7 +82,25 @@ settingsRoutes.get('/main', (req, res, next) => { settingsRoutes.post('/main', async (req, res) => { const settings = getSettings(); - settings.main = merge(settings.main, req.body); + const { ignoredPathPatterns, ...rest } = req.body; + settings.main = merge(settings.main, rest); + + // merge() does not replace arrays (merges by index), so explicitly replace when present + if (Array.isArray(ignoredPathPatterns)) { + const { cleaned, rejected } = sanitizeIgnoredPathPatterns( + ignoredPathPatterns as unknown[] + ); + + if (rejected.length > 0) { + logger.warn( + `Ignored invalid or unsafe regex pattern(s) in ignoredPathPatterns: ${rejected.join(', ')}`, + { label: 'Settings' } + ); + } + + settings.main.ignoredPathPatterns = cleaned; + } + await settings.save(); return res.status(200).json(settings.main); diff --git a/server/utils/ignoredPathPatterns.test.ts b/server/utils/ignoredPathPatterns.test.ts new file mode 100644 index 0000000000..042a2e4f9e --- /dev/null +++ b/server/utils/ignoredPathPatterns.test.ts @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + compileIgnoredPathPattern, + sanitizeIgnoredPathPatterns, +} from '@server/utils/ignoredPathPatterns'; + +describe('ignoredPathPatterns', () => { + it('compiles valid patterns as case-insensitive regexes', () => { + const regex = compileIgnoredPathPattern('placeholders/'); + + assert.ok(regex instanceof RegExp); + assert.equal(regex.flags, 'i'); + assert.ok(regex.test('/media/PLACEHOLDERS/movie.mkv')); + }); + + it('returns null for invalid, unsafe, or empty patterns', () => { + assert.equal(compileIgnoredPathPattern('('), null); + assert.equal(compileIgnoredPathPattern('(a+)+$'), null); + assert.equal(compileIgnoredPathPattern(''), null); + }); + + it('returns null for patterns longer than 256 characters', () => { + assert.ok(compileIgnoredPathPattern('a'.repeat(256))); + assert.equal(compileIgnoredPathPattern('a'.repeat(257)), null); + }); + + it('rejects invalid and unsafe patterns while keeping safe unique ones', () => { + const { cleaned, rejected } = sanitizeIgnoredPathPatterns([ + 'placeholders/', + '(a+)+$', + '(', + 'placeholders/', + ' trailers/ ', + '', + ]); + + assert.deepEqual(cleaned, ['placeholders/', 'trailers/']); + assert.deepEqual(rejected, ['(a+)+$', '(']); + }); + + it('deduplicates rejected patterns and surfaces non-string entries', () => { + const { cleaned, rejected } = sanitizeIgnoredPathPatterns([ + '(', + '(', + 42, + { toString: null }, + 'placeholders/', + ]); + + assert.deepEqual(cleaned, ['placeholders/']); + assert.deepEqual(rejected, [ + '(', + '', + '', + ]); + }); +}); diff --git a/server/utils/ignoredPathPatterns.ts b/server/utils/ignoredPathPatterns.ts new file mode 100644 index 0000000000..9e01703028 --- /dev/null +++ b/server/utils/ignoredPathPatterns.ts @@ -0,0 +1,49 @@ +import safeRegex from 'safe-regex'; + +// safe-regex is a heuristic with known false negatives, and the length cap +// only limits pattern size, not matching complexity. Patterns are +// admin-configured, so a pathological pattern is a self-inflicted risk. +const MAX_PATTERN_LENGTH = 256; + +export function compileIgnoredPathPattern(pattern: string): RegExp | null { + if ( + typeof pattern !== 'string' || + pattern.length === 0 || + pattern.length > MAX_PATTERN_LENGTH + ) { + return null; + } + + try { + const regex = new RegExp(pattern, 'i'); + + return safeRegex(regex) ? regex : null; + } catch { + return null; + } +} + +export function sanitizeIgnoredPathPatterns(patterns: unknown[]): { + cleaned: string[]; + rejected: string[]; +} { + const cleaned = new Set(); + const rejected = new Set(); + + for (const pattern of patterns) { + if (typeof pattern !== 'string') { + rejected.add(``); + continue; + } + + const trimmed = pattern.trim(); + + if (trimmed.length === 0) { + continue; + } + + (compileIgnoredPathPattern(trimmed) ? cleaned : rejected).add(trimmed); + } + + return { cleaned: [...cleaned], rejected: [...rejected] }; +} diff --git a/server/utils/mediaFilter.test.ts b/server/utils/mediaFilter.test.ts new file mode 100644 index 0000000000..b70a91d4a9 --- /dev/null +++ b/server/utils/mediaFilter.test.ts @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { getSettings } from '@server/lib/settings'; +import { compileIgnoredPathPattern } from '@server/utils/ignoredPathPatterns'; +import { + getUnignoredJellyfinMediaSources, + getUnignoredPlexMedia, + isPathIgnored, +} from '@server/utils/mediaFilter'; + +describe('mediaFilter', () => { + it('recompiles regexes for distinct pattern lists that collide under NUL-joined keys', () => { + const settings = getSettings(); + const originalPatterns = [...(settings.main.ignoredPathPatterns ?? [])]; + const firstPatterns = ['^match$', 'x\0^other$']; + const secondPatterns = ['^match$\0x', '^other$']; + + assert.equal(firstPatterns.join('\0'), secondPatterns.join('\0')); + assert.notEqual( + JSON.stringify(firstPatterns), + JSON.stringify(secondPatterns) + ); + + try { + settings.main.ignoredPathPatterns = firstPatterns; + assert.equal(isPathIgnored(['match']), true); + + settings.main.ignoredPathPatterns = secondPatterns; + assert.equal(isPathIgnored(['other']), true); + } finally { + settings.main.ignoredPathPatterns = originalPatterns; + } + }); + + it('filters ignored Plex and Jellyfin sources without dropping mixed items', () => { + const settings = getSettings(); + const originalPatterns = [...(settings.main.ignoredPathPatterns ?? [])]; + const plexMedia = [ + { + Part: [{ file: '/library/movies/Test Movie (2024)/movie.mkv' }], + videoResolution: '1080', + }, + { + Part: [{ file: '/library/movies/placeholders/Test Movie (2024).mkv' }], + videoResolution: '4k', + }, + { + // Windows-style path: only matches "placeholders/" after backslash + // normalization, so it must be filtered out. + Part: [ + { file: 'C:\\library\\movies\\placeholders\\Test Movie (2024).mkv' }, + ], + videoResolution: '4k', + }, + ]; + const jellyfinSources = [ + { + Path: '/library/shows/Test Show/Season 01/S01E01.mkv', + MediaStreams: [], + }, + { + Path: '/library/shows/placeholders/Test Show/Season 01/S01E01.mkv', + MediaStreams: [], + }, + { + // Windows-style path: only matches after backslash normalization. + Path: 'C:\\library\\shows\\placeholders\\Test Show\\Season 01\\S01E01.mkv', + MediaStreams: [], + }, + ]; + + try { + settings.main.ignoredPathPatterns = ['placeholders/']; + + assert.equal( + isPathIgnored([ + '/library/movies/Test Movie (2024)/movie.mkv', + '/library/movies/placeholders/Test Movie (2024).mkv', + ]), + false + ); + // Backslash normalization: Windows placeholder path is ignored, while a + // Windows non-placeholder path is not. + assert.equal( + isPathIgnored([ + 'C:\\library\\movies\\placeholders\\Test Movie (2024).mkv', + ]), + true + ); + assert.equal( + isPathIgnored(['C:\\library\\movies\\Test Movie (2024)\\movie.mkv']), + false + ); + assert.deepEqual(getUnignoredPlexMedia(plexMedia), [plexMedia[0]]); + assert.deepEqual(getUnignoredJellyfinMediaSources(jellyfinSources), [ + jellyfinSources[0], + ]); + } finally { + settings.main.ignoredPathPatterns = originalPatterns; + } + }); + + it('skips unsafe ignored path patterns', () => { + assert.equal(compileIgnoredPathPattern('(a+)+$'), null); + assert.equal(compileIgnoredPathPattern('('), null); + assert.equal( + compileIgnoredPathPattern('placeholders/')?.test( + '/library/placeholders/file.mkv' + ), + true + ); + }); +}); diff --git a/server/utils/mediaFilter.ts b/server/utils/mediaFilter.ts new file mode 100644 index 0000000000..e6235ac527 --- /dev/null +++ b/server/utils/mediaFilter.ts @@ -0,0 +1,90 @@ +import { getSettings } from '@server/lib/settings'; +import logger from '@server/logger'; +import { compileIgnoredPathPattern } from '@server/utils/ignoredPathPatterns'; + +let regexCache = new Map(); +const warnedPatterns: Set = new Set(); +let lastPatternsKey = ''; + +function getCompiledRegexes(patterns: string[]): Map { + const patternsKey = JSON.stringify(patterns); + if (patternsKey === lastPatternsKey) return regexCache; + + regexCache = new Map(); + warnedPatterns.clear(); + lastPatternsKey = patternsKey; + + for (const pattern of patterns) { + const regex = compileIgnoredPathPattern(pattern); + + if (regex) { + regexCache.set(pattern, regex); + continue; + } + + if (!warnedPatterns.has(pattern)) { + warnedPatterns.add(pattern); + logger.warn( + `Invalid or unsafe regex pattern in ignored path patterns: ${pattern}`, + { label: 'MediaFilter' } + ); + } + } + + return regexCache; +} + +export function getJellyfinFilePaths( + mediaSources?: { Path: string }[] +): string[] { + return (mediaSources?.map((ms) => ms.Path) ?? []).filter( + (p): p is string => !!p + ); +} + +export function getPlexFilePaths( + media: { Part?: { file: string }[] }[] +): string[] { + return media + .flatMap((m) => m.Part?.map((p) => p.file) ?? []) + .filter((fp): fp is string => !!fp); +} + +function hasIgnoredPathPatterns(): boolean { + return (getSettings().main.ignoredPathPatterns ?? []).length > 0; +} + +export function getUnignoredJellyfinMediaSources( + mediaSources?: T[] +): T[] { + if (!hasIgnoredPathPatterns()) { + return mediaSources ?? []; + } + + return (mediaSources ?? []).filter( + (source) => !isPathIgnored(getJellyfinFilePaths([source])) + ); +} + +export function getUnignoredPlexMedia( + media: T[] +): T[] { + if (!hasIgnoredPathPatterns()) { + return media; + } + + return media.filter( + (mediaItem) => !isPathIgnored(getPlexFilePaths([mediaItem])) + ); +} + +export function isPathIgnored(filePaths: string[]): boolean { + const patterns = getSettings().main.ignoredPathPatterns ?? []; + if (patterns.length === 0 || filePaths.length === 0) return false; + + const normalized = filePaths.map((p) => p.replace(/\\/g, '/')); + const compiledRegexes = getCompiledRegexes(patterns); + + const regexList = Array.from(compiledRegexes.values()); + return normalized.every((fp) => regexList.some((regex) => regex.test(fp))); +} diff --git a/src/components/Settings/SettingsMain/index.tsx b/src/components/Settings/SettingsMain/index.tsx index 42b38e84d0..b4782059d3 100644 --- a/src/components/Settings/SettingsMain/index.tsx +++ b/src/components/Settings/SettingsMain/index.tsx @@ -19,12 +19,19 @@ import { ArrowPathIcon } from '@heroicons/react/24/solid'; import type { UserSettingsGeneralResponse } from '@server/interfaces/api/userSettingsInterfaces'; import type { MainSettings } from '@server/lib/settings'; import type { AvailableLocale } from '@server/types/languages'; +import { compileIgnoredPathPattern } from '@server/utils/ignoredPathPatterns'; import axios from 'axios'; import { Field, Form, Formik } from 'formik'; import { useIntl } from 'react-intl'; +import CreatableSelect from 'react-select/creatable'; import useSWR, { mutate } from 'swr'; import * as Yup from 'yup'; +type TagOption = { + label: string; + value: string; +}; + const messages = defineMessages('components.Settings.SettingsMain', { general: 'General', generalsettings: 'General Settings', @@ -80,6 +87,12 @@ const messages = defineMessages('components.Settings.SettingsMain', { versionCheck: 'Version Check', versionCheckTip: 'Automatically check for new versions on GitHub.', validationUrl: 'You must provide a valid URL', + ignoredPathPatterns: 'Ignored Path Patterns', + ignoredPathPatternsTip: + 'Case-insensitive regular expressions matched against media file paths, e.g. "placeholders/" or ".*trailers/.*"', + ignoredPathPatternsPlaceholder: 'Type a regex pattern and press Enter…', + ignoredPathPatternsInvalidRegex: + 'The regex pattern "{pattern}" is invalid or unsafe and was not added.', }); const SettingsMain = () => { @@ -183,6 +196,7 @@ const SettingsMain = () => { cacheImages: data?.cacheImages, youtubeUrl: data?.youtubeUrl, versionCheck: data?.versionCheck, + ignoredPathPatterns: data?.ignoredPathPatterns ?? [], }} enableReinitialize validationSchema={MainSettingsSchema} @@ -207,8 +221,16 @@ const SettingsMain = () => { cacheImages: values.cacheImages, youtubeUrl: values.youtubeUrl, versionCheck: values?.versionCheck, + ignoredPathPatterns: [ + ...new Set( + (values.ignoredPathPatterns ?? []) + .map((s) => s.trim()) + .filter((s) => s.length > 0) + ), + ], }); mutate('/api/v1/settings/public'); + mutate('/api/v1/status'); mutate('/api/v1/status?checkUpdateAvailable=false'); if (setLocale) { @@ -606,6 +628,56 @@ const SettingsMain = () => { /> +
+ +
+
+ + inputId="ignoredPathPatterns" + components={{ DropdownIndicator: null }} + isClearable + isMulti + noOptionsMessage={() => null} + className="react-select-container" + classNamePrefix="react-select" + placeholder={intl.formatMessage( + messages.ignoredPathPatternsPlaceholder + )} + value={(values.ignoredPathPatterns ?? []).map((p) => ({ + label: p, + value: p, + }))} + onChange={(newValue) => { + const valid: string[] = []; + const seen = new Set(); + for (const v of newValue) { + const trimmed = v.value.trim(); + if (!trimmed || seen.has(trimmed)) continue; + seen.add(trimmed); + if (compileIgnoredPathPattern(trimmed)) { + valid.push(trimmed); + } else { + addToast( + intl.formatMessage( + messages.ignoredPathPatternsInvalidRegex, + { pattern: trimmed } + ), + { autoDismiss: true, appearance: 'error' } + ); + } + } + setFieldValue('ignoredPathPatterns', valid); + }} + /> +
+
+