Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions server/lib/notifications/agents/discord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
5 changes: 5 additions & 0 deletions server/lib/notifications/agents/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ' : ''
Expand Down
3 changes: 3 additions & 0 deletions server/lib/notifications/agents/gotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions server/lib/notifications/agents/pushbullet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions server/lib/notifications/agents/pushover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions server/lib/notifications/agents/slack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions server/lib/notifications/agents/telegram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 5 additions & 0 deletions server/lib/notifications/agents/webpush.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions server/lib/notifications/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export enum Notification {
ISSUE_RESOLVED = 1024,
ISSUE_REOPENED = 2048,
MEDIA_AUTO_REQUESTED = 4096,
EPISODE_AVAILABLE = 8192,
}

export const hasNotificationType = (
Expand Down
175 changes: 175 additions & 0 deletions server/lib/scanners/jellyfin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class JellyfinScanner {
private enable4kMovie = false;
private enable4kShow = false;
private asyncLock = new AsyncLock();
private processedEpisodeIds = new Set<string>();

constructor({ isRecentOnly }: { isRecentOnly?: boolean } = {}) {
this.tmdb = new TheMovieDb();
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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',
Expand Down
Loading