From 0432d5360ab15e9c3e2bbfc68d478854a9417f9a Mon Sep 17 00:00:00 2001 From: barelyprofessional <150058423+barelyprofessional@users.noreply.github.com> Date: Wed, 24 Sep 2025 01:04:29 -0500 Subject: [PATCH] Only add a row to the view counts table if the view count has changed or the stream ID changed --- KfChatDotNetBot/Services/TwitchGraphQl.cs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/KfChatDotNetBot/Services/TwitchGraphQl.cs b/KfChatDotNetBot/Services/TwitchGraphQl.cs index 9615c7a..67aacaf 100644 --- a/KfChatDotNetBot/Services/TwitchGraphQl.cs +++ b/KfChatDotNetBot/Services/TwitchGraphQl.cs @@ -3,6 +3,7 @@ using System.Net.Http.Json; using System.Text.Json; using KfChatDotNetBot.Models.DbModels; using KfChatDotNetBot.Settings; +using Microsoft.EntityFrameworkCore; using NLog; namespace KfChatDotNetBot.Services; @@ -57,18 +58,21 @@ public class TwitchGraphQl(string? proxy = null, CancellationToken cancellationT if (stream.IsLive) { - _logger.Info("Updating DB with fresh view count"); await using var db = new ApplicationDbContext(); - await db.TwitchViewCounts.AddAsync(new TwitchViewCountDbModel + var mostRecentViewCount = await db.TwitchViewCounts.OrderBy(x => x.Id).LastOrDefaultAsync(ct); + if (mostRecentViewCount == null || mostRecentViewCount.Viewers != stream.ViewerCount!.Value || mostRecentViewCount.Topic != stream.Id) { - Topic = stream.Id!, - Viewers = stream.ViewerCount!.Value, - Time = DateTimeOffset.UtcNow, - ServerTime = 0 - }, ct); - await db.SaveChangesAsync(ct); + _logger.Info("Updating DB with fresh view count"); + await db.TwitchViewCounts.AddAsync(new TwitchViewCountDbModel + { + Topic = stream.Id!, + Viewers = stream.ViewerCount!.Value, + Time = DateTimeOffset.UtcNow, + ServerTime = 0 + }, ct); + await db.SaveChangesAsync(ct); + } } - var persistedLive = settings[BuiltIn.Keys.TwitchGraphQlPersistedCurrentlyLive].ToBoolean(); if (stream.IsLive == persistedLive) continue; OnStreamStateUpdated?.Invoke(this, settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value!, stream.IsLive);