From 1d43515fb9768d43da18a7c3501be516aa58dc53 Mon Sep 17 00:00:00 2001 From: Tom Date: Mon, 12 Aug 2024 19:45:17 +0000 Subject: [PATCH] Generalized the ChatMessageReader to make it work with ChannelResubscrition. Added connections refresh command. --- Chat/Commands/CommandBuilder.cs | 19 +-- Chat/Commands/CommandManager.cs | 4 +- Chat/Commands/Parameters/CommandParameter.cs | 2 +- Chat/Commands/Parameters/MentionParameter.cs | 4 +- .../Parameters/OBSTransformationParameter.cs | 2 +- Chat/Commands/Parameters/StateParameter.cs | 2 +- Chat/Commands/Parameters/StaticParameter.cs | 2 +- .../Parameters/TTSVoiceNameParameter.cs | 2 +- .../Parameters/UnvalidatedParameter.cs | 2 +- Chat/Commands/RefreshCommand.cs | 15 ++- Chat/Messaging/ChatMessageReader.cs | 121 +++--------------- Chat/Speech/TTSPlayer.cs | 6 +- Hermes/Account.cs | 2 +- Hermes/Socket/Handlers/RequestAckHandler.cs | 26 ++++ Hermes/Socket/HermesSocketClient.cs | 9 ++ TTS.cs | 5 +- .../Handlers/ChannelChatMessageHandler.cs | 87 ++++++++++++- .../Handlers/ChannelResubscriptionHandler.cs | 7 +- 18 files changed, 182 insertions(+), 135 deletions(-) diff --git a/Chat/Commands/CommandBuilder.cs b/Chat/Commands/CommandBuilder.cs index 091f141..56636df 100644 --- a/Chat/Commands/CommandBuilder.cs +++ b/Chat/Commands/CommandBuilder.cs @@ -37,7 +37,8 @@ namespace TwitchChatTTS.Chat.Commands _logger = logger; _stack = new Stack(); - Clear(); + _root = new CommandNode(new StaticParameter("root", "root")); + _current = _root; } @@ -201,7 +202,7 @@ namespace TwitchChatTTS.Chat.Commands public interface ICommandSelector { - CommandSelectorResult GetBestMatch(string[] args, ChannelChatMessage message); + CommandSelectorResult GetBestMatch(string[] args, TwitchChatFragment[] fragments); IDictionary GetNonStaticArguments(string[] args, string path); } @@ -214,12 +215,12 @@ namespace TwitchChatTTS.Chat.Commands _root = root; } - public CommandSelectorResult GetBestMatch(string[] args, ChannelChatMessage message) + public CommandSelectorResult GetBestMatch(string[] args, TwitchChatFragment[] fragments) { - return GetBestMatch(_root, message, args, null, string.Empty, null); + return GetBestMatch(_root, fragments, args, null, string.Empty, null); } - private CommandSelectorResult GetBestMatch(CommandNode node, ChannelChatMessage message, IEnumerable args, IChatPartialCommand? match, string path, string[]? permissions) + private CommandSelectorResult GetBestMatch(CommandNode node, TwitchChatFragment[] fragments, IEnumerable args, IChatPartialCommand? match, string path, string[]? permissions) { if (node == null || !args.Any()) return new CommandSelectorResult(match, path, permissions); @@ -234,13 +235,13 @@ namespace TwitchChatTTS.Chat.Commands if (child.Parameter.GetType() == typeof(StaticParameter)) { if (child.Parameter.Name.ToLower() == argumentLower) - return GetBestMatch(child, message, args.Skip(1), child.Command ?? match, (path.Length == 0 ? string.Empty : path + ".") + child.Parameter.Name.ToLower(), perms); + return GetBestMatch(child, fragments, args.Skip(1), child.Command ?? match, (path.Length == 0 ? string.Empty : path + ".") + child.Parameter.Name.ToLower(), perms); continue; } - if ((!child.Parameter.Optional || child.Parameter.Validate(argument, message)) && child.Command != null) - return GetBestMatch(child, message, args.Skip(1), child.Command, (path.Length == 0 ? string.Empty : path + ".") + "*", perms); + if ((!child.Parameter.Optional || child.Parameter.Validate(argument, fragments)) && child.Command != null) + return GetBestMatch(child, fragments, args.Skip(1), child.Command, (path.Length == 0 ? string.Empty : path + ".") + "*", perms); if (!child.Parameter.Optional) - return GetBestMatch(child, message, args.Skip(1), match, (path.Length == 0 ? string.Empty : path + ".") + "*", permissions); + return GetBestMatch(child, fragments, args.Skip(1), match, (path.Length == 0 ? string.Empty : path + ".") + "*", permissions); } return new CommandSelectorResult(match, path, permissions); diff --git a/Chat/Commands/CommandManager.cs b/Chat/Commands/CommandManager.cs index e21e3f6..96d4fc7 100644 --- a/Chat/Commands/CommandManager.cs +++ b/Chat/Commands/CommandManager.cs @@ -59,7 +59,7 @@ namespace TwitchChatTTS.Chat.Commands string[] args = parts.ToArray(); string com = args.First().ToLower(); - CommandSelectorResult selectorResult = _commandSelector.GetBestMatch(args, message); + CommandSelectorResult selectorResult = _commandSelector.GetBestMatch(args, message.Message.Fragments); if (selectorResult.Command == null) { _logger.Warning($"Could not match '{arg}' to any command [chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]"); @@ -86,7 +86,7 @@ namespace TwitchChatTTS.Chat.Commands var parameter = entry.Value; var argument = entry.Key; // Optional parameters were validated while fetching this command. - if (!parameter.Optional && !parameter.Validate(argument, message)) + 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}]"); return ChatCommandResult.Syntax; diff --git a/Chat/Commands/Parameters/CommandParameter.cs b/Chat/Commands/Parameters/CommandParameter.cs index c75bd24..b565a8d 100644 --- a/Chat/Commands/Parameters/CommandParameter.cs +++ b/Chat/Commands/Parameters/CommandParameter.cs @@ -13,6 +13,6 @@ namespace TwitchChatTTS.Chat.Commands.Parameters Optional = optional; } - public abstract bool Validate(string value, ChannelChatMessage message); + public abstract bool Validate(string value, TwitchChatFragment[] fragments); } } \ No newline at end of file diff --git a/Chat/Commands/Parameters/MentionParameter.cs b/Chat/Commands/Parameters/MentionParameter.cs index df3a32b..f725575 100644 --- a/Chat/Commands/Parameters/MentionParameter.cs +++ b/Chat/Commands/Parameters/MentionParameter.cs @@ -8,9 +8,9 @@ namespace TwitchChatTTS.Chat.Commands.Parameters { } - public override bool Validate(string value, ChannelChatMessage message) + public override bool Validate(string value, TwitchChatFragment[] fragments) { - return value.StartsWith('@') && message.Message.Fragments.Any(f => f.Text == value && f.Mention != null); + return value.StartsWith('@') && fragments.Any(f => f.Text == value && f.Mention != null); } } } \ No newline at end of file diff --git a/Chat/Commands/Parameters/OBSTransformationParameter.cs b/Chat/Commands/Parameters/OBSTransformationParameter.cs index ef280a2..b4dff61 100644 --- a/Chat/Commands/Parameters/OBSTransformationParameter.cs +++ b/Chat/Commands/Parameters/OBSTransformationParameter.cs @@ -10,7 +10,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters { } - public override bool Validate(string value, ChannelChatMessage message) + public override bool Validate(string value, TwitchChatFragment[] fragments) { return _values.Contains(value.ToLower()); } diff --git a/Chat/Commands/Parameters/StateParameter.cs b/Chat/Commands/Parameters/StateParameter.cs index b44233a..a704387 100644 --- a/Chat/Commands/Parameters/StateParameter.cs +++ b/Chat/Commands/Parameters/StateParameter.cs @@ -10,7 +10,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters { } - public override bool Validate(string value, ChannelChatMessage message) + public override bool Validate(string value, TwitchChatFragment[] fragments) { return _values.Contains(value.ToLower()); } diff --git a/Chat/Commands/Parameters/StaticParameter.cs b/Chat/Commands/Parameters/StaticParameter.cs index 6077e89..299d9ea 100644 --- a/Chat/Commands/Parameters/StaticParameter.cs +++ b/Chat/Commands/Parameters/StaticParameter.cs @@ -13,7 +13,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters _value = value.ToLower(); } - public override bool Validate(string value, ChannelChatMessage message) + public override bool Validate(string value, TwitchChatFragment[] fragments) { return _value == value.ToLower(); } diff --git a/Chat/Commands/Parameters/TTSVoiceNameParameter.cs b/Chat/Commands/Parameters/TTSVoiceNameParameter.cs index 95c6143..3971db8 100644 --- a/Chat/Commands/Parameters/TTSVoiceNameParameter.cs +++ b/Chat/Commands/Parameters/TTSVoiceNameParameter.cs @@ -13,7 +13,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters _user = user; } - public override bool Validate(string value, ChannelChatMessage message) + public override bool Validate(string value, TwitchChatFragment[] fragments) { if (_user.VoicesAvailable == null) return false; diff --git a/Chat/Commands/Parameters/UnvalidatedParameter.cs b/Chat/Commands/Parameters/UnvalidatedParameter.cs index b6e5247..d40c35d 100644 --- a/Chat/Commands/Parameters/UnvalidatedParameter.cs +++ b/Chat/Commands/Parameters/UnvalidatedParameter.cs @@ -8,7 +8,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters { } - public override bool Validate(string value, ChannelChatMessage message) + public override bool Validate(string value, TwitchChatFragment[] fragments) { return true; } diff --git a/Chat/Commands/RefreshCommand.cs b/Chat/Commands/RefreshCommand.cs index bcf96ec..1632e7b 100644 --- a/Chat/Commands/RefreshCommand.cs +++ b/Chat/Commands/RefreshCommand.cs @@ -4,7 +4,6 @@ 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; @@ -37,7 +36,8 @@ namespace TwitchChatTTS.Chat.Commands .CreateStaticInputParameter("default_voice", b => b.CreateCommand(new RefreshTTSDefaultVoice())) .CreateStaticInputParameter("redemptions", b => b.CreateCommand(new RefreshRedemptions())) .CreateStaticInputParameter("obs_cache", b => b.CreateCommand(new RefreshObs(_obs, _logger))) - .CreateStaticInputParameter("permissions", b => b.CreateCommand(new RefreshPermissions())); + .CreateStaticInputParameter("permissions", b => b.CreateCommand(new RefreshPermissions())) + .CreateStaticInputParameter("connections", b => b.CreateCommand(new RefreshConnections())); }); } @@ -113,7 +113,6 @@ namespace TwitchChatTTS.Chat.Commands private sealed class RefreshPermissions : IChatPartialCommand { - public bool AcceptCustomPermission { get => true; } public async Task Execute(IDictionary values, ChannelChatMessage message, HermesSocketClient hermes) @@ -121,5 +120,15 @@ namespace TwitchChatTTS.Chat.Commands await hermes.FetchPermissions(); } } + + private sealed class RefreshConnections : IChatPartialCommand + { + public bool AcceptCustomPermission { get => true; } + + public async Task Execute(IDictionary values, ChannelChatMessage message, HermesSocketClient hermes) + { + await hermes.FetchConnections(); + } + } } } \ No newline at end of file diff --git a/Chat/Messaging/ChatMessageReader.cs b/Chat/Messaging/ChatMessageReader.cs index afcda83..09fd2c5 100644 --- a/Chat/Messaging/ChatMessageReader.cs +++ b/Chat/Messaging/ChatMessageReader.cs @@ -3,10 +3,7 @@ using CommonSocketLibrary.Abstract; using CommonSocketLibrary.Common; using Microsoft.Extensions.DependencyInjection; using Serilog; -using TwitchChatTTS.Chat.Commands; using TwitchChatTTS.Chat.Emotes; -using TwitchChatTTS.Chat.Groups; -using TwitchChatTTS.Chat.Groups.Permissions; using TwitchChatTTS.Chat.Speech; using TwitchChatTTS.Hermes.Socket; using TwitchChatTTS.OBS.Socket; @@ -17,13 +14,8 @@ namespace TwitchChatTTS.Chat.Messaging { public class ChatMessageReader { - public string Name => "channel.chat.message"; - private readonly User _user; private readonly TTSPlayer _player; - private readonly ICommandManager _commands; - private readonly IGroupPermissionManager _permissionManager; - private readonly IChatterGroupManager _chatterGroupManager; private readonly IEmoteDatabase _emotes; private readonly OBSSocketClient _obs; private readonly HermesSocketClient _hermes; @@ -36,9 +28,6 @@ namespace TwitchChatTTS.Chat.Messaging public ChatMessageReader( User user, TTSPlayer player, - ICommandManager commands, - IGroupPermissionManager permissionManager, - IChatterGroupManager chatterGroupManager, IEmoteDatabase emotes, [FromKeyedServices("hermes")] SocketClient hermes, [FromKeyedServices("obs")] SocketClient obs, @@ -48,9 +37,6 @@ namespace TwitchChatTTS.Chat.Messaging { _user = user; _player = player; - _commands = commands; - _permissionManager = permissionManager; - _chatterGroupManager = chatterGroupManager; _emotes = emotes; _obs = (obs as OBSSocketClient)!; _hermes = (hermes as HermesSocketClient)!; @@ -61,62 +47,46 @@ namespace TwitchChatTTS.Chat.Messaging _logger = logger; } - public async Task Execute(TwitchWebsocketClient sender, ChannelChatMessage message) + public async Task Read(TwitchWebsocketClient sender, long broadcasterId, long? chatterId, string? chatterLogin, string? messageId, TwitchReplyInfo? reply, TwitchChatFragment[] fragments, int priority) { if (_hermes.Connected && !_hermes.Ready) { - _logger.Debug($"TTS is not yet ready. Ignoring chat messages [message id: {message.MessageId}]"); - return; // new MessageResult(MessageStatus.NotReady, -1, -1); + _logger.Debug($"TTS is not yet ready. Ignoring chat messages [message id: {messageId}]"); + return; } if (_configuration.Twitch?.TtsWhenOffline != true && !_obs.Streaming) { - _logger.Debug($"OBS is not streaming. Ignoring chat messages [message id: {message.MessageId}]"); - return; // new MessageResult(MessageStatus.NotReady, -1, -1); - } - - var chatterId = long.Parse(message.ChatterUserId); - var broadcasterId = long.Parse(message.BroadcasterUserId); - var messageId = message.MessageId; - var groups = GetGroups(message, chatterId); - var commandResult = await CheckForChatCommand(message.Message.Text, message, groups); - if (commandResult != ChatCommandResult.Unknown) - return; - - var bits = GetTotalBits(message); - if (!HasPermission(message, chatterId, groups, bits)) - { - _logger.Debug($"Blocked message by {message.ChatterUserLogin}: {message.Message.Text}"); + _logger.Debug($"OBS is not streaming. Ignoring chat messages [message id: {messageId}]"); return; } - var emoteUsage = GetEmoteUsage(message); + var emoteUsage = GetEmoteUsage(fragments); var tasks = new List(); if (_obs.Streaming) { if (emoteUsage.NewEmotes.Any()) tasks.Add(_hermes.SendEmoteDetails(emoteUsage.NewEmotes)); - if (emoteUsage.EmotesUsed.Any()) - tasks.Add(_hermes.SendEmoteUsage(message.MessageId, chatterId, emoteUsage.EmotesUsed)); - if (!_user.Chatters.Contains(chatterId)) + if (emoteUsage.EmotesUsed.Any() && messageId != null && chatterId != null) + tasks.Add(_hermes.SendEmoteUsage(messageId, chatterId.Value, emoteUsage.EmotesUsed)); + if (!string.IsNullOrEmpty(chatterLogin) && chatterId != null && !_user.Chatters.Contains(chatterId.Value)) { - tasks.Add(_hermes.SendChatterDetails(chatterId, message.ChatterUserLogin)); - _user.Chatters.Add(chatterId); + tasks.Add(_hermes.SendChatterDetails(chatterId.Value, chatterLogin)); + _user.Chatters.Add(chatterId.Value); } } - if (_user.Raids.TryGetValue(message.BroadcasterUserId, out var raid) && !raid.Chatters.Contains(chatterId)) + if (chatterId != null && _user.Raids.TryGetValue(broadcasterId.ToString(), out var raid) && !raid.Chatters.Contains(chatterId.Value)) { - _logger.Information($"Potential chat message from raider ignored due to potential raid message spam [chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]"); + _logger.Information($"Potential chat message from raider ignored due to potential raid message spam [chatter: {chatterLogin}][chatter id: {chatterId}]"); return; } - var msg = FilterMessage(message); - int priority = _chatterGroupManager.GetPriorityFor(groups); - string voiceSelected = GetSelectedVoiceFor(chatterId); + var msg = FilterMessage(fragments, reply); + string voiceSelected = chatterId == null ? _user.DefaultTTSVoice : GetSelectedVoiceFor(chatterId.Value); var messages = GetPartialTTSMessages(msg, voiceSelected).ToList(); var groupedMessage = new TTSGroupedMessage(broadcasterId, chatterId, messageId, messages, DateTime.UtcNow, priority); _player.Add(groupedMessage, groupedMessage.Priority); - + if (tasks.Any()) await Task.WhenAll(tasks); } @@ -175,25 +145,11 @@ namespace TwitchChatTTS.Chat.Messaging return list; } - private async Task CheckForChatCommand(string arguments, ChannelChatMessage message, IEnumerable groups) + private string FilterMessage(TwitchChatFragment[] fragments, TwitchReplyInfo? reply) { - try - { - var commandResult = await _commands.Execute(arguments, message, groups); - return commandResult; - } - catch (Exception ex) - { - _logger.Error(ex, $"Failed executing a chat command [message: {arguments}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}][message id: {message.MessageId}]"); - } - return ChatCommandResult.Fail; - } - - private string FilterMessage(ChannelChatMessage message) - { - var msg = string.Join(string.Empty, message.Message.Fragments.Where(f => f.Type != "cheermote").Select(f => f.Text)).Trim(); - if (message.Reply != null) - msg = msg.Substring(message.Reply.ParentUserLogin.Length + 2); + var msg = string.Join(string.Empty, fragments.Where(f => f.Type != "cheermote").Select(f => f.Text)).Trim(); + if (reply != null) + msg = msg.Substring(reply.ParentUserLogin.Length + 2); // Replace filtered words. if (_user.RegexFilters != null) @@ -222,11 +178,11 @@ namespace TwitchChatTTS.Chat.Messaging return msg; } - private ChatMessageEmoteUsage GetEmoteUsage(ChannelChatMessage message) + private ChatMessageEmoteUsage GetEmoteUsage(TwitchChatFragment[] fragments) { var emotesUsed = new HashSet(); var newEmotes = new Dictionary(); - foreach (var fragment in message.Message.Fragments) + foreach (var fragment in fragments) { if (fragment.Emote != null) { @@ -256,30 +212,6 @@ namespace TwitchChatTTS.Chat.Messaging return new ChatMessageEmoteUsage(emotesUsed, newEmotes); } - private int GetTotalBits(ChannelChatMessage message) - { - return message.Message.Fragments.Where(f => f.Type == "cheermote" && f.Cheermote != null) - .Select(f => f.Cheermote!.Bits) - .Sum(); - } - - private string GetGroupNameByBadgeName(string badgeName) - { - if (badgeName == "subscriber") - return "subscribers"; - if (badgeName == "moderator") - return "moderators"; - return badgeName.ToLower(); - } - - private IEnumerable GetGroups(ChannelChatMessage message, long chatterId) - { - var defaultGroups = new string[] { "everyone" }; - var badgesGroups = message.Badges.Select(b => b.SetId).Select(GetGroupNameByBadgeName); - var customGroups = _chatterGroupManager.GetGroupNamesFor(chatterId); - return defaultGroups.Union(badgesGroups).Union(customGroups); - } - private IEnumerable GetPartialTTSMessages(string message, string defaultVoice) { var matches = _user.VoiceNameRegex?.Matches(message).ToArray(); @@ -319,17 +251,6 @@ namespace TwitchChatTTS.Chat.Messaging return voiceSelected ?? "Brian"; } - private bool HasPermission(ChannelChatMessage message, long chatterId, IEnumerable groups, int bits) - { - var permissionPath = "tts.chat.messages.read"; - if (!string.IsNullOrWhiteSpace(message.ChannelPointsCustomRewardId)) - permissionPath = "tts.chat.redemptions.read"; - else if (bits > 0) - permissionPath = "tts.chat.bits.read"; - - return chatterId == _user.OwnerId ? true : _permissionManager.CheckIfAllowed(groups, permissionPath) == true; - } - private class ChatMessageEmoteUsage { public readonly HashSet EmotesUsed = new HashSet(); diff --git a/Chat/Speech/TTSPlayer.cs b/Chat/Speech/TTSPlayer.cs index 305d62d..a22a28b 100644 --- a/Chat/Speech/TTSPlayer.cs +++ b/Chat/Speech/TTSPlayer.cs @@ -194,15 +194,15 @@ namespace TwitchChatTTS.Chat.Speech public class TTSGroupedMessage { public long RoomId { get; set; } - public long ChatterId { get; set; } - public string MessageId { get; set; } + public long? ChatterId { get; set; } + public string? MessageId { get; set; } public DateTime Timestamp { get; set; } public int Priority { get; set; } public IList Messages { get; set; } public ISampleProvider? Audio { get; set; } - public TTSGroupedMessage(long broadcasterId, long chatterId, string messageId, IList messages, DateTime timestamp, int priority) + public TTSGroupedMessage(long broadcasterId, long? chatterId, string? messageId, IList messages, DateTime timestamp, int priority) { RoomId = broadcasterId; ChatterId = chatterId; diff --git a/Hermes/Account.cs b/Hermes/Account.cs index 799efa8..067201f 100644 --- a/Hermes/Account.cs +++ b/Hermes/Account.cs @@ -2,5 +2,5 @@ public class Account { public string Id { get; set; } public string Username { get; set; } public string Role { get; set; } - public string? BroadcasterId { get; set; } + public string BroadcasterId { get; set; } } \ No newline at end of file diff --git a/Hermes/Socket/Handlers/RequestAckHandler.cs b/Hermes/Socket/Handlers/RequestAckHandler.cs index de11f2f..77bbaea 100644 --- a/Hermes/Socket/Handlers/RequestAckHandler.cs +++ b/Hermes/Socket/Handlers/RequestAckHandler.cs @@ -19,6 +19,8 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers { private User _user; private readonly ICallbackManager _callbackManager; + private readonly TwitchApiClient _twitch; + private readonly NightbotApiClient _nightbot; private readonly IServiceProvider _serviceProvider; private readonly JsonSerializerOptions _options; private readonly ILogger _logger; @@ -30,6 +32,8 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers public RequestAckHandler( ICallbackManager callbackManager, + TwitchApiClient twitch, + NightbotApiClient nightbot, IServiceProvider serviceProvider, User user, JsonSerializerOptions options, @@ -37,6 +41,8 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers ) { _callbackManager = callbackManager; + _twitch = twitch; + _nightbot = nightbot; _serviceProvider = serviceProvider; _user = user; _options = options; @@ -142,6 +148,26 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers _user.VoicesAvailable[voiceId] = voice; _logger.Information($"Updated TTS voice [voice: {voice}][id: {voiceId}]"); } + else if (message.Request.Type == "get_connections") + { + var connections = JsonSerializer.Deserialize>(message.Data?.ToString(), _options); + if (connections == null) + { + _logger.Error("Null value was given when attempting to fetch connections."); + _logger.Debug(message.Data?.ToString()); + return; + } + + _user.TwitchConnection = connections.FirstOrDefault(c => c.Type == "twitch" && c.Default); + _user.NightbotConnection = connections.FirstOrDefault(c => c.Type == "nightbot" && c.Default); + + if (_user.TwitchConnection != null) + _twitch.Initialize(_user.TwitchConnection.ClientId, _user.TwitchConnection.AccessToken); + if (_user.NightbotConnection != null) + _nightbot.Initialize(_user.NightbotConnection.ClientId, _user.NightbotConnection.AccessToken); + + _logger.Information($"Fetched connections from TTS account [count: {connections.Count()}][twitch: {_user.TwitchConnection != null}][nightbot: {_user.NightbotConnection != null}]"); + } else if (message.Request.Type == "get_tts_users") { var users = JsonSerializer.Deserialize>(message.Data.ToString(), _options); diff --git a/Hermes/Socket/HermesSocketClient.cs b/Hermes/Socket/HermesSocketClient.cs index bec3018..ff1d2e6 100644 --- a/Hermes/Socket/HermesSocketClient.cs +++ b/Hermes/Socket/HermesSocketClient.cs @@ -215,6 +215,15 @@ namespace TwitchChatTTS.Hermes.Socket }); } + public async Task FetchConnections() + { + await Send(3, new RequestMessage() + { + Type = "get_connections", + Data = null + }); + } + public void Initialize() { _logger.Information("Initializing Hermes websocket client."); diff --git a/TTS.cs b/TTS.cs index 43392b3..b415756 100644 --- a/TTS.cs +++ b/TTS.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; -using System.Web; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; @@ -16,7 +14,6 @@ using TwitchChatTTS.Twitch.Socket; using TwitchChatTTS.Chat.Commands; using System.Text; using TwitchChatTTS.Chat.Speech; -using NAudio.Wave; namespace TwitchChatTTS { @@ -95,7 +92,7 @@ namespace TwitchChatTTS _logger.Information($"A new update for TTS is avaiable! Version {hermesVersion.MajorVersion}.{hermesVersion.MinorVersion} is available at {hermesVersion.Download}"); var changes = hermesVersion.Changelog.Split("\n"); if (changes != null && changes.Any()) - _logger.Information("Changelogs:\n - " + string.Join("\n - ", changes) + "\n\n"); + _logger.Information("Changelog:\n - " + string.Join("\n - ", changes) + "\n\n"); await Task.Delay(15 * 1000); } diff --git a/Twitch/Socket/Handlers/ChannelChatMessageHandler.cs b/Twitch/Socket/Handlers/ChannelChatMessageHandler.cs index b8c62e3..3ee6fad 100644 --- a/Twitch/Socket/Handlers/ChannelChatMessageHandler.cs +++ b/Twitch/Socket/Handlers/ChannelChatMessageHandler.cs @@ -1,4 +1,7 @@ using Serilog; +using TwitchChatTTS.Chat.Commands; +using TwitchChatTTS.Chat.Groups; +using TwitchChatTTS.Chat.Groups.Permissions; using TwitchChatTTS.Chat.Messaging; using TwitchChatTTS.Twitch.Socket.Messages; @@ -9,18 +12,27 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers public string Name => "channel.chat.message"; private readonly ChatMessageReader _reader; - private readonly Configuration _configuration; + private readonly User _user; + private readonly ICommandManager _commands; + private readonly IGroupPermissionManager _permissionManager; + private readonly IChatterGroupManager _chatterGroupManager; private readonly ILogger _logger; public ChannelChatMessageHandler( ChatMessageReader reader, - Configuration configuration, + ICommandManager commands, + IGroupPermissionManager permissionManager, + IChatterGroupManager chatterGroupManager, + User user, ILogger logger ) { _reader = reader; - _configuration = configuration; + _user = user; + _commands = commands; + _permissionManager = permissionManager; + _chatterGroupManager = chatterGroupManager; _logger = logger; } @@ -32,7 +44,74 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers if (data is not ChannelChatMessage message) return; - await _reader.Execute(sender, message); + var broadcasterId = long.Parse(message.BroadcasterUserId); + var chatterId = long.Parse(message.ChatterUserId); + var chatterLogin = message.ChatterUserLogin; + var messageId = message.MessageId; + var fragments = message.Message.Fragments; + var groups = GetGroups(message.Badges, chatterId); + var bits = GetTotalBits(fragments); + + var commandResult = await CheckForChatCommand(message.Message.Text, message, groups); + if (commandResult != ChatCommandResult.Unknown) + return; + + if (!HasPermission(message.ChannelPointsCustomRewardId, chatterId, groups, bits)) + { + _logger.Debug($"Blocked message by {chatterLogin}: {message}"); + return; + } + + int priority = _chatterGroupManager.GetPriorityFor(groups); + await _reader.Read(sender, broadcasterId, chatterId, chatterLogin, messageId, message.Reply, fragments, priority); + } + + private async Task CheckForChatCommand(string arguments, ChannelChatMessage message, IEnumerable groups) + { + try + { + return await _commands.Execute(arguments, message, groups); + } + catch (Exception ex) + { + _logger.Error(ex, $"Failed executing a chat command [message: {arguments}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}][message id: {message.MessageId}]"); + } + return ChatCommandResult.Fail; + } + + private string GetGroupNameByBadgeName(string badgeName) + { + if (badgeName == "subscriber") + return "subscribers"; + if (badgeName == "moderator") + return "moderators"; + return badgeName.ToLower(); + } + + private IEnumerable GetGroups(TwitchBadge[] badges, long chatterId) + { + var defaultGroups = new string[] { "everyone" }; + var badgesGroups = badges.Select(b => b.SetId).Select(GetGroupNameByBadgeName); + var customGroups = _chatterGroupManager.GetGroupNamesFor(chatterId); + return defaultGroups.Union(badgesGroups).Union(customGroups); + } + + private int GetTotalBits(TwitchChatFragment[] fragments) + { + return fragments.Where(f => f.Type == "cheermote" && f.Cheermote != null) + .Select(f => f.Cheermote!.Bits) + .Sum(); + } + + private bool HasPermission(string? customRewardId, long chatterId, IEnumerable groups, int bits) + { + var permissionPath = "tts.chat.messages.read"; + if (!string.IsNullOrWhiteSpace(customRewardId)) + permissionPath = "tts.chat.redemptions.read"; + else if (bits > 0) + permissionPath = "tts.chat.bits.read"; + + return chatterId == _user.OwnerId ? true : _permissionManager.CheckIfAllowed(groups, permissionPath) == true; } } } \ No newline at end of file diff --git a/Twitch/Socket/Handlers/ChannelResubscriptionHandler.cs b/Twitch/Socket/Handlers/ChannelResubscriptionHandler.cs index 42ecd26..f397091 100644 --- a/Twitch/Socket/Handlers/ChannelResubscriptionHandler.cs +++ b/Twitch/Socket/Handlers/ChannelResubscriptionHandler.cs @@ -24,8 +24,13 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers { if (data is not ChannelResubscriptionMessage message) return; + + _logger.Debug($"Resubscription occured [chatter: {message.UserLogin}][chatter id: {message.UserId}][tier: {message.Tier}][streak: {message.StreakMonths}][cumulative: {message.CumulativeMonths}][duration: {message.DurationMonths}]"); + + long broadcasterId = long.Parse(message.BroadcasterUserId); + long chatterId = message.UserId == null ? 0 : long.Parse(message.UserId); + Task.Run(async () => await _reader.Read(sender, broadcasterId, chatterId, message.UserLogin, null, null, message.Message.Fragments, 100)); - _logger.Debug($"Resubscription occured [chatter: {message.UserLogin}][chatter id: {message.UserId}][Tier: {message.Tier}][Streak: {message.StreakMonths}][Cumulative: {message.CumulativeMonths}][Duration: {message.DurationMonths}]"); try { var actions = _redemptionManager.Get("subscription");