Fix SessionStart double notifications (#272)

This commit is contained in:
chiragkrishna 2024-09-05 21:28:52 +05:30 committed by GitHub
parent e2ff7056e7
commit f4b40c6cbc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,4 +1,7 @@
using System.Threading.Tasks;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Plugin.Webhook.Destinations;
using Jellyfin.Plugin.Webhook.Helpers;
using MediaBrowser.Controller;
@ -14,6 +17,9 @@ public class SessionStartNotifier : IEventConsumer<SessionStartedEventArgs>
{
private readonly IServerApplicationHost _applicationHost;
private readonly IWebhookSender _webhookSender;
private static readonly ConcurrentDictionary<string, DateTime> _recentEvents = new();
private static readonly TimeSpan RecentEventThreshold = TimeSpan.FromSeconds(5);
private static readonly TimeSpan CleanupThreshold = TimeSpan.FromMinutes(5);
/// <summary>
/// Initializes a new instance of the <see cref="SessionStartNotifier"/> class.
@ -36,6 +42,22 @@ public class SessionStartNotifier : IEventConsumer<SessionStartedEventArgs>
return;
}
// Clean up old session entries when a new session event is triggered
CleanupOldEntries();
// Generate a unique key for this session event
string sessionKey = eventArgs.Argument.Id;
// Check if we've processed a similar event recently
if (_recentEvents.TryGetValue(sessionKey, out DateTime lastProcessedTime) &&
DateTime.UtcNow - lastProcessedTime < RecentEventThreshold)
{
return;
}
// Update the cache with the latest event time
_recentEvents[sessionKey] = DateTime.UtcNow;
var dataObject = DataObjectHelpers
.GetBaseDataObject(_applicationHost, NotificationType.SessionStart)
.AddSessionInfoData(eventArgs.Argument)
@ -44,4 +66,21 @@ public class SessionStartNotifier : IEventConsumer<SessionStartedEventArgs>
await _webhookSender.SendNotification(NotificationType.SessionStart, dataObject)
.ConfigureAwait(false);
}
/// <summary>
/// Cleans up old session entries from the cache.
/// </summary>
private static void CleanupOldEntries()
{
DateTime threshold = DateTime.UtcNow - CleanupThreshold;
var keysToRemove = _recentEvents
.Where(kvp => kvp.Value < threshold)
.Select(kvp => kvp.Key)
.ToList();
foreach (var key in keysToRemove)
{
_recentEvents.TryRemove(key, out _);
}
}
}