Only add a row to the view counts table if the view count has changed or the stream ID changed

This commit is contained in:
barelyprofessional
2025-09-24 01:04:29 -05:00
parent 5b71c0a1bb
commit 0432d5360a

View File

@@ -3,6 +3,7 @@ using System.Net.Http.Json;
using System.Text.Json; using System.Text.Json;
using KfChatDotNetBot.Models.DbModels; using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetBot.Settings; using KfChatDotNetBot.Settings;
using Microsoft.EntityFrameworkCore;
using NLog; using NLog;
namespace KfChatDotNetBot.Services; namespace KfChatDotNetBot.Services;
@@ -57,18 +58,21 @@ public class TwitchGraphQl(string? proxy = null, CancellationToken cancellationT
if (stream.IsLive) if (stream.IsLive)
{ {
_logger.Info("Updating DB with fresh view count");
await using var db = new ApplicationDbContext(); 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!, _logger.Info("Updating DB with fresh view count");
Viewers = stream.ViewerCount!.Value, await db.TwitchViewCounts.AddAsync(new TwitchViewCountDbModel
Time = DateTimeOffset.UtcNow, {
ServerTime = 0 Topic = stream.Id!,
}, ct); Viewers = stream.ViewerCount!.Value,
await db.SaveChangesAsync(ct); Time = DateTimeOffset.UtcNow,
ServerTime = 0
}, ct);
await db.SaveChangesAsync(ct);
}
} }
var persistedLive = settings[BuiltIn.Keys.TwitchGraphQlPersistedCurrentlyLive].ToBoolean(); var persistedLive = settings[BuiltIn.Keys.TwitchGraphQlPersistedCurrentlyLive].ToBoolean();
if (stream.IsLive == persistedLive) continue; if (stream.IsLive == persistedLive) continue;
OnStreamStateUpdated?.Invoke(this, settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value!, stream.IsLive); OnStreamStateUpdated?.Invoke(this, settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value!, stream.IsLive);