Fixed 7tv & Twitch reconnection. Added adbreak, follow, subscription handlers for Twitch. Added multi-chat support. Added support to unsubscribe from Twitch event subs.

This commit is contained in:
Tom
2024-08-06 19:29:29 +00:00
parent 75fcb8e0f8
commit 8014c12bc5
60 changed files with 1064 additions and 672 deletions

View File

@ -1,310 +0,0 @@
// using System.Text.RegularExpressions;
// using TwitchLib.Client.Events;
// using Serilog;
// using TwitchChatTTS;
// using TwitchChatTTS.Chat.Commands;
// using TwitchChatTTS.Hermes.Socket;
// using TwitchChatTTS.Chat.Groups.Permissions;
// using TwitchChatTTS.Chat.Groups;
// using TwitchChatTTS.Chat.Emotes;
// using Microsoft.Extensions.DependencyInjection;
// using CommonSocketLibrary.Common;
// using CommonSocketLibrary.Abstract;
// using TwitchChatTTS.OBS.Socket;
// public class ChatMessageHandler
// {
// private readonly User _user;
// private readonly TTSPlayer _player;
// private readonly CommandManager _commands;
// private readonly IGroupPermissionManager _permissionManager;
// private readonly IChatterGroupManager _chatterGroupManager;
// private readonly IEmoteDatabase _emotes;
// private readonly OBSSocketClient _obs;
// private readonly HermesSocketClient _hermes;
// private readonly Configuration _configuration;
// private readonly ILogger _logger;
// private Regex _sfxRegex;
// private HashSet<long> _chatters;
// public HashSet<long> Chatters { get => _chatters; set => _chatters = value; }
// public ChatMessageHandler(
// User user,
// TTSPlayer player,
// CommandManager commands,
// IGroupPermissionManager permissionManager,
// IChatterGroupManager chatterGroupManager,
// IEmoteDatabase emotes,
// [FromKeyedServices("hermes")] SocketClient<WebSocketMessage> hermes,
// [FromKeyedServices("obs")] SocketClient<WebSocketMessage> obs,
// Configuration configuration,
// ILogger logger
// )
// {
// _user = user;
// _player = player;
// _commands = commands;
// _permissionManager = permissionManager;
// _chatterGroupManager = chatterGroupManager;
// _emotes = emotes;
// _obs = (obs as OBSSocketClient)!;
// _hermes = (hermes as HermesSocketClient)!;
// _configuration = configuration;
// _logger = logger;
// _chatters = new HashSet<long>();
// _sfxRegex = new Regex(@"\(([A-Za-z0-9_-]+)\)");
// }
// public async Task<MessageResult> Handle(OnMessageReceivedArgs e)
// {
// var m = e.ChatMessage;
// if (_hermes.Connected && !_hermes.Ready)
// {
// _logger.Debug($"TTS is not yet ready. Ignoring chat messages [message id: {m.Id}]");
// return new MessageResult(MessageStatus.NotReady, -1, -1);
// }
// if (_configuration.Twitch?.TtsWhenOffline != true && !_obs.Streaming)
// {
// _logger.Debug($"OBS is not streaming. Ignoring chat messages [message id: {m.Id}]");
// return new MessageResult(MessageStatus.NotReady, -1, -1);
// }
// var msg = e.ChatMessage.Message;
// var chatterId = long.Parse(m.UserId);
// var tasks = new List<Task>();
// var checks = new bool[] { true, m.IsSubscriber, m.IsVip, m.IsModerator, m.IsBroadcaster };
// var defaultGroups = new string[] { "everyone", "subscribers", "vip", "moderators", "broadcaster" };
// var customGroups = _chatterGroupManager.GetGroupNamesFor(chatterId);
// var groups = defaultGroups.Where((e, i) => checks[i]).Union(customGroups);
// try
// {
// var commandResult = await _commands.Execute(msg, m, groups);
// if (commandResult != ChatCommandResult.Unknown)
// return new MessageResult(MessageStatus.Command, -1, -1);
// }
// catch (Exception ex)
// {
// _logger.Error(ex, $"Failed executing a chat command [message: {msg}][chatter: {m.Username}][chatter id: {m.UserId}][message id: {m.Id}]");
// }
// var permissionPath = "tts.chat.messages.read";
// if (!string.IsNullOrWhiteSpace(m.CustomRewardId))
// permissionPath = "tts.chat.redemptions.read";
// var permission = chatterId == _user.OwnerId ? true : _permissionManager.CheckIfAllowed(groups, permissionPath);
// if (permission != true)
// {
// _logger.Debug($"Blocked message by {m.Username}: {msg}");
// return new MessageResult(MessageStatus.Blocked, -1, -1);
// }
// if (_obs.Streaming && !_chatters.Contains(chatterId))
// {
// tasks.Add(_hermes.SendChatterDetails(chatterId, m.Username));
// _chatters.Add(chatterId);
// }
// // Filter highly repetitive words (like emotes) from the message.
// int totalEmoteUsed = 0;
// var emotesUsed = new HashSet<string>();
// var words = msg.Split(' ');
// var wordCounter = new Dictionary<string, int>();
// string filteredMsg = string.Empty;
// var newEmotes = new Dictionary<string, string>();
// foreach (var w in words)
// {
// if (wordCounter.ContainsKey(w))
// wordCounter[w]++;
// else
// wordCounter.Add(w, 1);
// var emoteId = _emotes.Get(w);
// if (emoteId == null)
// {
// emoteId = m.EmoteSet.Emotes.FirstOrDefault(e => e.Name == w)?.Id;
// if (emoteId != null)
// {
// newEmotes.Add(emoteId, w);
// _emotes.Add(w, emoteId);
// }
// }
// if (emoteId != null)
// {
// emotesUsed.Add(emoteId);
// totalEmoteUsed++;
// }
// if (wordCounter[w] <= 4 && (emoteId == null || totalEmoteUsed <= 5))
// filteredMsg += w + " ";
// }
// if (_obs.Streaming && newEmotes.Any())
// tasks.Add(_hermes.SendEmoteDetails(newEmotes));
// msg = filteredMsg;
// // Replace filtered words.
// if (_user.RegexFilters != null)
// {
// foreach (var wf in _user.RegexFilters)
// {
// if (wf.Search == null || wf.Replace == null)
// continue;
// if (wf.IsRegex)
// {
// try
// {
// var regex = new Regex(wf.Search);
// msg = regex.Replace(msg, wf.Replace);
// continue;
// }
// catch (Exception)
// {
// wf.IsRegex = false;
// }
// }
// msg = msg.Replace(wf.Search, wf.Replace);
// }
// }
// // Determine the priority of this message
// int priority = _chatterGroupManager.GetPriorityFor(groups) + m.SubscribedMonthCount * (m.IsSubscriber ? 10 : 5);
// // Determine voice selected.
// string voiceSelected = _user.DefaultTTSVoice;
// if (_user.VoicesSelected?.ContainsKey(chatterId) == true)
// {
// var voiceId = _user.VoicesSelected[chatterId];
// if (_user.VoicesAvailable.TryGetValue(voiceId, out string? voiceName) && voiceName != null)
// {
// if (_user.VoicesEnabled.Contains(voiceName) || chatterId == _user.OwnerId || m.IsStaff)
// {
// voiceSelected = voiceName;
// }
// }
// }
// // Determine additional voices used
// var matches = _user.WordFilterRegex?.Matches(msg).ToArray();
// if (matches == null || matches.FirstOrDefault() == null || matches.First().Index < 0)
// {
// HandlePartialMessage(priority, voiceSelected, msg.Trim(), e);
// return new MessageResult(MessageStatus.None, _user.TwitchUserId, chatterId, emotesUsed);
// }
// HandlePartialMessage(priority, voiceSelected, msg.Substring(0, matches.First().Index).Trim(), e);
// foreach (Match match in matches)
// {
// var message = match.Groups[2].ToString();
// if (string.IsNullOrWhiteSpace(message))
// continue;
// var voice = match.Groups[1].ToString();
// voice = voice[0].ToString().ToUpper() + voice.Substring(1).ToLower();
// HandlePartialMessage(priority, voice, message.Trim(), e);
// }
// if (tasks.Any())
// await Task.WhenAll(tasks);
// return new MessageResult(MessageStatus.None, _user.TwitchUserId, chatterId, emotesUsed);
// }
// private void HandlePartialMessage(int priority, string voice, string message, OnMessageReceivedArgs e)
// {
// if (string.IsNullOrWhiteSpace(message))
// return;
// var m = e.ChatMessage;
// var parts = _sfxRegex.Split(message);
// var badgesString = string.Join(", ", e.ChatMessage.Badges.Select(b => b.Key + " = " + b.Value));
// if (parts.Length == 1)
// {
// _logger.Information($"Username: {m.Username}; User ID: {m.UserId}; Voice: {voice}; Priority: {priority}; Message: {message}; Month: {m.SubscribedMonthCount}; Reward Id: {m.CustomRewardId}; {badgesString}");
// _player.Add(new TTSMessage()
// {
// Voice = voice,
// Message = message,
// Timestamp = DateTime.UtcNow,
// Username = m.Username,
// //Bits = m.Bits,
// Badges = e.Badges,
// Priority = priority
// });
// return;
// }
// var sfxMatches = _sfxRegex.Matches(message);
// var sfxStart = sfxMatches.FirstOrDefault()?.Index ?? message.Length;
// for (var i = 0; i < sfxMatches.Count; i++)
// {
// var sfxMatch = sfxMatches[i];
// var sfxName = sfxMatch.Groups[1]?.ToString()?.ToLower();
// if (!File.Exists("sfx/" + sfxName + ".mp3"))
// {
// parts[i * 2 + 2] = parts[i * 2] + " (" + parts[i * 2 + 1] + ")" + parts[i * 2 + 2];
// continue;
// }
// if (!string.IsNullOrWhiteSpace(parts[i * 2]))
// {
// _logger.Information($"Username: {m.Username}; User ID: {m.UserId}; Voice: {voice}; Priority: {priority}; Message: {parts[i * 2]}; Month: {m.SubscribedMonthCount}; {badgesString}");
// _player.Add(new TTSMessage()
// {
// Voice = voice,
// Message = parts[i * 2],
// Moderator = m.IsModerator,
// Timestamp = DateTime.UtcNow,
// Username = m.Username,
// Bits = m.Bits,
// Badges = m.Badges,
// Priority = priority
// });
// }
// _logger.Information($"Username: {m.Username}; User ID: {m.UserId}; Voice: {voice}; Priority: {priority}; SFX: {sfxName}; Month: {m.SubscribedMonthCount}; {badgesString}");
// _player.Add(new TTSMessage()
// {
// Voice = voice,
// Message = sfxName,
// File = $"sfx/{sfxName}.mp3",
// Moderator = m.IsModerator,
// Timestamp = DateTime.UtcNow,
// Username = m.Username,
// Bits = m.Bits,
// Badges = m.Badges,
// Priority = priority
// });
// }
// if (!string.IsNullOrWhiteSpace(parts.Last()))
// {
// _logger.Information($"Username: {m.Username}; User ID: {m.UserId}; Voice: {voice}; Priority: {priority}; Message: {parts.Last()}; Month: {m.SubscribedMonthCount}; {badgesString}");
// _player.Add(new TTSMessage()
// {
// Voice = voice,
// Message = parts.Last(),
// Moderator = m.IsModerator,
// Timestamp = DateTime.UtcNow,
// Username = m.Username,
// Bits = m.Bits,
// Badges = m.Badges,
// Priority = priority
// });
// }
// }
// }

