From 9fd43502f56f0eed7d94b9d00fb349006ce62723 Mon Sep 17 00:00:00 2001 From: Tom Date: Wed, 14 Aug 2024 18:19:18 +0000 Subject: [PATCH] Cleaned up code --- Hermes/HermesApiClient.cs | 147 +----------------- Hermes/TwitchBotAuth.cs | 21 --- Startup.cs | 6 +- TTSListening.cs | 2 +- Twitch/Socket/Handlers/NotificationHandler.cs | 5 +- Twitch/Socket/TwitchConnectionManager.cs | 12 +- Twitch/Socket/TwitchWebsocketClient.cs | 3 - 7 files changed, 13 insertions(+), 183 deletions(-) delete mode 100644 Hermes/TwitchBotAuth.cs diff --git a/Hermes/HermesApiClient.cs b/Hermes/HermesApiClient.cs index bdfa6bc..b780e72 100644 --- a/Hermes/HermesApiClient.cs +++ b/Hermes/HermesApiClient.cs @@ -1,26 +1,23 @@ using TwitchChatTTS.Helpers; using TwitchChatTTS; using System.Text.Json; -using HermesSocketLibrary.Requests.Messages; using TwitchChatTTS.Hermes; using Serilog; public class HermesApiClient { - private readonly TwitchBotAuth _token; private readonly WebClientWrap _web; private readonly ILogger _logger; public const string BASE_URL = "tomtospeech.com"; - public HermesApiClient(TwitchBotAuth token, Configuration configuration, ILogger logger) + public HermesApiClient(Configuration configuration, ILogger logger) { if (string.IsNullOrWhiteSpace(configuration.Hermes?.Token)) { throw new Exception("Ensure you have written your API key in \".token\" file, in the same folder as this application."); } - _token = token; _web = new WebClientWrap(new JsonSerializerOptions() { PropertyNameCaseInsensitive = false, @@ -30,42 +27,6 @@ public class HermesApiClient _logger = logger; } - - public async Task AuthorizeTwitch() - { - try - { - _logger.Debug($"Attempting to authorize Twitch API..."); - var authorize = await _web.GetJson($"https://{HermesApiClient.BASE_URL}/api/account/reauthorize"); - if (authorize != null) - { - _token.AccessToken = authorize.AccessToken; - _token.RefreshToken = authorize.RefreshToken; - _token.UserId = authorize.UserId; - _token.BroadcasterId = authorize.BroadcasterId; - _token.ExpiresIn = authorize.ExpiresIn; - _token.UpdatedAt = DateTime.Now; - _logger.Information("Updated Twitch API tokens."); - _logger.Debug($"Twitch API Auth data [user id: {_token.UserId}][id: {_token.BroadcasterId}][expires in: {_token.ExpiresIn}][expires at: {_token.ExpiresAt.ToShortTimeString()}]"); - } - else if (authorize != null) - { - _logger.Error("Twitch API Authorization failed: " + authorize.AccessToken + " | " + authorize.RefreshToken + " | " + authorize.UserId + " | " + authorize.BroadcasterId); - return null; - } - return _token; - } - catch (JsonException) - { - _logger.Debug($"Failed to Authorize Twitch API due to JSON error."); - } - catch (Exception e) - { - _logger.Error(e, "Failed to authorize to Twitch API."); - } - return null; - } - public async Task GetLatestTTSVersion() { return await _web.GetJson($"https://{BASE_URL}/api/info/version"); @@ -81,110 +42,4 @@ public class HermesApiClient throw new NullReferenceException("Invalid value found while fetching for hermes account data."); return account; } - - public async Task FetchTwitchBotToken() - { - var token = await _web.GetJson($"https://{BASE_URL}/api/token/bot"); - if (token == null || token.ClientId == null || token.AccessToken == null || token.RefreshToken == null || token.ClientSecret == null) - throw new Exception("Failed to fetch Twitch API token from Hermes."); - - return token; - } - - public async Task FetchTTSDefaultVoice() - { - var data = await _web.GetJson($"https://{BASE_URL}/api/settings/tts/default"); - if (data == null) - throw new Exception("Failed to fetch TTS default voice from Hermes."); - - return data; - } - - public async Task> FetchTTSChatterSelectedVoices() - { - var voices = await _web.GetJson>($"https://{BASE_URL}/api/settings/tts/selected"); - if (voices == null) - throw new Exception("Failed to fetch TTS chatter selected voices from Hermes."); - - return voices; - } - - public async Task> FetchTTSEnabledVoices() - { - var voices = await _web.GetJson>($"https://{BASE_URL}/api/settings/tts"); - if (voices == null) - throw new Exception("Failed to fetch TTS enabled voices from Hermes."); - - return voices; - } - - public async Task> FetchTTSWordFilters() - { - var filters = await _web.GetJson>($"https://{BASE_URL}/api/settings/tts/filter/words"); - if (filters == null) - throw new Exception("Failed to fetch TTS word filters from Hermes."); - - return filters; - } - - public async Task> FetchRedemptions() - { - var redemptions = await _web.GetJson>($"https://{BASE_URL}/api/settings/redemptions", new JsonSerializerOptions() - { - PropertyNameCaseInsensitive = false, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }); - if (redemptions == null) - throw new Exception("Failed to fetch redemptions from Hermes."); - - return redemptions; - } - - public async Task> FetchGroups() - { - var groups = await _web.GetJson>($"https://{BASE_URL}/api/settings/groups", new JsonSerializerOptions() - { - PropertyNameCaseInsensitive = false, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }); - if (groups == null) - throw new Exception("Failed to fetch groups from Hermes."); - - return groups; - } - - public async Task> FetchGroupChatters() - { - var chatters = await _web.GetJson>($"https://{BASE_URL}/api/settings/groups/users", new JsonSerializerOptions() - { - PropertyNameCaseInsensitive = false, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }); - if (chatters == null) - throw new Exception("Failed to fetch groups from Hermes."); - - return chatters; - } - - public async Task> FetchGroupPermissions() - { - var permissions = await _web.GetJson>($"https://{BASE_URL}/api/settings/groups/permissions", new JsonSerializerOptions() - { - PropertyNameCaseInsensitive = false, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }); - if (permissions == null) - throw new Exception("Failed to fetch group permissions from Hermes."); - - return permissions; - } - - public async Task> FetchRedeemableActions() - { - var actions = await _web.GetJson>($"https://{BASE_URL}/api/settings/redemptions/actions"); - if (actions == null) - throw new Exception("Failed to fetch redeemable actions from Hermes."); - - return actions; - } } \ No newline at end of file diff --git a/Hermes/TwitchBotAuth.cs b/Hermes/TwitchBotAuth.cs deleted file mode 100644 index cd065ca..0000000 --- a/Hermes/TwitchBotAuth.cs +++ /dev/null @@ -1,21 +0,0 @@ -public class TwitchBotAuth -{ - public string? UserId { get; set; } - public string? AccessToken { get; set; } - public string? RefreshToken { get; set; } - public string? BroadcasterId { get; set; } - public long? ExpiresIn - { - get => _expiresIn; - set - { - _expiresIn = value; - if (value != null) - ExpiresAt = DateTime.UtcNow + TimeSpan.FromSeconds((double) value); - } - } - public DateTime ExpiresAt { get; set; } - public DateTime UpdatedAt { get; set; } - - private long? _expiresIn; -} \ No newline at end of file diff --git a/Startup.cs b/Startup.cs index d5569ec..a361db3 100644 --- a/Startup.cs +++ b/Startup.cs @@ -32,6 +32,7 @@ using CommonSocketLibrary.Backoff; using TwitchChatTTS.Chat.Speech; using TwitchChatTTS.Chat.Messaging; using TwitchChatTTS.Chat.Observers; +using TwitchChatTTS.Chat.Commands.Limits; // dotnet publish -r linux-x64 -p:PublishSingleFile=true --self-contained true // dotnet publish -r win-x64 -p:PublishSingleFile=true --self-contained true @@ -85,7 +86,6 @@ s.AddSingleton(); s.AddSingleton(); s.AddSingleton(); s.AddSingleton(); -s.AddSingleton(); s.AddSingleton(); s.AddSingleton(); @@ -94,6 +94,8 @@ s.AddSingleton(); s.AddSingleton(); s.AddSingleton(); +s.AddSingleton(); + // OBS websocket s.AddKeyedSingleton("obs"); s.AddKeyedSingleton("obs"); @@ -118,8 +120,6 @@ s.AddKeyedSingleton, SevenSocketClient>("7tv"); // Nightbot s.AddSingleton(); -s.AddSingleton(); - // twitch websocket s.AddKeyedSingleton("twitch", new ExponentialBackoff(1000, 120 * 1000)); s.AddSingleton(); diff --git a/TTSListening.cs b/TTSListening.cs index d4a386e..66403d6 100644 --- a/TTSListening.cs +++ b/TTSListening.cs @@ -110,7 +110,7 @@ namespace TwitchChatTTS } catch (Exception e) { - _logger.Error(e, "Failed to fetch TTS message for "); + _logger.Error(e, $"Failed to fetch TTS message [message: {message.Message.Trim()}][chatter id: {group.ChatterId}]."); } } diff --git a/Twitch/Socket/Handlers/NotificationHandler.cs b/Twitch/Socket/Handlers/NotificationHandler.cs index e991bc9..c73b29e 100644 --- a/Twitch/Socket/Handlers/NotificationHandler.cs +++ b/Twitch/Socket/Handlers/NotificationHandler.cs @@ -44,9 +44,9 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers _messageTypes.Add("channel.subscription.gift", typeof(ChannelSubscriptionGiftMessage)); } - public async Task Execute(TwitchWebsocketClient sender, object data) + public Task Execute(TwitchWebsocketClient sender, object data) { - Task.Run(async () => + return Task.Run(() => { if (sender == null) return; @@ -66,6 +66,7 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers } var d = JsonSerializer.Deserialize(message.Event.ToString()!, type, _options); + ArgumentNullException.ThrowIfNull(d); Task.Run(async () => await handler.Execute(sender, d)); }); } diff --git a/Twitch/Socket/TwitchConnectionManager.cs b/Twitch/Socket/TwitchConnectionManager.cs index b2571a8..35bea8a 100644 --- a/Twitch/Socket/TwitchConnectionManager.cs +++ b/Twitch/Socket/TwitchConnectionManager.cs @@ -78,21 +78,19 @@ namespace TwitchChatTTS.Twitch.Socket { if (_identified?.UID == client.UID) { - _logger.Warning($"Identified Twitch client has disconnected [client: {client.UID}][main: {_identified.UID}][backup: {_backup?.UID}]"); + _logger.Debug($"Identified Twitch client has disconnected [client: {client.UID}][main: {_identified.UID}][backup: {_backup?.UID}]"); _identified = null; reconnecting = true; } else if (_backup?.UID == client.UID) { - _logger.Warning($"Backup Twitch client has disconnected [client: {client.UID}][main: {_identified?.UID}][backup: {_backup.UID}]"); + _logger.Debug($"Backup Twitch client has disconnected [client: {client.UID}][main: {_identified?.UID}][backup: {_backup.UID}]"); _backup = null; } else if (client.ReceivedReconnecting) - { _logger.Debug($"Twitch client disconnected due to reconnection [client: {client.UID}][main: {_identified?.UID}][backup: {_backup?.UID}]"); - } else - _logger.Error($"Twitch client disconnected from unknown source [client: {client.UID}][main: {_identified?.UID}][backup: {_backup?.UID}]"); + _logger.Warning($"Twitch client disconnected from unknown source [client: {client.UID}][main: {_identified?.UID}][backup: {_backup?.UID}]"); } if (reconnecting) @@ -111,7 +109,7 @@ namespace TwitchChatTTS.Twitch.Socket { if (_backup != null && _backup.UID == client.UID) { - _logger.Information($"Twitch client has been identified [client: {client.UID}][main: {_identified?.UID}][backup: {_backup.UID}]"); + _logger.Debug($"Twitch client has been identified [client: {client.UID}][main: {_identified?.UID}][backup: {_backup.UID}]"); _identified = _backup; _backup = null; } @@ -120,7 +118,7 @@ namespace TwitchChatTTS.Twitch.Socket } else if (_identified.UID == client.UID) { - _logger.Warning($"Twitch client has been re-identified [client: {client.UID}][main: {_identified.UID}][backup: {_backup?.UID}]"); + _logger.Debug($"Twitch client has been re-identified [client: {client.UID}][main: {_identified.UID}][backup: {_backup?.UID}]"); } else if (_backup == null || _backup.UID != client.UID) { diff --git a/Twitch/Socket/TwitchWebsocketClient.cs b/Twitch/Socket/TwitchWebsocketClient.cs index 441ed2f..95e054d 100644 --- a/Twitch/Socket/TwitchWebsocketClient.cs +++ b/Twitch/Socket/TwitchWebsocketClient.cs @@ -17,7 +17,6 @@ namespace TwitchChatTTS.Twitch.Socket private readonly IDictionary _subscriptions; private readonly IBackoff _backoff; private readonly Configuration _configuration; - private DateTime _lastReceivedMessageTimestamp; private bool _disconnected; private readonly object _lock; @@ -157,8 +156,6 @@ namespace TwitchChatTTS.Twitch.Socket return; } - _lastReceivedMessageTimestamp = DateTime.UtcNow; - string content = message.Payload?.ToString() ?? string.Empty; if (message.Metadata.MessageType != "session_keepalive") _logger.Debug("Twitch RX #" + message.Metadata.MessageType + ": " + content);