Added policies. Added action for channel ad break ending.

This commit is contained in:
Tom
2024-10-22 07:54:59 +00:00
parent f1f345970f
commit 07b035039d
15 changed files with 453 additions and 163 deletions

View File

@ -9,5 +9,6 @@ namespace TwitchChatTTS.Chat.Commands
Syntax = 4,
Fail = 5,
OtherRoom = 6,
RateLimited = 7
}
}

View File

@ -3,6 +3,7 @@ using CommonSocketLibrary.Abstract;
using CommonSocketLibrary.Common;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using TwitchChatTTS.Chat.Commands.Limits;
using TwitchChatTTS.Chat.Groups.Permissions;
using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
@ -17,6 +18,7 @@ namespace TwitchChatTTS.Chat.Commands
private readonly HermesSocketClient _hermes;
//private readonly TwitchWebsocketClient _twitch;
private readonly IGroupPermissionManager _permissionManager;
private readonly IUsagePolicy<long> _permissionPolicy;
private readonly ILogger _logger;
private string CommandStartSign { get; } = "!";
@ -26,6 +28,7 @@ namespace TwitchChatTTS.Chat.Commands
[FromKeyedServices("hermes")] SocketClient<WebSocketMessage> hermes,
//[FromKeyedServices("twitch")] SocketClient<TwitchWebsocketMessage> twitch,
IGroupPermissionManager permissionManager,
IUsagePolicy<long> limitManager,
ILogger logger
)
{
@ -33,6 +36,7 @@ namespace TwitchChatTTS.Chat.Commands
_hermes = (hermes as HermesSocketClient)!;
//_twitch = (twitch as TwitchWebsocketClient)!;
_permissionManager = permissionManager;
_permissionPolicy = limitManager;
_logger = logger;
}
@ -69,9 +73,10 @@ namespace TwitchChatTTS.Chat.Commands
// Check if command can be executed by this chatter.
var command = selectorResult.Command;
long chatterId = long.Parse(message.ChatterUserId);
var path = $"tts.commands.{com}";
if (chatterId != _user.OwnerId)
{
bool executable = command.AcceptCustomPermission ? CanExecute(chatterId, groups, $"tts.commands.{com}", selectorResult.Permissions) : false;
bool executable = command.AcceptCustomPermission ? CanExecute(chatterId, groups, path, selectorResult.Permissions) : false;
if (!executable)
{
_logger.Warning($"Denied permission to use command [chatter id: {chatterId}][args: {arg}][command type: {command.GetType().Name}]");
@ -79,6 +84,12 @@ namespace TwitchChatTTS.Chat.Commands
}
}
if (!_permissionPolicy.TryUse(chatterId, groups, path))
{
_logger.Warning($"Chatter reached usage limit on command [command type: {command.GetType().Name}][chatter id: {chatterId}][path: {path}][groups: {string.Join("|", groups)}]");
return ChatCommandResult.RateLimited;
}
// Check if the arguments are valid.
var arguments = _commandSelector.GetNonStaticArguments(args, selectorResult.Path);
foreach (var entry in arguments)
@ -88,7 +99,7 @@ namespace TwitchChatTTS.Chat.Commands
// Optional parameters were validated while fetching this command.
if (!parameter.Optional && !parameter.Validate(argument, message.Message.Fragments))
{
_logger.Warning($"Command failed due to an argument being invalid [argument name: {parameter.Name}][argument value: {argument}][arguments: {arg}][command type: {command.GetType().Name}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]");
_logger.Warning($"Command failed due to an argument being invalid [argument name: {parameter.Name}][argument value: {argument}][parameter type: {parameter.GetType().Name}][arguments: {arg}][command type: {command.GetType().Name}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]");
return ChatCommandResult.Syntax;
}
}

View File