View File

@ -13,6 +13,6 @@ namespace TwitchChatTTS.Chat.Commands
public interface IChatPartialCommand
{
bool AcceptCustomPermission { get; }
Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client);
Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes);
}
}

View File

@ -7,6 +7,7 @@ namespace TwitchChatTTS.Chat.Commands
Success = 2,
Permission = 3,
Syntax = 4,
Fail = 5
Fail = 5,
OtherRoom = 6,
}
}

View File

@ -45,17 +45,18 @@ namespace TwitchChatTTS.Chat.Commands
{
if (_current == _root)
throw new Exception("Cannot add permissions without a command name.");
_current.AddPermission(path);
return this;
}
public ICommandBuilder AddAlias(string alias, string child) {
public ICommandBuilder AddAlias(string alias, string child)
{
if (_current == _root)
throw new Exception("Cannot add aliases without a command name.");
if (_current.Children == null || !_current.Children.Any())
throw new Exception("Cannot add alias if this has no parameter.");
_current.AddAlias(alias, child);
return this;
}
@ -327,7 +328,8 @@ namespace TwitchChatTTS.Chat.Commands
Permissions = Permissions.Union([path]).ToArray();
}
public CommandNode AddAlias(string alias, string child) {
public CommandNode AddAlias(string alias, string child)
{
var target = _children.FirstOrDefault(c => c.Parameter.Name == child);
if (target == null)
throw new Exception($"Cannot find child parameter [parameter: {child}][alias: {alias}]");
@ -339,6 +341,8 @@ namespace TwitchChatTTS.Chat.Commands
var clone = target.MemberwiseClone() as CommandNode;
var node = new CommandNode(new StaticParameter(alias, alias, target.Parameter.Optional));
node._children = target._children;
node.Permissions = target.Permissions;
node.Command = target.Command;
_children.Add(node);
return this;
}

View File

@ -0,0 +1,41 @@
using Serilog;
using static TwitchChatTTS.Chat.Commands.TTSCommands;
namespace TwitchChatTTS.Chat.Commands
{
public class CommandFactory : ICommandFactory
{
private readonly IEnumerable<IChatCommand> _commands;
private readonly ICommandBuilder _builder;
private readonly ILogger _logger;
public CommandFactory(
IEnumerable<IChatCommand> commands,
ICommandBuilder builder,
ILogger logger
)
{
_commands = commands;
_builder = builder;
_logger = logger;
}
public ICommandSelector Build()
{
foreach (var command in _commands)
{
try
{
_logger.Debug($"Creating command tree for '{command.Name}'.");
command.Build(_builder);
}
catch (Exception e)
{
_logger.Error(e, $"Failed to properly load a chat command [command name: {command.Name}]");
}
}
return _builder.Build();
}
}
}

View File

@ -10,37 +10,30 @@ using static TwitchChatTTS.Chat.Commands.TTSCommands;
namespace TwitchChatTTS.Chat.Commands
{
public class CommandManager
public class CommandManager : ICommandManager
{
private readonly User _user;
private readonly ICommandSelector _commandSelector;
private ICommandSelector _commandSelector;
private readonly HermesSocketClient _hermes;
//private readonly TwitchWebsocketClient _twitch;
private readonly IGroupPermissionManager _permissionManager;
private readonly ILogger _logger;
private string CommandStartSign { get; } = "!";
public CommandManager(
IEnumerable<IChatCommand> commands,
ICommandBuilder commandBuilder,
User user,
[FromKeyedServices("hermes")] SocketClient<WebSocketMessage> socketClient,
[FromKeyedServices("hermes")] SocketClient<WebSocketMessage> hermes,
//[FromKeyedServices("twitch")] SocketClient<TwitchWebsocketMessage> twitch,
IGroupPermissionManager permissionManager,
ILogger logger
)
{
_user = user;
_hermes = (socketClient as HermesSocketClient)!;
_hermes = (hermes as HermesSocketClient)!;
//_twitch = (twitch as TwitchWebsocketClient)!;
_permissionManager = permissionManager;
_logger = logger;
foreach (var command in commands)
{
_logger.Debug($"Creating command tree for '{command.Name}'.");
command.Build(commandBuilder);
}
_commandSelector = commandBuilder.Build();
}
@ -54,9 +47,13 @@ namespace TwitchChatTTS.Chat.Commands
if (!arg.StartsWith(CommandStartSign))
return ChatCommandResult.Unknown;
if (message.BroadcasterUserId != _user.TwitchUserId.ToString())
return ChatCommandResult.OtherRoom;
string[] parts = Regex.Matches(arg.Substring(CommandStartSign.Length), "(?<match>[^\"\\n\\s]+|\"[^\"\\n]*\")")
.Cast<Match>()
.Select(m => m.Groups["match"].Value)
.Where(m => !string.IsNullOrEmpty(m))
.Select(m => m.StartsWith('"') && m.EndsWith('"') ? m.Substring(1, m.Length - 2) : m)
.ToArray();
string[] args = parts.ToArray();
@ -65,7 +62,7 @@ namespace TwitchChatTTS.Chat.Commands
CommandSelectorResult selectorResult = _commandSelector.GetBestMatch(args, message);
if (selectorResult.Command == null)
{
_logger.Warning($"Could not match '{arg}' to any command.");
_logger.Warning($"Could not match '{arg}' to any command [chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]");
return ChatCommandResult.Missing;
}
@ -111,10 +108,24 @@ namespace TwitchChatTTS.Chat.Commands
return ChatCommandResult.Success;
}
public void Update(ICommandFactory factory)
{
_commandSelector = factory.Build();
}
private bool CanExecute(long chatterId, IEnumerable<string> groups, string path, string[]? additionalPaths)
{
_logger.Debug($"Checking for permission [chatter id: {chatterId}][group: {string.Join(", ", groups)}][path: {path}]{(additionalPaths != null ? "[paths: " + string.Join('|', additionalPaths) + "]" : string.Empty)}");
return _permissionManager.CheckIfAllowed(groups, path) != false && (additionalPaths == null || additionalPaths.All(p => _permissionManager.CheckIfAllowed(groups, p) != false));
if (_permissionManager.CheckIfAllowed(groups, path) != false)
{
if (additionalPaths == null)
return true;
// All direct allow must not be false and at least one of them must be true.
if (additionalPaths.All(p => _permissionManager.CheckIfDirectAllowed(groups, p) != false) && additionalPaths.Any(p => _permissionManager.CheckIfDirectAllowed(groups, p) == true))
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,9 @@
using static TwitchChatTTS.Chat.Commands.TTSCommands;
namespace TwitchChatTTS.Chat.Commands
{
public interface ICommandFactory
{
ICommandSelector Build();
}
}

View File

@ -0,0 +1,9 @@
using TwitchChatTTS.Twitch.Socket.Messages;
namespace TwitchChatTTS.Chat.Commands
{
public interface ICommandManager {
Task<ChatCommandResult> Execute(string arg, ChannelChatMessage message, IEnumerable<string> groups);
void Update(ICommandFactory factory);
}
}

View File

@ -5,6 +5,7 @@ using Serilog;
using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.OBS.Socket;
using TwitchChatTTS.OBS.Socket.Data;
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
using static TwitchChatTTS.Chat.Commands.TTSCommands;
@ -71,7 +72,7 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
string sceneName = values["sceneName"];
string sourceName = values["sourceName"];
@ -97,7 +98,7 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
string sceneName = values["sceneName"];
string sourceName = values["sourceName"];
@ -133,7 +134,7 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
string sceneName = values["sceneName"];
string sourceName = values["sourceName"];

View File

@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection;
using Serilog;
using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.OBS.Socket;
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
using static TwitchChatTTS.Chat.Commands.TTSCommands;
@ -44,9 +45,9 @@ namespace TwitchChatTTS.Chat.Commands
{
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await client.FetchEnabledTTSVoices();
await hermes.FetchEnabledTTSVoices();
}
}
@ -54,9 +55,9 @@ namespace TwitchChatTTS.Chat.Commands
{
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await client.FetchTTSWordFilters();
await hermes.FetchTTSWordFilters();
}
}
@ -64,9 +65,9 @@ namespace TwitchChatTTS.Chat.Commands
{
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await client.FetchTTSChatterVoices();
await hermes.FetchTTSChatterVoices();
}
}
@ -74,9 +75,9 @@ namespace TwitchChatTTS.Chat.Commands
{
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await client.FetchDefaultTTSVoice();
await hermes.FetchDefaultTTSVoice();
}
}
@ -84,9 +85,9 @@ namespace TwitchChatTTS.Chat.Commands
{
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await client.FetchRedemptions();
await hermes.FetchRedemptions();
}
}
@ -97,12 +98,13 @@ namespace TwitchChatTTS.Chat.Commands
public bool AcceptCustomPermission { get => true; }
public RefreshObs(OBSSocketClient obsManager, ILogger logger) {
public RefreshObs(OBSSocketClient obsManager, ILogger logger)
{
_obsManager = obsManager;
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
_obsManager.ClearCache();
_logger.Information("Cleared the cache used for OBS.");
@ -114,9 +116,9 @@ namespace TwitchChatTTS.Chat.Commands
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await client.FetchPermissions();
await hermes.FetchPermissions();
}
}
}

