Updated settings change route

This commit is contained in:
2025-01-13 12:27:35 +02:00
parent 49fe637455
commit 7ebe3e7014
10 changed files with 194 additions and 28 deletions

View File

@@ -21,7 +21,6 @@ public static class Installer
}
AnsiConsole.MarkupLine($"Invalid {key} !");
Environment.Exit(-20);
return value;

0
DiscordBot/builder.sh Normal file → Executable file
View File

View File

@@ -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)

View File

@@ -16,7 +16,7 @@ public class SettingsChangeEndpoint : IEndpoint
return ApiResponse.Fail("Invalid json string");
}
Dictionary<string, string> jsonDictionary = await JsonManager.ConvertFromJson<Dictionary<string, string>>(jsonRequest);
Dictionary<string, object> jsonDictionary = await JsonManager.ConvertFromJson<Dictionary<string, object>>(jsonRequest);
foreach (var (key, value) in jsonDictionary)
{
Application.CurrentApplication.ApplicationEnvironmentVariables.Set(key, value);

View File

@@ -11,16 +11,11 @@ public class SettingsGetEndpoint : IEndpoint
public EndpointType HttpMethod => EndpointType.Get;
public async Task<ApiResponse> HandleRequest(string? jsonRequest)
{
if (string.IsNullOrEmpty(jsonRequest))
{
return ApiResponse.Fail("The json from the request was empty");
}
Dictionary<string, object> jsonSettingsDictionary = new Dictionary<string, object>()
{
{"token", Application.CurrentApplication.ApplicationEnvironmentVariables.Get("token", string.Empty)},
{"prefix", Application.CurrentApplication.ApplicationEnvironmentVariables.Get("prefix", string.Empty)},
{"ServerIDs", Application.CurrentApplication.ApplicationEnvironmentVariables.GetList("ServerIDs", new List<ulong>())}
{"serverIds", Application.CurrentApplication.ApplicationEnvironmentVariables.GetList("ServerID", new List<ulong>())}
};
string jsonResponse = await JsonManager.ConvertToJsonString(jsonSettingsDictionary);

View File

@@ -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<PluginInfo> plugins = new();
await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins);

View File

@@ -96,6 +96,8 @@ public abstract class CustomSettingsDictionaryBase<TKey,TValue> : ICustomSetting
return list;
}
Application.CurrentApplication.Logger.Log($"Key '{key}' not found in settings dictionary. Adding default value.", LogType.Warning);
return defaultValue;
}

View File

@@ -31,7 +31,6 @@ public sealed class PluginRepository : RepositoryBase
return Default;
}
try
{
var pluginRepoDict = Application.CurrentApplication.ApplicationEnvironmentVariables.GetDictionary<string, string>("PluginRepository");

View File

@@ -1,5 +1,5 @@
@inject DialogService DialogService
@inject NotificationService NotificationService
<div style="display: flex; justify-content: center; align-items: center; height: 100vh; background-color: transparent;">
<RadzenCard Style="padding: 2rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.2); width: 50%; max-width: 600px;">
<RadzenStack Orientation="Orientation.Vertical" Gap="20px" Style="color: white;">
@@ -9,21 +9,24 @@
Name="token"
Placeholder="Enter your token here ..."
Style="width: 100%;"
bind-Value="@TokenString" />
Value="@TokenString"
ValueChanged="str => TokenString = str"/>
<RadzenLabel Text="Specify the bot's prefix:" />
<RadzenTextBox
id="prefix"
Name="prefix"
Placeholder="Enter your prefix here ..."
Style="width: 100%;"
bind-Value="@PrefixString" />
Value="@PrefixString"
ValueChanged="str => PrefixString = str" />
<RadzenLabel Text="Enter server IDs (separated by semicolons):" />
<RadzenTextBox
id="server"
Name="server"
Placeholder="Enter server IDs here ..."
Style="width: 100%;"
bind-Value="@ServerIdsString" />
Value="@ServerIdsString"
ValueChanged="str => ServerIdsString = str" />
<RadzenButton Text="Save Changes" Click="SaveButtonClick" Style="margin-top: 1rem;" />
</RadzenStack>
@@ -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<string, string, string> 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;
}
}

View File

@@ -1,5 +1,84 @@
@page "/settings"
@using DiscordBotWebUI.Components.CustomTags
@using DiscordBotWebUI.ServerCommunication
@inject NotificationService NotificationService
<PageTitle>Settings</PageTitle>
<SettingsComponent/>
@if (SettingsLoaded)
{
<SettingsComponent SaveSettings="SaveSettings"
TokenString="@Token"
PrefixString="@Prefix"
ServerIdsString="@ServerIds"/>
}
else
{
<p>Loading...</p>
}
@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<string, object>? settings = await JsonManager.ConvertFromJson<Dictionary<string, object>>(response.Message);
if (settings == null)
{
return;
}
Token = settings["token"].ToString();
Prefix = settings["prefix"].ToString();
var serverIds = await JsonManager.ConvertFromJson<List<ulong>>(settings["serverIds"].ToString());
ServerIds = string.Join(";", serverIds);
SettingsLoaded = true;
StateHasChanged();
}
private async void SaveSettings(string token, string prefix, string serverIds)
{
var dict = new Dictionary<string, object>
{
{"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
});
}
}
}