@ -1,88 +0,0 @@
namespace TwitchChatTTS.Chat.Commands.Limits
{
public interface ICommandLimitManager
{
bool HasReachedLimit(long chatterId, string name, string group);
void RemoveUsageLimit(string name, string group);
void SetUsageLimit(int count, TimeSpan span, string name, string group);
bool TryUse(long chatterId, string name, string group);
}
public class CommandLimitManager : ICommandLimitManager
{
// group + name -> chatter id -> usage
private readonly IDictionary<string, IDictionary<long, Usage>> _usages;
// group + name -> limit
private readonly IDictionary<string, Limit> _limits;
public CommandLimitManager()
{
_usages = new Dictionary<string, IDictionary<long, Usage>>();
_limits = new Dictionary<string, Limit>();
}
public bool HasReachedLimit(long chatterId, string name, string group)
{
throw new NotImplementedException();
}
public void RemoveUsageLimit(string name, string group)
{
throw new NotImplementedException();
}
public void SetUsageLimit(int count, TimeSpan span, string name, string group)
{
throw new NotImplementedException();
}
public bool TryUse(long chatterId, string name, string group)
{
var path = $"{group}.{name}";
if (!_limits.TryGetValue(path, out var limit))
return true;
if (!_usages.TryGetValue(path, out var groupUsage))
{
groupUsage = new Dictionary<long, Usage>();
_usages.Add(path, groupUsage);
}
if (!groupUsage.TryGetValue(chatterId, out var usage))
{
usage = new Usage()
{
Usages = new long[limit.Count],
Index = 0
};
groupUsage.Add(chatterId, usage);
}
int first = (usage.Index + 1) % limit.Count;
long timestamp = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
if (timestamp - usage.Usages[first] < limit.Span)
{
return false;
}
usage.Usages[usage.Index] = timestamp;
usage.Index = first;
return true;
}
private class Usage
{
public long[] Usages { get; set; }
public int Index { get; set; }
}
private struct Limit
{
public int Count { get; set; }
public int Span { get; set; }
}
}
}

View File

@ -0,0 +1,10 @@
namespace TwitchChatTTS.Chat.Commands.Limits
{
public interface IUsagePolicy<K>
{
void Remove(string group, string policy);
void Set(string group, string policy, int count, TimeSpan span);
bool TryUse(K key, string group, string policy);
public bool TryUse(K key, IEnumerable<string> groups, string policy);
}
}

View File