View File

@ -1,5 +1,6 @@
using Serilog;
using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
using static TwitchChatTTS.Chat.Commands.TTSCommands;
@ -51,7 +52,7 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
if (_player.Playing == null)
return;
@ -78,7 +79,7 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
_player.RemoveAll();

View File

@ -1,5 +1,8 @@
using CommonSocketLibrary.Abstract;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
using static TwitchChatTTS.Chat.Commands.TTSCommands;
@ -7,13 +10,21 @@ namespace TwitchChatTTS.Chat.Commands
{
public class TTSCommand : IChatCommand
{
private readonly TwitchWebsocketClient _twitch;
private readonly User _user;
private readonly TwitchApiClient _client;
private readonly ILogger _logger;
public TTSCommand(User user, ILogger logger)
public TTSCommand(
[FromKeyedServices("twitch")] SocketClient<TwitchWebsocketMessage> twitch,
User user,
TwitchApiClient client,
ILogger logger)
{
_twitch = (twitch as TwitchWebsocketClient)!;
_user = user;
_client = client;
_logger = logger;
}
@ -51,7 +62,19 @@ namespace TwitchChatTTS.Chat.Commands
})
.AddAlias("off", "disable")
.AddAlias("disabled", "disable")
.AddAlias("false", "disable");
.AddAlias("false", "disable")
.CreateStaticInputParameter("join", b =>
{
b.CreateMentionParameter("mention", true)
.AddPermission("tts.commands.tts.join")
.CreateCommand(new JoinRoomCommand(_twitch, _client, _user, _logger));
})
.CreateStaticInputParameter("leave", b =>
{
b.CreateMentionParameter("mention", true)
.AddPermission("tts.commands.tts.leave")
.CreateCommand(new LeaveRoomCommand(_twitch, _client, _user, _logger));
});
});
}
@ -119,7 +142,8 @@ namespace TwitchChatTTS.Chat.Commands
}
var voiceId = _user.VoicesAvailable.FirstOrDefault(v => v.Value.ToLower() == voiceNameLower).Key;
if (voiceId == null) {
if (voiceId == null)
{
_logger.Warning($"Could not find the identifier for the tts voice [voice name: {voiceName}]");
return;
}
@ -157,5 +181,94 @@ namespace TwitchChatTTS.Chat.Commands
_logger.Information($"Changed state for TTS voice [voice: {voiceName}][state: {_state}][invoker: {message.ChatterUserLogin}][id: {message.ChatterUserId}]");
}
}
private sealed class JoinRoomCommand : IChatPartialCommand
{
private readonly TwitchWebsocketClient _twitch;
private readonly TwitchApiClient _client;
private readonly User _user;
private ILogger _logger;
public bool AcceptCustomPermission { get => true; }
public JoinRoomCommand(
[FromKeyedServices("twitch")] SocketClient<TwitchWebsocketMessage> twitch,
TwitchApiClient client,
User user,
ILogger logger
)
{
_twitch = (twitch as TwitchWebsocketClient)!;
_client = client;
_user = user;
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
{
var mention = values["mention"].ToLower();
var fragment = message.Message.Fragments.FirstOrDefault(f => f.Mention != null && f.Text.ToLower() == mention);
if (fragment == null)
{
_logger.Warning("Cannot find the channel to join chat with.");
return;
}
await _client.CreateEventSubscription("channel.chat.message", "1", _twitch.SessionId, _user.TwitchUserId.ToString(), fragment.Mention!.UserId);
_logger.Information($"Joined chat room [channel: {fragment.Mention.UserLogin}][channel id: {fragment.Mention.UserId}][invoker: {message.ChatterUserLogin}][id: {message.ChatterUserId}]");
}
}
private sealed class LeaveRoomCommand : IChatPartialCommand
{
private readonly TwitchWebsocketClient _twitch;
private readonly TwitchApiClient _client;
private readonly User _user;
private ILogger _logger;
public bool AcceptCustomPermission { get => true; }
public LeaveRoomCommand(
[FromKeyedServices("twitch")] SocketClient<TwitchWebsocketMessage> twitch,
TwitchApiClient client,
User user,
ILogger logger
)
{
_twitch = (twitch as TwitchWebsocketClient)!;
_client = client;
_user = user;
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
{
var mention = values["mention"].ToLower();
var fragment = message.Message.Fragments.FirstOrDefault(f => f.Mention != null && f.Text.ToLower() == mention);
if (fragment?.Mention == null)
{
_logger.Warning("Cannot find the channel to leave chat from.");
return;
}
var subscriptionId = _twitch.GetSubscriptionId(_user.TwitchUserId.ToString(), "channel.chat.message");
if (subscriptionId == null)
{
_logger.Warning("Cannot find the subscription for that channel.");
return;
}
try
{
await _client.DeleteEventSubscription(subscriptionId);
_twitch.RemoveSubscription(fragment.Mention.UserId, "channel.chat.message");
_logger.Information($"Joined chat room [channel: {fragment.Mention.UserLogin}][channel id: {fragment.Mention.UserId}][invoker: {message.ChatterUserLogin}][id: {message.ChatterUserId}]");
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to delete the subscription from Twitch.");
}
}
}
}
}

