From 7ebe3e701408fde408e32cb9611c3f847e5662b9 Mon Sep 17 00:00:00 2001 From: Andrei Tudor Date: Mon, 13 Jan 2025 12:27:35 +0200 Subject: [PATCH] Updated settings change route --- DiscordBot/Installer.cs | 1 - DiscordBot/builder.sh | 0 .../API/Endpoints/EndpointManager.cs | 12 +- .../SettingsChangeEndpoint.cs | 2 +- .../SettingsManagement/SettingsGetEndpoint.cs | 7 +- DiscordBotCore/Application.cs | 3 +- .../Settings/CustomSettingsDictionaryBase.cs | 2 + DiscordBotCore/Repository/PluginRepository.cs | 1 - .../CustomTags/SettingsComponent.razor | 113 ++++++++++++++++-- .../Pages/SidebarPages/Settings.razor | 81 ++++++++++++- 10 files changed, 194 insertions(+), 28 deletions(-) mode change 100644 => 100755 DiscordBot/builder.sh diff --git a/DiscordBot/Installer.cs b/DiscordBot/Installer.cs index c4b9296..67effe9 100644 --- a/DiscordBot/Installer.cs +++ b/DiscordBot/Installer.cs @@ -21,7 +21,6 @@ public static class Installer } AnsiConsole.MarkupLine($"Invalid {key} !"); - Environment.Exit(-20); return value; diff --git a/DiscordBot/builder.sh b/DiscordBot/builder.sh old mode 100644 new mode 100755 diff --git a/DiscordBotCore/API/Endpoints/EndpointManager.cs b/DiscordBotCore/API/Endpoints/EndpointManager.cs index fa4dc33..de0386b 100644 --- a/DiscordBotCore/API/Endpoints/EndpointManager.cs +++ b/DiscordBotCore/API/Endpoints/EndpointManager.cs @@ -8,10 +8,10 @@ namespace DiscordBotCore.API.Endpoints; internal sealed class EndpointManager { - private WebApplication _appBuilder; + private readonly WebApplication _AppBuilder; internal EndpointManager(WebApplication appBuilder) { - _appBuilder = appBuilder; + _AppBuilder = appBuilder; } internal void MapEndpoint(IEndpoint endpoint) @@ -19,7 +19,7 @@ internal sealed class EndpointManager switch (endpoint.HttpMethod) { case EndpointType.Get: - _appBuilder.MapGet(endpoint.Path, async context => + _AppBuilder.MapGet(endpoint.Path, async context => { //convert the context to a string string jsonRequest = string.Empty; @@ -34,7 +34,7 @@ internal sealed class EndpointManager }); break; case EndpointType.Put: - _appBuilder.MapPut(endpoint.Path, async context => + _AppBuilder.MapPut(endpoint.Path, async context => { string jsonRequest = string.Empty; if (context.Request.Body.CanRead) @@ -48,7 +48,7 @@ internal sealed class EndpointManager }); break; case EndpointType.Post: - _appBuilder.MapPost(endpoint.Path, async context => + _AppBuilder.MapPost(endpoint.Path, async context => { string jsonRequest = string.Empty; if (context.Request.Body.CanRead) @@ -62,7 +62,7 @@ internal sealed class EndpointManager }); break; case EndpointType.Delete: - _appBuilder.MapDelete(endpoint.Path, async context => + _AppBuilder.MapDelete(endpoint.Path, async context => { string jsonRequest = string.Empty; if (context.Request.Body.CanRead) diff --git a/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsChangeEndpoint.cs b/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsChangeEndpoint.cs index 72cb8c4..7020c9d 100644 --- a/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsChangeEndpoint.cs +++ b/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsChangeEndpoint.cs @@ -16,7 +16,7 @@ public class SettingsChangeEndpoint : IEndpoint return ApiResponse.Fail("Invalid json string"); } - Dictionary jsonDictionary = await JsonManager.ConvertFromJson>(jsonRequest); + Dictionary jsonDictionary = await JsonManager.ConvertFromJson>(jsonRequest); foreach (var (key, value) in jsonDictionary) { Application.CurrentApplication.ApplicationEnvironmentVariables.Set(key, value); diff --git a/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsGetEndpoint.cs b/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsGetEndpoint.cs index 0818765..63cf566 100644 --- a/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsGetEndpoint.cs +++ b/DiscordBotCore/API/Endpoints/SettingsManagement/SettingsGetEndpoint.cs @@ -11,16 +11,11 @@ public class SettingsGetEndpoint : IEndpoint public EndpointType HttpMethod => EndpointType.Get; public async Task HandleRequest(string? jsonRequest) { - if (string.IsNullOrEmpty(jsonRequest)) - { - return ApiResponse.Fail("The json from the request was empty"); - } - Dictionary jsonSettingsDictionary = new Dictionary() { {"token", Application.CurrentApplication.ApplicationEnvironmentVariables.Get("token", string.Empty)}, {"prefix", Application.CurrentApplication.ApplicationEnvironmentVariables.Get("prefix", string.Empty)}, - {"ServerIDs", Application.CurrentApplication.ApplicationEnvironmentVariables.GetList("ServerIDs", new List())} + {"serverIds", Application.CurrentApplication.ApplicationEnvironmentVariables.GetList("ServerID", new List())} }; string jsonResponse = await JsonManager.ConvertToJsonString(jsonSettingsDictionary); diff --git a/DiscordBotCore/Application.cs b/DiscordBotCore/Application.cs index d8191e8..470826e 100644 --- a/DiscordBotCore/Application.cs +++ b/DiscordBotCore/Application.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Threading; using System.Threading.Tasks; using DiscordBotCore.API; using DiscordBotCore.API.Endpoints; @@ -82,7 +81,7 @@ namespace DiscordBotCore CurrentApplication.Logger = new Logger(_LogsFolder, _LogFormat); - if (!File.Exists(_PluginsDatabaseFile)) + if (!File.Exists(_PluginsDatabaseFile)) { List plugins = new(); await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins); diff --git a/DiscordBotCore/Others/Settings/CustomSettingsDictionaryBase.cs b/DiscordBotCore/Others/Settings/CustomSettingsDictionaryBase.cs index 42264c0..67e0d62 100644 --- a/DiscordBotCore/Others/Settings/CustomSettingsDictionaryBase.cs +++ b/DiscordBotCore/Others/Settings/CustomSettingsDictionaryBase.cs @@ -96,6 +96,8 @@ public abstract class CustomSettingsDictionaryBase : ICustomSetting return list; } + Application.CurrentApplication.Logger.Log($"Key '{key}' not found in settings dictionary. Adding default value.", LogType.Warning); + return defaultValue; } diff --git a/DiscordBotCore/Repository/PluginRepository.cs b/DiscordBotCore/Repository/PluginRepository.cs index 02388d5..356c8e6 100644 --- a/DiscordBotCore/Repository/PluginRepository.cs +++ b/DiscordBotCore/Repository/PluginRepository.cs @@ -31,7 +31,6 @@ public sealed class PluginRepository : RepositoryBase return Default; } - try { var pluginRepoDict = Application.CurrentApplication.ApplicationEnvironmentVariables.GetDictionary("PluginRepository"); diff --git a/DiscordBotWebUI/Components/CustomTags/SettingsComponent.razor b/DiscordBotWebUI/Components/CustomTags/SettingsComponent.razor index b1cdf49..b880aac 100644 --- a/DiscordBotWebUI/Components/CustomTags/SettingsComponent.razor +++ b/DiscordBotWebUI/Components/CustomTags/SettingsComponent.razor @@ -1,5 +1,5 @@ @inject DialogService DialogService - +@inject NotificationService NotificationService
@@ -9,21 +9,24 @@ Name="token" Placeholder="Enter your token here ..." Style="width: 100%;" - bind-Value="@TokenString" /> + Value="@TokenString" + ValueChanged="str => TokenString = str"/> + Value="@PrefixString" + ValueChanged="str => PrefixString = str" /> + Value="@ServerIdsString" + ValueChanged="str => ServerIdsString = str" /> @@ -32,12 +35,16 @@ @code { - private string TokenString { get; set; } - private string PrefixString { get; set; } - private string ServerIdsString { get; set; } + [Parameter] + public string TokenString { get; set; } + [Parameter] + public string PrefixString { get; set; } + [Parameter] + public string ServerIdsString { get; set; } [Parameter] - public required Action SaveSettings { get; set; } + public required Action SaveSettings { get; set; } + private async void SaveButtonClick() { @@ -49,18 +56,104 @@ OkButtonText = "Restart Now", CancelButtonText = "Don't Save" }); - + if (!response.HasValue) { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Error, + Summary = "Error", + Detail = "An error occurred while trying to save settings." + }); return; } if (!response.Value) { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Info, + Summary = "Info", + Detail = "Settings were not saved." + }); + return; + } + + if (string.IsNullOrWhiteSpace(TokenString) || string.IsNullOrWhiteSpace(PrefixString) || string.IsNullOrWhiteSpace(ServerIdsString)) + { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Error, + Summary = "Error", + Detail = "Please fill in all fields." + }); + return; + } + + if(!ValidateToken()) + { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Error, + Summary = "Error", + Detail = "Invalid token." + }); + return; + } + + if(!ValidatePrefix()) + { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Error, + Summary = "Error", + Detail = "Invalid prefix." + }); + return; + } + + if(!ValidateServerIds()) + { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Error, + Summary = "Error", + Detail = "Invalid server IDs." + }); return; } - SaveSettings.Invoke(); + SaveSettings.Invoke(TokenString, PrefixString, ServerIdsString); + } + + private bool ValidateToken() + { + if(TokenString.Length < 59) + { + return false; + } + + return true; + } + + private bool ValidatePrefix() + { + if(PrefixString.Length < 1) + { + return false; + } + + return true; + } + + private bool ValidateServerIds() + { + if(ServerIdsString.Length < 1) + { + return false; + } + + return true; } } \ No newline at end of file diff --git a/DiscordBotWebUI/Components/Pages/SidebarPages/Settings.razor b/DiscordBotWebUI/Components/Pages/SidebarPages/Settings.razor index 9feaba1..b20b04b 100644 --- a/DiscordBotWebUI/Components/Pages/SidebarPages/Settings.razor +++ b/DiscordBotWebUI/Components/Pages/SidebarPages/Settings.razor @@ -1,5 +1,84 @@ @page "/settings" @using DiscordBotWebUI.Components.CustomTags +@using DiscordBotWebUI.ServerCommunication + +@inject NotificationService NotificationService Settings - \ No newline at end of file +@if (SettingsLoaded) +{ + +} +else +{ +

Loading...

+} + + +@code { + private string Token { get; set; } + private string Prefix { get; set; } + private string ServerIds { get; set; } + + private bool SettingsLoaded { get; set; } + + [Inject] + private ApiHandler ApiHandler { get; set; } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if(!firstRender) + { + return; + } + + var response = await ApiHandler.GetAsync("/api/settings/get"); + if (!response.Success) + { + return; + } + + Dictionary? settings = await JsonManager.ConvertFromJson>(response.Message); + + if (settings == null) + { + return; + } + + Token = settings["token"].ToString(); + Prefix = settings["prefix"].ToString(); + var serverIds = await JsonManager.ConvertFromJson>(settings["serverIds"].ToString()); + ServerIds = string.Join(";", serverIds); + + SettingsLoaded = true; + + StateHasChanged(); + } + + private async void SaveSettings(string token, string prefix, string serverIds) + { + var dict = new Dictionary + { + {"token", token}, + {"prefix", prefix}, + {"ServerID", serverIds.Split(';').Select(ulong.Parse).ToList()} + }; + + string json = await JsonManager.ConvertToJsonString(dict); + var response = await ApiHandler.PostAsync("/api/settings/update", json); + + if (!response.Success) + { + NotificationService.Notify(new NotificationMessage() + { + Severity = NotificationSeverity.Error, + Summary = "Error", + Detail = response.Message + }); + } + } + +} \ No newline at end of file