- Renamed CustomReaction model to NadekoExpression

- Used structured logging everywhere
This commit is contained in:
Kwoth
2022-01-04 07:35:55 +01:00
parent ef49030841
commit 3aa6a54b6e
30 changed files with 330 additions and 300 deletions

View File

@@ -221,7 +221,6 @@ public class ProtectionService : INService
if (stats.Count >= spamSettings.AntiSpamSettings.MessageThreshold)
if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats))
{
stats.Dispose();
var settings = spamSettings.AntiSpamSettings;
await PunishUsers(settings.Action,
ProtectionType.Spamming,
@@ -319,10 +318,8 @@ public class ProtectionService : INService
public bool TryStopAntiSpam(ulong guildId)
{
if (_antiSpamGuilds.TryRemove(guildId, out var removed))
if (_antiSpamGuilds.TryRemove(guildId, out _))
{
foreach (var (_, val) in removed.UserStats) val.Dispose();
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.AntiSpamSetting).ThenInclude(x => x.IgnoredChannels));

View File

@@ -1,52 +1,65 @@
#nullable disable
namespace NadekoBot.Modules.Administration;
public sealed class UserSpamStats : IDisposable
public sealed class UserSpamStats
{
public int Count
=> timers.Count;
{
get
{
lock (_applyLock)
{
Cleanup();
Log.Information("{Count}",_messageTracker.Count.ToString());
return _messageTracker.Count;
}
}
}
public string LastMessage { get; set; }
private string lastMessage;
private ConcurrentQueue<Timer> timers;
private readonly Queue<DateTime> _messageTracker;
private readonly object _applyLock = new();
private readonly TimeSpan _maxTime = TimeSpan.FromMinutes(30);
public UserSpamStats(IUserMessage msg)
{
LastMessage = msg.Content.ToUpperInvariant();
timers = new();
lastMessage = msg.Content.ToUpperInvariant();
_messageTracker = new();
ApplyNextMessage(msg);
}
public void ApplyNextMessage(IUserMessage message)
{
var upperMsg = message.Content.ToUpperInvariant();
lock (_applyLock)
{
var upperMsg = message.Content.ToUpperInvariant();
if (upperMsg != LastMessage || (string.IsNullOrWhiteSpace(upperMsg) && message.Attachments.Any()))
if (upperMsg != lastMessage || (string.IsNullOrWhiteSpace(upperMsg) && message.Attachments.Any()))
{
LastMessage = upperMsg;
while (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite);
// if it's a new message, reset spam counter
lastMessage = upperMsg;
_messageTracker.Clear();
}
var t = new Timer(_ =>
{
if (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite);
},
null,
TimeSpan.FromMinutes(30),
TimeSpan.FromMinutes(30));
timers.Enqueue(t);
_messageTracker.Enqueue(DateTime.UtcNow);
}
}
public void Dispose()
private void Cleanup()
{
while (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite);
lock (_applyLock)
{
while (_messageTracker.TryPeek(out var dateTime))
{
if (DateTime.UtcNow - dateTime < _maxTime)
break;
_messageTracker.Dequeue();
}
}
}
}