View File

@ -1,6 +1,7 @@
using HermesSocketLibrary.Socket.Data;
using Serilog;
using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages;
using static TwitchChatTTS.Chat.Commands.TTSCommands;
@ -37,11 +38,11 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
_logger.Information($"TTS Version: {TTS.MAJOR_VERSION}.{TTS.MINOR_VERSION}");
await client.SendLoggingMessage(HermesLoggingLevel.Info, $"{_user.TwitchUsername} [twitch id: {_user.TwitchUserId}] using version {TTS.MAJOR_VERSION}.{TTS.MINOR_VERSION}.");
await hermes.SendLoggingMessage(HermesLoggingLevel.Info, $"{_user.TwitchUsername} [twitch id: {_user.TwitchUserId}] using version {TTS.MAJOR_VERSION}.{TTS.MINOR_VERSION}.");
}
}
}

View File

@ -8,8 +8,6 @@ namespace TwitchChatTTS.Chat.Commands
public class VoiceCommand : IChatCommand
{
private readonly User _user;
// TODO: get permissions
// TODO: validated parameter for username by including '@' and regex for username
private readonly ILogger _logger;
public VoiceCommand(User user, ILogger logger)
@ -26,7 +24,7 @@ namespace TwitchChatTTS.Chat.Commands
{
b.CreateVoiceNameParameter("voiceName", true)
.CreateCommand(new TTSVoiceSelector(_user, _logger))
.CreateUnvalidatedParameter("chatter", optional: true)
.CreateMentionParameter("chatter", enabled: true, optional: true)
.AddPermission("tts.command.voice.admin")
.CreateCommand(new TTSVoiceSelectorAdmin(_user, _logger));
});
@ -45,7 +43,7 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
if (_user == null || _user.VoicesSelected == null)
return;
@ -57,12 +55,12 @@ namespace TwitchChatTTS.Chat.Commands
if (_user.VoicesSelected.ContainsKey(chatterId))
{
await client.UpdateTTSUser(chatterId, voice.Key);
await hermes.UpdateTTSUser(chatterId, voice.Key);
_logger.Debug($"Sent request to create chat TTS voice [voice: {voice.Value}][username: {message.ChatterUserLogin}][reason: command]");
}
else
{
await client.CreateTTSUser(chatterId, voice.Key);
await hermes.CreateTTSUser(chatterId, voice.Key);
_logger.Debug($"Sent request to update chat TTS voice [voice: {voice.Value}][username: {message.ChatterUserLogin}][reason: command]");
}
}
@ -81,13 +79,12 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger;
}
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient client)
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
if (_user == null || _user.VoicesSelected == null)
return;
var chatterLogin = values["chatter"].Substring(1);
var mention = message.Message.Fragments.FirstOrDefault(f => f.Mention != null && f.Mention.UserLogin == chatterLogin)?.Mention;
var mention = message.Message.Fragments.FirstOrDefault(f => f.Mention != null && f.Text == values["chatter"])?.Mention;
if (mention == null)
{
_logger.Warning("Failed to find the chatter to apply voice command to.");
@ -101,12 +98,12 @@ namespace TwitchChatTTS.Chat.Commands
if (_user.VoicesSelected.ContainsKey(chatterId))
{
await client.UpdateTTSUser(chatterId, voice.Key);
await hermes.UpdateTTSUser(chatterId, voice.Key);
_logger.Debug($"Sent request to create chat TTS voice [voice: {voice.Value}][username: {mention.UserLogin}][reason: command]");
}
else
{
await client.CreateTTSUser(chatterId, voice.Key);
await hermes.CreateTTSUser(chatterId, voice.Key);
_logger.Debug($"Sent request to update chat TTS voice [voice: {voice.Value}][username: {mention.UserLogin}][reason: command]");
}
}