@ -0,0 +1,216 @@
using Serilog;
namespace TwitchChatTTS.Chat.Commands.Limits
{
public class UsagePolicy<K> : IUsagePolicy<K> where K : notnull
{
private readonly ILogger _logger;
private readonly UsagePolicyNode<K> _root;
public UsagePolicy(ILogger logger)
{
_logger = logger;
_root = new UsagePolicyNode<K>(string.Empty, null, null, logger);
}
public void Remove(string group, string policy)
{
ArgumentException.ThrowIfNullOrWhiteSpace(group, nameof(group));
ArgumentException.ThrowIfNullOrWhiteSpace(policy, nameof(policy));
string[] path = (group + '.' + policy).Split('.');
_root.Remove(path);
}
public void Set(string group, string policy, int count, TimeSpan span)
{
ArgumentException.ThrowIfNullOrWhiteSpace(group, nameof(group));
ArgumentException.ThrowIfNullOrWhiteSpace(policy, nameof(policy));
if (count <= 0)
throw new InvalidOperationException("Count cannot be 0 or lower.");
if (span.TotalMilliseconds == 0)
throw new InvalidOperationException("Time span cannot be 0 milliseconds.");
string[] path = (group + '.' + policy).Split('.');
_root.Set(path, count, span);
}
public bool TryUse(K key, string group, string policy)
{
ArgumentException.ThrowIfNullOrWhiteSpace(group, nameof(group));
ArgumentException.ThrowIfNullOrWhiteSpace(policy, nameof(policy));
string[] path = (group + '.' + policy).Split('.');
UsagePolicyNode<K>? node = _root.Get(path);
_logger.Debug($"Fetched policy node [is null: {node == null}]");
if (node == null)
return false;
return node.TryUse(key, DateTime.UtcNow);
}
public bool TryUse(K key, IEnumerable<string> groups, string policy)
{
ArgumentNullException.ThrowIfNull(groups, nameof(groups));
ArgumentException.ThrowIfNullOrWhiteSpace(policy, nameof(policy));
foreach (string group in groups)
{
if (TryUse(key, group, policy))
{
_logger.Debug($"Checking policy node [policy: {group}.{policy}][result: True]");
return true;
}
_logger.Debug($"Checking policy node [policy: {group}.{policy}][result: False]");
}
return false;
}
private class UsagePolicyLimit
{
public int Count { get; set; }
public TimeSpan Span { get; set; }
public UsagePolicyLimit(int count, TimeSpan span)
{
Count = count;
Span = span;
}
}
private class UserUsageData
{
public DateTime[] Uses { get; set; }
public int Index { get; set; }
public UserUsageData(int size, int index)
{
Uses = new DateTime[size];
Index = index;
}
}
private class UsagePolicyNode<T> where T : notnull
{
public string Name { get; set; }
public UsagePolicyLimit? Limit { get; private set; }
private UsagePolicyNode<T>? _parent { get; }
private IDictionary<T, UserUsageData> _usages { get; }
private IList<UsagePolicyNode<T>> _children { get; }
private ILogger _logger;
private object _lock { get; }
public UsagePolicyNode(string name, UsagePolicyLimit? data, UsagePolicyNode<T>? parent, ILogger logger)
{
//ArgumentException.ThrowIfNullOrWhiteSpace(name, nameof(name));
Name = name;
Limit = data;
_parent = parent;
_usages = new Dictionary<T, UserUsageData>();
_children = new List<UsagePolicyNode<T>>();
_logger = logger;
_lock = new object();
}
public UsagePolicyNode<T>? Get(IEnumerable<string> path)
{
if (!path.Any())
return this;
var nextName = path.First();
var next = _children.FirstOrDefault(c => c.Name == nextName);
if (next == null)
return this;
return next.Get(path.Skip(1));
}
public UsagePolicyNode<T>? Remove(IEnumerable<string> path)
{
if (!path.Any())
{
if (_parent == null)
throw new InvalidOperationException("Cannot remove root node");
_parent._children.Remove(this);
return this;
}
var nextName = path.First();
var next = _children.FirstOrDefault(c => c.Name == nextName);
_logger.Debug($"internal remove node [is null: {next == null}][path: {string.Join('.', path)}]");
if (next == null)
return null;
return next.Remove(path.Skip(1));
}
public void Set(IEnumerable<string> path, int count, TimeSpan span)
{
if (!path.Any())
{
Limit = new UsagePolicyLimit(count, span);
return;
}
var nextName = path.First();
var next = _children.FirstOrDefault(c => c.Name == nextName);
_logger.Debug($"internal set node [is null: {next == null}][path: {string.Join('.', path)}]");
if (next == null)
{
next = new UsagePolicyNode<T>(nextName, null, this, _logger);
_children.Add(next);
}
next.Set(path.Skip(1), count, span);
}
public bool TryUse(T key, DateTime timestamp)
{
if (_parent == null)
return false;
if (Limit == null || Limit.Count <= 0)
return _parent.TryUse(key, timestamp);
UserUsageData? usage;
lock (_lock)
{
if (!_usages.TryGetValue(key, out usage))
{
usage = new UserUsageData(Limit.Count, 1 % Limit.Count);
usage.Uses[0] = timestamp;
_usages.Add(key, usage);
_logger.Debug($"internal use node create");
return true;
}
if (usage.Uses.Length != Limit.Count)
{
var sizeDiff = Math.Max(0, usage.Uses.Length - Limit.Count);
var temp = usage.Uses.Skip(sizeDiff);
var tempSize = usage.Uses.Length - sizeDiff;
usage.Uses = temp.Union(new DateTime[Math.Max(0, Limit.Count - tempSize)]).ToArray();
}
}
// Attempt on parent node if policy has been abused.
if (timestamp - usage.Uses[usage.Index] < Limit.Span)
{
_logger.Debug($"internal use node spam [span: {(timestamp - usage.Uses[usage.Index]).TotalMilliseconds}][index: {usage.Index}]");
return _parent.TryUse(key, timestamp);
}
_logger.Debug($"internal use node normal [span: {(timestamp - usage.Uses[usage.Index]).TotalMilliseconds}][index: {usage.Index}]");
lock (_lock)
{
usage.Uses[usage.Index] = timestamp;
usage.Index = (usage.Index + 1) % Limit.Count;
}
return true;
}
}
}
}

View File

@ -12,7 +12,7 @@ using TwitchChatTTS.Twitch.Socket.Messages;
namespace TwitchChatTTS.Chat.Messaging
{
public class ChatMessageReader
public class ChatMessageReader : IChatMessageReader
{
private readonly User _user;
private readonly TTSPlayer _player;
@ -94,7 +94,6 @@ namespace TwitchChatTTS.Chat.Messaging
private IEnumerable<TTSMessage> HandlePartialMessage(string voice, string message)
{
var parts = _sfxRegex.Split(message);
if (parts.Length == 1)
{
return [new TTSMessage()

View File

@ -0,0 +1,10 @@
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
namespace TwitchChatTTS.Chat.Messaging
{
public interface IChatMessageReader
{
Task Read(TwitchWebsocketClient sender, long broadcasterId, long? chatterId, string? chatterLogin, string? messageId, TwitchReplyInfo? reply, TwitchChatFragment[] fragments, int priority);
}
}