From 6264be78d0fecd8a73bf80c9c8b8da3a5a29bc47 Mon Sep 17 00:00:00 2001 From: Parker Rowe Date: Mon, 14 Apr 2025 16:34:04 -0400 Subject: [PATCH] feat(notifications): adds a NEW_EPISODE notification that fires for new episodes in partial seasons This feature adds a new NEW_EPISODE notification type and a trigger specifically built for Jellyfin. It fires during the "recently added" scan of Jellyfin when Jellyfin returns an episode in the newly added array. re #480 --- server/lib/notifications/agents/discord.ts | 4 + server/lib/notifications/agents/email.ts | 5 + server/lib/notifications/agents/gotify.ts | 3 + server/lib/notifications/agents/pushbullet.ts | 3 + server/lib/notifications/agents/pushover.ts | 3 + server/lib/notifications/agents/slack.ts | 3 + server/lib/notifications/agents/telegram.ts | 3 + server/lib/notifications/agents/webpush.ts | 5 + server/lib/notifications/index.ts | 1 + server/lib/scanners/jellyfin/index.ts | 175 +++++++++++++++ server/subscriber/MediaSubscriber.ts | 205 ++++++++++++++++++ .../NotificationTypeSelector/index.tsx | 17 ++ 12 files changed, 427 insertions(+) diff --git a/server/lib/notifications/agents/discord.ts b/server/lib/notifications/agents/discord.ts index cabd332def..34de2d2f04 100644 --- a/server/lib/notifications/agents/discord.ts +++ b/server/lib/notifications/agents/discord.ts @@ -138,6 +138,10 @@ class DiscordAgent color = EmbedColors.GREEN; status = 'Available'; break; + case Notification.EPISODE_AVAILABLE: + color = EmbedColors.BLUE; + status = 'New Episode Available'; + break; case Notification.MEDIA_DECLINED: color = EmbedColors.RED; status = 'Declined'; diff --git a/server/lib/notifications/agents/email.ts b/server/lib/notifications/agents/email.ts index 59c5b4aa78..bc7e4bbae2 100644 --- a/server/lib/notifications/agents/email.ts +++ b/server/lib/notifications/agents/email.ts @@ -102,6 +102,11 @@ class EmailAgent is4k ? 'in 4K ' : '' }is now available:`; break; + case Notification.EPISODE_AVAILABLE: + body = `A new episode of the following ${mediaType} ${ + is4k ? 'in 4K ' : '' + }is now available:`; + break; case Notification.MEDIA_DECLINED: body = `Your request for the following ${mediaType} ${ is4k ? 'in 4K ' : '' diff --git a/server/lib/notifications/agents/gotify.ts b/server/lib/notifications/agents/gotify.ts index 514281f728..11c2faa612 100644 --- a/server/lib/notifications/agents/gotify.ts +++ b/server/lib/notifications/agents/gotify.ts @@ -72,6 +72,9 @@ class GotifyAgent case Notification.MEDIA_AVAILABLE: status = 'Available'; break; + case Notification.EPISODE_AVAILABLE: + status = 'New Episode Available'; + break; case Notification.MEDIA_DECLINED: status = 'Declined'; break; diff --git a/server/lib/notifications/agents/pushbullet.ts b/server/lib/notifications/agents/pushbullet.ts index eed4fda917..cac9165fe2 100644 --- a/server/lib/notifications/agents/pushbullet.ts +++ b/server/lib/notifications/agents/pushbullet.ts @@ -69,6 +69,9 @@ class PushbulletAgent case Notification.MEDIA_AVAILABLE: status = 'Available'; break; + case Notification.EPISODE_AVAILABLE: + status = 'New Episode Available'; + break; case Notification.MEDIA_DECLINED: status = 'Declined'; break; diff --git a/server/lib/notifications/agents/pushover.ts b/server/lib/notifications/agents/pushover.ts index 7abf0d72a0..34358643e8 100644 --- a/server/lib/notifications/agents/pushover.ts +++ b/server/lib/notifications/agents/pushover.ts @@ -109,6 +109,9 @@ class PushoverAgent case Notification.MEDIA_AVAILABLE: status = 'Available'; break; + case Notification.EPISODE_AVAILABLE: + status = 'New Episode Available'; + break; case Notification.MEDIA_DECLINED: status = 'Declined'; priority = 1; diff --git a/server/lib/notifications/agents/slack.ts b/server/lib/notifications/agents/slack.ts index 8f1f0c9535..1d97d55658 100644 --- a/server/lib/notifications/agents/slack.ts +++ b/server/lib/notifications/agents/slack.ts @@ -85,6 +85,9 @@ class SlackAgent case Notification.MEDIA_AVAILABLE: status = 'Available'; break; + case Notification.EPISODE_AVAILABLE: + status = 'New Episode Available'; + break; case Notification.MEDIA_DECLINED: status = 'Declined'; break; diff --git a/server/lib/notifications/agents/telegram.ts b/server/lib/notifications/agents/telegram.ts index 01d4de4973..e247926e4e 100644 --- a/server/lib/notifications/agents/telegram.ts +++ b/server/lib/notifications/agents/telegram.ts @@ -98,6 +98,9 @@ class TelegramAgent case Notification.MEDIA_AVAILABLE: status = 'Available'; break; + case Notification.EPISODE_AVAILABLE: + status = 'New Episode Available'; + break; case Notification.MEDIA_DECLINED: status = 'Declined'; break; diff --git a/server/lib/notifications/agents/webpush.ts b/server/lib/notifications/agents/webpush.ts index 143961ec49..853088b100 100644 --- a/server/lib/notifications/agents/webpush.ts +++ b/server/lib/notifications/agents/webpush.ts @@ -82,6 +82,11 @@ class WebPushAgent is4k ? '4K ' : '' }${mediaType} request is now available!`; break; + case Notification.EPISODE_AVAILABLE: + message = `A new episode of your ${ + is4k ? '4K ' : '' + }${mediaType} request is now available!`; + break; case Notification.MEDIA_DECLINED: message = `Your ${is4k ? '4K ' : ''}${mediaType} request was declined.`; break; diff --git a/server/lib/notifications/index.ts b/server/lib/notifications/index.ts index 71aea8fe9f..0d8fcd4ab3 100644 --- a/server/lib/notifications/index.ts +++ b/server/lib/notifications/index.ts @@ -17,6 +17,7 @@ export enum Notification { ISSUE_RESOLVED = 1024, ISSUE_REOPENED = 2048, MEDIA_AUTO_REQUESTED = 4096, + EPISODE_AVAILABLE = 8192, } export const hasNotificationType = ( diff --git a/server/lib/scanners/jellyfin/index.ts b/server/lib/scanners/jellyfin/index.ts index bfef4f7ea8..171e2dbfc2 100644 --- a/server/lib/scanners/jellyfin/index.ts +++ b/server/lib/scanners/jellyfin/index.ts @@ -40,6 +40,7 @@ class JellyfinScanner { private enable4kMovie = false; private enable4kShow = false; private asyncLock = new AsyncLock(); + private processedEpisodeIds = new Set(); constructor({ isRecentOnly }: { isRecentOnly?: boolean } = {}) { this.tmdb = new TheMovieDb(); @@ -533,11 +534,181 @@ class JellyfinScanner { await this.processMovie(item); } else if (item.Type === 'Series') { await this.processShow(item); + } else if (item.Type === 'Episode' && this.isRecentOnly) { + // Process individual episodes when using the recently added scan + await this.processEpisode(item); } }) ); } + /** + * Process an individual episode from Jellyfin's recently added endpoint. + * This is more efficient for detecting new episodes compared to scanning entire shows. + */ + private async processEpisode(jellyfinEpisode: JellyfinLibraryItem) { + if (!jellyfinEpisode.SeriesId) { + this.log('Episode missing SeriesId, skipping', 'warn', { + episodeId: jellyfinEpisode.Id, + name: jellyfinEpisode.Name, + }); + return; + } + + const seasonNumber = jellyfinEpisode.ParentIndexNumber ?? 0; + const episodeNumber = jellyfinEpisode.IndexNumber ?? 0; + + // Generate a unique identifier for this episode based on series ID and episode info + const episodeIdentifier = `${jellyfinEpisode.SeriesId}_S${seasonNumber}E${episodeNumber}`; + + // Skip if we've already processed this episode in this scan session + if (this.processedEpisodeIds.has(episodeIdentifier)) { + this.log( + `Episode ${episodeIdentifier} already processed this session, skipping`, + 'debug' + ); + return; + } + + try { + // Get series metadata + const seriesMetadata = await this.jfClient.getItemData( + jellyfinEpisode.SeriesId + ); + + if (!seriesMetadata?.ProviderIds?.Tmdb) { + this.log('Series missing TMDB ID, skipping episode', 'debug', { + seriesId: jellyfinEpisode.SeriesId, + episodeId: jellyfinEpisode.Id, + seriesName: jellyfinEpisode.SeriesName, + }); + return; + } + + const tmdbId = Number(seriesMetadata.ProviderIds.Tmdb); + + // Get the media entity + const mediaRepository = getRepository(Media); + const media = await mediaRepository.findOne({ + where: { tmdbId, mediaType: MediaType.TV }, + }); + + if (!media) { + this.log( + 'Media not found in database, skipping episode notification', + 'debug', + { + tmdbId, + seriesName: jellyfinEpisode.SeriesName, + } + ); + return; + } + + // Check if we've recently sent a notification for this show + // (within the last 12 hours) + if (media.lastSeasonChange) { + const notificationThreshold = 12 * 60 * 60 * 1000; // 12 hours in milliseconds + const timeSinceLastNotification = + Date.now() - media.lastSeasonChange.getTime(); + + if (timeSinceLastNotification < notificationThreshold) { + this.log( + `Skipping notification - show ${ + jellyfinEpisode.SeriesName + } was recently notified (${Math.round( + timeSinceLastNotification / (60 * 60 * 1000) + )} hours ago)`, + 'debug' + ); + this.processedEpisodeIds.add(episodeIdentifier); + return; + } + } + + // Get episode details + const episodeData = await this.jfClient.getItemData(jellyfinEpisode.Id); + + if (!episodeData) { + this.log('Failed to get episode data', 'error', { + episodeId: jellyfinEpisode.Id, + }); + return; + } + + // Check episode creation date to avoid notifying about older episodes + const episodeDate = new Date( + episodeData.DateCreated ?? new Date().toISOString() + ); + const now = new Date(); + const episodeAge = now.getTime() - episodeDate.getTime(); + const recentThreshold = 24 * 60 * 60 * 1000; // 24 hours in milliseconds + + if (episodeAge > recentThreshold) { + this.log( + `Skipping older episode ${ + jellyfinEpisode.SeriesName + } S${seasonNumber}E${episodeNumber} (created ${Math.round( + episodeAge / (24 * 60 * 60 * 1000) + )} days ago)`, + 'debug' + ); + this.processedEpisodeIds.add(episodeIdentifier); + return; + } + + // Check if this is a 4K episode + const is4k = + episodeData.MediaSources?.some((source) => + source.MediaStreams.some( + (stream) => stream.Type === 'Video' && (stream.Width ?? 0) >= 2000 + ) + ) ?? false; + + // Get the corresponding season from the media entity + const season = media.seasons.find((s) => s.seasonNumber === seasonNumber); + + if (!season) { + this.log('Season not found in media seasons', 'debug', { + tmdbId, + seasonNumber, + mediaId: media.id, + }); + return; + } + + // Check if the season is partially available - this is where we'd expect new episodes + const isPartiallyAvailable = + is4k && this.enable4kShow + ? season.status4k === MediaStatus.PARTIALLY_AVAILABLE + : season.status === MediaStatus.PARTIALLY_AVAILABLE; + + // Only proceed with notification if the season is partially available + if (isPartiallyAvailable) { + // Log the detection + this.log( + `New ${is4k ? '4K' : 'standard'} episode detected for ${ + jellyfinEpisode.SeriesName + } S${seasonNumber}E${episodeNumber}`, + 'info' + ); + + // Mark this episode as processed + this.processedEpisodeIds.add(episodeIdentifier); + + // Update lastSeasonChange, which updates the entity and triggers the notification + media.lastSeasonChange = new Date(); + await mediaRepository.save(media); + } + } catch (e) { + this.log('Failed to process episode', 'error', { + errorMessage: e.message, + episodeId: jellyfinEpisode.Id, + name: jellyfinEpisode.Name, + }); + } + } + private async loop({ start = 0, end = BUNDLE_SIZE, @@ -595,6 +766,10 @@ class JellyfinScanner { const sessionId = uuid(); this.sessionId = sessionId; + + // Reset processed episode IDs for new scan + this.processedEpisodeIds.clear(); + logger.info('Jellyfin Sync Starting', { sessionId, label: 'Jellyfin Sync', diff --git a/server/subscriber/MediaSubscriber.ts b/server/subscriber/MediaSubscriber.ts index eecfe6f3d9..ecb5edde2c 100644 --- a/server/subscriber/MediaSubscriber.ts +++ b/server/subscriber/MediaSubscriber.ts @@ -174,6 +174,183 @@ export class MediaSubscriber implements EntitySubscriberInterface { } } + private async notifyNewEpisodes( + entity: Media, + dbEntity: Media, + is4k: boolean + ) { + // Only proceed if this is a TV show + if (entity.mediaType !== MediaType.TV) { + logger.debug('Skipping episode notification - not a TV show', { + label: 'Notifications', + mediaId: entity.id, + mediaType: entity.mediaType, + }); + return; + } + + logger.debug('Checking for new episodes', { + label: 'Notifications', + mediaId: entity.id, + is4k, + }); + + const requestRepository = getRepository(MediaRequest); + + // Get seasons that are partially available in the updated entity + const partiallyAvailableSeasons = entity.seasons + .filter( + (season: Season) => + season[is4k ? 'status4k' : 'status'] === + MediaStatus.PARTIALLY_AVAILABLE + ) + .map((season: Season) => season.seasonNumber); + + logger.debug('Partially available seasons', { + label: 'Notifications', + mediaId: entity.id, + is4k, + partiallyAvailableSeasons, + }); + + // If we have partially available seasons, see if they were updated + if (partiallyAvailableSeasons.length > 0) { + // Check if the lastSeasonChange was updated (indicates new episodes) + if ( + entity.lastSeasonChange && + dbEntity.lastSeasonChange && + entity.lastSeasonChange.getTime() > dbEntity.lastSeasonChange.getTime() + ) { + logger.debug('Detected lastSeasonChange update', { + label: 'Notifications', + mediaId: entity.id, + is4k, + oldTimestamp: dbEntity.lastSeasonChange.toISOString(), + newTimestamp: entity.lastSeasonChange.toISOString(), + }); + + // Find relevant requests for this media + const requests = await requestRepository.find({ + where: { + media: { + id: entity.id, + }, + is4k, + status: Not(MediaRequestStatus.DECLINED), + }, + }); + + logger.debug('Found requests for media', { + label: 'Notifications', + mediaId: entity.id, + is4k, + requestCount: requests.length, + requestIds: requests.map((req) => req.id), + }); + + if (requests.length > 0) { + const tmdb = new TheMovieDb(); + + try { + const tv = await tmdb.getTvShow({ tvId: entity.tmdbId }); + + // Send notifications to requesters of this show + for (const request of requests) { + // Check if the request has any seasons that are partially available + const hasRequestedPartialSeasons = request.seasons.some( + (season) => + partiallyAvailableSeasons.includes(season.seasonNumber) + ); + + const requestSeasons = request.seasons.map((s) => s.seasonNumber); + logger.debug('Checking request for matching seasons', { + label: 'Notifications', + mediaId: entity.id, + is4k, + requestId: request.id, + requestedSeasons: requestSeasons, + partiallyAvailableSeasons, + matchFound: hasRequestedPartialSeasons, + }); + + if (hasRequestedPartialSeasons) { + logger.info('Sending new episode notification', { + label: 'Notifications', + mediaId: entity.id, + is4k, + requestId: request.id, + userId: request.requestedBy.id, + seasons: partiallyAvailableSeasons, + }); + + notificationManager.sendNotification( + Notification.EPISODE_AVAILABLE, + { + event: `${is4k ? '4K ' : ''}New Episode Available`, + subject: `${tv.name}${ + tv.first_air_date + ? ` (${tv.first_air_date.slice(0, 4)})` + : '' + }`, + message: truncate(tv.overview, { + length: 500, + separator: /\s/, + omission: '…', + }), + notifyAdmin: false, + notifySystem: true, + notifyUser: request.requestedBy, + image: `https://image.tmdb.org/t/p/w600_and_h900_bestv2${tv.poster_path}`, + media: entity, + extra: [ + { + name: 'Affected Seasons', + value: partiallyAvailableSeasons.join(', '), + }, + ], + request, + } + ); + } + } + } catch (e) { + logger.error( + 'Something went wrong sending episode notification(s)', + { + label: 'Notifications', + errorMessage: e.message, + mediaId: entity.id, + } + ); + } + } else { + logger.debug('No matching requests found for episode notification', { + label: 'Notifications', + mediaId: entity.id, + is4k, + }); + } + } else { + logger.debug('No lastSeasonChange update detected', { + label: 'Notifications', + mediaId: entity.id, + is4k, + hasOldTimestamp: !!dbEntity.lastSeasonChange, + hasNewTimestamp: !!entity.lastSeasonChange, + oldTimestamp: dbEntity.lastSeasonChange?.toISOString(), + newTimestamp: entity.lastSeasonChange?.toISOString(), + }); + } + } else { + logger.debug('No partially available seasons found', { + label: 'Notifications', + mediaId: entity.id, + is4k, + seasonCount: entity.seasons.length, + }); + } + } + private async updateChildRequestStatus(event: Media, is4k: boolean) { const requestRepository = getRepository(MediaRequest); @@ -229,6 +406,20 @@ export class MediaSubscriber implements EntitySubscriberInterface { event.databaseEntity, false ); + + // Check if lastSeasonChange was updated, which signals new episodes + if ( + event.entity.lastSeasonChange && + event.databaseEntity.lastSeasonChange && + event.entity.lastSeasonChange.getTime() > + event.databaseEntity.lastSeasonChange.getTime() + ) { + this.notifyNewEpisodes( + event.entity as Media, + event.databaseEntity, + false + ); + } } if ( @@ -241,6 +432,20 @@ export class MediaSubscriber implements EntitySubscriberInterface { event.databaseEntity, true ); + + // Check if lastSeasonChange was updated, which signals new episodes for 4K + if ( + event.entity.lastSeasonChange && + event.databaseEntity.lastSeasonChange && + event.entity.lastSeasonChange.getTime() > + event.databaseEntity.lastSeasonChange.getTime() + ) { + this.notifyNewEpisodes( + event.entity as Media, + event.databaseEntity, + true + ); + } } if ( diff --git a/src/components/NotificationTypeSelector/index.tsx b/src/components/NotificationTypeSelector/index.tsx index e24eb9b13e..4aec111c20 100644 --- a/src/components/NotificationTypeSelector/index.tsx +++ b/src/components/NotificationTypeSelector/index.tsx @@ -29,6 +29,11 @@ const messages = defineMessages('components.NotificationTypeSelector', { 'Send notifications when media requests become available.', usermediaavailableDescription: 'Get notified when your media requests become available.', + episodeavailable: 'New Episode in Partially Available Season', + episodeavailableDescription: + 'Send notifications when new episodes of partially available seasons of requested shows become available.', + userepisodeavailableDescription: + 'Get notified when new episodes for partially available seasons of your requested shows become available.', mediafailed: 'Request Processing Failed', mediafailedDescription: 'Send notifications when media requests fail to be added to Radarr or Sonarr.', @@ -106,6 +111,7 @@ export enum Notification { ISSUE_RESOLVED = 1024, ISSUE_REOPENED = 2048, MEDIA_AUTO_REQUESTED = 4096, + EPISODE_AVAILABLE = 8192, } export const ALL_NOTIFICATIONS = Object.values(Notification) @@ -274,6 +280,17 @@ const NotificationTypeSelector = ({ value: Notification.MEDIA_AVAILABLE, hasNotifyUser: true, }, + { + id: 'episode-available', + name: intl.formatMessage(messages.episodeavailable), + description: intl.formatMessage( + user + ? messages.userepisodeavailableDescription + : messages.episodeavailableDescription + ), + value: Notification.EPISODE_AVAILABLE, + hasNotifyUser: true, + }, { id: 'media-failed', name: intl.formatMessage(messages.mediafailed),