View File

@ -12,62 +12,75 @@ namespace TwitchChatTTS.Chat.Groups
private readonly ILogger _logger;
public ChatterGroupManager(ILogger logger) {
public ChatterGroupManager(ILogger logger)
{
_logger = logger;
_groups = new ConcurrentDictionary<string, Group>();
_chatters = new ConcurrentDictionary<long, ICollection<string>>();
}
public void Add(Group group) {
public void Add(Group group)
{
_groups.Add(group.Name, group);
}
public void Add(long chatter, string groupName) {
public void Add(long chatter, string groupName)
{
_chatters.Add(chatter, new List<string>() { groupName });
}
public void Add(long chatter, ICollection<string> groupNames) {
if (_chatters.TryGetValue(chatter, out var list)) {
public void Add(long chatter, ICollection<string> groupNames)
{
if (_chatters.TryGetValue(chatter, out var list))
{
foreach (var group in groupNames)
list.Add(group);
} else
}
else
_chatters.Add(chatter, groupNames);
}
public void Clear() {
public void Clear()
{
_groups.Clear();
_chatters.Clear();
}
public Group? Get(string groupName) {
public Group? Get(string groupName)
{
if (_groups.TryGetValue(groupName, out var group))
return group;
return null;
}
public IEnumerable<string> GetGroupNamesFor(long chatter) {
public IEnumerable<string> GetGroupNamesFor(long chatter)
{
if (_chatters.TryGetValue(chatter, out var groups))
return groups.Select(g => _groups[g].Name);
return Array.Empty<string>();
}
public int GetPriorityFor(long chatter) {
public int GetPriorityFor(long chatter)
{
if (!_chatters.TryGetValue(chatter, out var groups))
return 0;
return GetPriorityFor(groups);
}
public int GetPriorityFor(IEnumerable<string> groupNames) {
public int GetPriorityFor(IEnumerable<string> groupNames)
{
var values = groupNames.Select(g => _groups.TryGetValue(g, out var group) ? group : null).Where(g => g != null);
if (values.Any())
return values.Max(g => g.Priority);
return 0;
}
public bool Remove(long chatterId, string groupId) {
if (_chatters.TryGetValue(chatterId, out var groups)) {
public bool Remove(long chatterId, string groupId)
{
if (_chatters.TryGetValue(chatterId, out var groups))
{
groups.Remove(groupId);
_logger.Debug($"Removed chatter from group [chatter id: {chatterId}][group name: {_groups[groupId]}][group id: {groupId}]");
return true;

View File

@ -23,6 +23,13 @@ namespace TwitchChatTTS.Chat.Groups.Permissions
return res;
}
public bool? CheckIfDirectAllowed(string path)
{
var res = Get(path)?.DirectAllow;
_logger.Debug($"Permission Node GET {path} = {res?.ToString() ?? "null"} [direct]");
return res;
}
public bool? CheckIfAllowed(IEnumerable<string> groups, string path)
{
bool overall = false;
@ -37,6 +44,20 @@ namespace TwitchChatTTS.Chat.Groups.Permissions
return overall ? true : null;
}
public bool? CheckIfDirectAllowed(IEnumerable<string> groups, string path)
{
bool overall = false;
foreach (var group in groups)
{
var result = CheckIfDirectAllowed($"{group}.{path}");
if (result == false)
return false;
if (result == true)
overall = true;
}
return overall ? true : null;
}
public void Clear()
{
_root.Clear();
@ -104,6 +125,7 @@ namespace TwitchChatTTS.Chat.Groups.Permissions
}
set => _allow = value;
}
public bool? DirectAllow { get => _allow; }
internal PermissionNode? Parent { get => _parent; }
public IList<PermissionNode>? Children { get => _children == null ? null : new ReadOnlyCollection<PermissionNode>(_children); }

View File

@ -5,6 +5,8 @@ namespace TwitchChatTTS.Chat.Groups.Permissions
void Set(string path, bool? allow);
bool? CheckIfAllowed(string path);
bool? CheckIfAllowed(IEnumerable<string> groups, string path);
bool? CheckIfDirectAllowed(string path);
bool? CheckIfDirectAllowed(IEnumerable<string> groups, string path);
void Clear();
bool Remove(string path);
}

View File

@ -101,13 +101,14 @@ public class TTSPlayer
}
}
public void RemoveAll(long chatterId)
public void RemoveAll(long broadcasterId, long chatterId)
{
try
{
_mutex2.WaitOne();
if (_buffer.UnorderedItems.Any(i => i.Element.ChatterId == chatterId)) {
var list = _buffer.UnorderedItems.Where(i => i.Element.ChatterId != chatterId).ToArray();
if (_buffer.UnorderedItems.Any(i => i.Element.RoomId == broadcasterId && i.Element.ChatterId == chatterId))
{
var list = _buffer.UnorderedItems.Where(i => i.Element.RoomId == broadcasterId && i.Element.ChatterId != chatterId).ToArray();
_buffer.Clear();
foreach (var item in list)
_buffer.Enqueue(item.Element, item.Element.Priority);
@ -121,8 +122,9 @@ public class TTSPlayer
try
{
_mutex.WaitOne();
if (_messages.UnorderedItems.Any(i => i.Element.ChatterId == chatterId)) {
var list = _messages.UnorderedItems.Where(i => i.Element.ChatterId != chatterId).ToArray();
if (_messages.UnorderedItems.Any(i => i.Element.RoomId == broadcasterId && i.Element.ChatterId == chatterId))
{
var list = _messages.UnorderedItems.Where(i => i.Element.RoomId == broadcasterId && i.Element.ChatterId != chatterId).ToArray();
_messages.Clear();
foreach (var item in list)
_messages.Enqueue(item.Element, item.Element.Priority);
@ -139,7 +141,8 @@ public class TTSPlayer
try
{
_mutex2.WaitOne();
if (_buffer.UnorderedItems.Any(i => i.Element.MessageId == messageId)) {
if (_buffer.UnorderedItems.Any(i => i.Element.MessageId == messageId))
{
var list = _buffer.UnorderedItems.Where(i => i.Element.MessageId != messageId).ToArray();
_buffer.Clear();
foreach (var item in list)
@ -155,7 +158,8 @@ public class TTSPlayer
try
{
_mutex.WaitOne();
if (_messages.UnorderedItems.Any(i => i.Element.MessageId == messageId)) {
if (_messages.UnorderedItems.Any(i => i.Element.MessageId == messageId))
{
var list = _messages.UnorderedItems.Where(i => i.Element.MessageId != messageId).ToArray();
_messages.Clear();
foreach (var item in list)
@ -182,6 +186,7 @@ public class TTSPlayer
public class TTSMessage
{
public string? Voice { get; set; }
public long RoomId { get; set; }
public long ChatterId { get; set; }
public string MessageId { get; set; }
public string? Message { get; set; }