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

@ -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]");
}
}