From 887b95f79853f29e590a9f770136c9a9125586ab Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Wed, 28 May 2025 21:43:57 -0500 Subject: [PATCH] fix: prevent duplicate stream notifications - add store that is singleton to keep track of last posted stream and prevent posting twice for same stream --- src/src/StevesBot.Webhook/Program.cs | 2 ++ .../YouTube/Handlers/NotificationHandler.cs | 9 +++++++++ .../YouTube/LastPostedStreamStore.cs | 11 +++++++++++ 3 files changed, 22 insertions(+) create mode 100644 src/src/StevesBot.Webhook/YouTube/LastPostedStreamStore.cs diff --git a/src/src/StevesBot.Webhook/Program.cs b/src/src/StevesBot.Webhook/Program.cs index b585858..4bed4fb 100644 --- a/src/src/StevesBot.Webhook/Program.cs +++ b/src/src/StevesBot.Webhook/Program.cs @@ -41,6 +41,8 @@ builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton>(); builder.Services.AddHostedService(); +builder.Services.AddSingleton(); + builder.Services.AddOptionsWithValidateOnStart() .BindConfiguration(nameof(DiscordNotificationOptions)) .ValidateDataAnnotations(); diff --git a/src/src/StevesBot.Webhook/YouTube/Handlers/NotificationHandler.cs b/src/src/StevesBot.Webhook/YouTube/Handlers/NotificationHandler.cs index 4226558..c75d2fc 100644 --- a/src/src/StevesBot.Webhook/YouTube/Handlers/NotificationHandler.cs +++ b/src/src/StevesBot.Webhook/YouTube/Handlers/NotificationHandler.cs @@ -8,6 +8,7 @@ internal static class NotificationHandler [FromServices] IYouTubeDataApiClient youTubeDataApiClient, [FromServices] IDiscordRestClient discordRestClient, [FromServices] IOptionsMonitor discordNotificationOptions, + [FromServices] LastPostedStreamStore lastPostedStream, CancellationToken cancellationToken ) { @@ -39,6 +40,14 @@ internal static class NotificationHandler return Results.Ok(); } + if (lastPostedStream.Value == videoId) + { + logger.LogInformation("Video ID {VideoId} has already been posted. Skipping notification.", videoId); + return Results.Ok(); + } + + lastPostedStream.SetValue(videoId); + logger.LogInformation( "Video ID {VideoId} is a live stream. Creating discord message in channel {ChannelId}", videoId, diff --git a/src/src/StevesBot.Webhook/YouTube/LastPostedStreamStore.cs b/src/src/StevesBot.Webhook/YouTube/LastPostedStreamStore.cs new file mode 100644 index 0000000..7030e9f --- /dev/null +++ b/src/src/StevesBot.Webhook/YouTube/LastPostedStreamStore.cs @@ -0,0 +1,11 @@ +namespace StevesBot.Webhook.YouTube; + +internal class LastPostedStreamStore +{ + public string Value { get; private set; } = string.Empty; + + public void SetValue(string value) + { + Value = value; + } +} \ No newline at end of file