feat: suppress repeated event from same user

This commit is contained in:
Oliver Booth 2023-08-26 21:46:58 +01:00
parent a5484365e4
commit cb3c08ffe3
Signed by: oliverbooth
GPG Key ID: B89D139977693FED
1 changed files with 23 additions and 2 deletions

View File

@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Microsoft.Extensions.Hosting;
@ -17,6 +18,7 @@ internal sealed class AvatarService : BackgroundService, IAvatarService
private readonly VirtualParadiseClient _virtualParadiseClient;
private readonly Subject<VirtualParadiseAvatar> _avatarJoined = new();
private readonly Subject<VirtualParadiseAvatar> _avatarLeft = new();
private readonly ConcurrentDictionary<int, VirtualParadiseAvatar> _cachedAvatars = new();
/// <summary>
/// Initializes a new instance of the <see cref="AvatarService" /> class.
@ -55,7 +57,8 @@ internal sealed class AvatarService : BackgroundService, IAvatarService
if (!configuration.AnnounceAvatarEvents || avatar.IsBot && !configuration.AnnounceBots)
return;
_avatarJoined.OnNext(avatar);
if (AddCachedAvatar(avatar))
_avatarJoined.OnNext(avatar);
}
private void OnVPAvatarLeft(VirtualParadiseAvatar avatar)
@ -66,6 +69,24 @@ internal sealed class AvatarService : BackgroundService, IAvatarService
if (!configuration.AnnounceAvatarEvents || avatar.IsBot && !configuration.AnnounceBots)
return;
_avatarLeft.OnNext(avatar);
if (RemoveCachedAvatar(avatar))
_avatarLeft.OnNext(avatar);
}
private bool AddCachedAvatar(VirtualParadiseAvatar avatar)
{
if (avatar is null) throw new ArgumentNullException(nameof(avatar));
bool result = !_cachedAvatars.Values.Any(a => a.User.Id == avatar.User.Id && a.Name == avatar.Name);
_cachedAvatars[avatar.Session] = avatar;
return result;
}
private bool RemoveCachedAvatar(VirtualParadiseAvatar avatar)
{
if (avatar is null) throw new ArgumentNullException(nameof(avatar));
_cachedAvatars.TryRemove(avatar.Session, out _);
return !_cachedAvatars.Values.Any(a => a.User.Id == avatar.User.Id && a.Name == avatar.Name);
}
}