Fixed plugin refresh command and added new method for executing tasks without return type in ConsoleUtilities

This commit is contained in:
2023-09-25 22:06:42 +03:00
parent c577f625c2
commit 89c4932cd7
8 changed files with 78 additions and 57 deletions

View File

@@ -1,6 +1,5 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others; using PluginManager.Others;

View File

@@ -40,25 +40,33 @@ public class Plugin : ICommandAction
switch (args[0]) switch (args[0])
{ {
case "refresh": case "refresh":
await Program.internalActionManager.Refresh(); await RefreshPlugins(true);
break; break;
case "list": case "list":
var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetAvailablePlugins(), "Loading plugins..."); var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetAvailablePlugins(), "Loading plugins...");
TableData tableData = new(new List<string> { "Name", "Description", "Type", "Version" }); TableData tableData = new(new List<string> { "Name", "Description", "Type", "Version" });
foreach (var plugin in data) tableData.AddRow(plugin); foreach (var plugin in data) tableData.AddRow(plugin);
tableData.HasRoundBorders = false; tableData.HasRoundBorders = false;
tableData.PrintAsTable(); tableData.PrintAsTable();
break; break;
case "load": case "load":
if (pluginsLoaded) if (pluginsLoaded)
break; break;
if (Config.DiscordBot is null)
{
AnsiConsole.MarkupLine("[red]Discord bot not initialized[/]");
break;
}
var loader = new PluginLoader(Config.DiscordBot.client); var loader = new PluginLoader(Config.DiscordBot.client);
if (args.Length == 2 && args[1] == "-q") if (args.Length == 2 && args[1] == "-q")
{ {
Console.WriteLine("Loading plugins in quiet mode...");
loader.LoadPlugins(); loader.LoadPlugins();
pluginsLoaded = true; pluginsLoaded = true;
break; break;
@@ -152,13 +160,10 @@ public class Plugin : ICommandAction
} }
} }
private async Task RefreshPlugins() private async Task RefreshPlugins(bool quiet)
{ {
Console.WriteLine("Reloading plugins list..."); await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty);
await Program.internalActionManager.Execute("plugin", "load");
await Program.internalActionManager.Refresh(); await Program.internalActionManager.Refresh();
Console.WriteLine("Finished reloading plugins list");
} }
@@ -199,7 +204,7 @@ public class Plugin : ICommandAction
if (pluginRequirements == string.Empty) if (pluginRequirements == string.Empty)
{ {
Console.WriteLine("Finished installing " + pluginName + " successfully"); Console.WriteLine("Finished installing " + pluginName + " successfully");
await RefreshPlugins(); await RefreshPlugins(false);
return; return;
} }
@@ -255,7 +260,7 @@ public class Plugin : ICommandAction
} }
}); });
await RefreshPlugins(); await RefreshPlugins(false);
} }
} }

View File

@@ -25,9 +25,7 @@ public class Entry
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{ {
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries");
"./Libraries"
);
var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll"); var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
if (!File.Exists(assemblyPath)) return null; if (!File.Exists(assemblyPath)) return null;
var assembly = Assembly.LoadFrom(assemblyPath); var assembly = Assembly.LoadFrom(assemblyPath);

View File

@@ -1,4 +1,3 @@
using System;
using PluginManager; using PluginManager;
using Spectre.Console; using Spectre.Console;
@@ -8,13 +7,14 @@ public static class Installer
{ {
public static void GenerateStartupConfig() public static void GenerateStartupConfig()
{ {
AnsiConsole.WriteLine("Welcome to the [bold]SethBot[/] installer !"); AnsiConsole.MarkupLine("Welcome to the [bold]SethBot[/] installer !");
AnsiConsole.WriteLine("First, we need to configure the bot. Don't worry, it will be quick !"); AnsiConsole.MarkupLine("First, we need to configure the bot. Don't worry, it will be quick !");
var token = AnsiConsole.Ask<string>("Please enter the bot token :");
var prefix = AnsiConsole.Ask<string>("Please enter the bot prefix :");
var serverId = AnsiConsole.Ask<string>("Please enter the Server ID :");
var token = AnsiConsole.Ask<string>("Please enter the bot [yellow]token[/]:");
var prefix = AnsiConsole.Ask<string>("Please enter the bot [yellow]prefix[/]:");
var serverId = AnsiConsole.Ask<string>("Please enter the [yellow]Server ID[/]:");
if (string.IsNullOrWhiteSpace(serverId)) serverId = "NULL";
Config.AppSettings.Add("token", token); Config.AppSettings.Add("token", token);
Config.AppSettings.Add("prefix", prefix); Config.AppSettings.Add("prefix", prefix);
Config.AppSettings.Add("ServerID", serverId); Config.AppSettings.Add("ServerID", serverId);

View File

@@ -22,13 +22,8 @@ public class Program
public static void Startup(string[] args) public static void Startup(string[] args)
{ {
PreLoadComponents(args).Wait(); PreLoadComponents(args).Wait();
if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix"))
AppSettings["token"] == null ||
AppSettings["token"]?.Length != 70 && AppSettings["token"]?.Length != 59 ||
!AppSettings.ContainsKey("prefix") || AppSettings["prefix"] == null ||
AppSettings["prefix"]?.Length != 1 ||
args.Length == 1 && args[0] == "/reset")
Installer.GenerateStartupConfig(); Installer.GenerateStartupConfig();
HandleInput().Wait(); HandleInput().Wait();
@@ -67,8 +62,9 @@ public class Program
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); Console.WriteLine($"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Console.WriteLine("Git URL: https://github.com/andreitdr/SethDiscordBot"); Console.WriteLine("Git SethBot: https://github.com/andreitdr/SethDiscordBot");
Console.WriteLine("Git Plugins: https://github.com/andreitdr/SethPlugins");
ConsoleUtilities.WriteColorText("&rRemember to close the bot using the ShutDown command (&yexit&r) or some settings won't be saved"); ConsoleUtilities.WriteColorText("&rRemember to close the bot using the ShutDown command (&yexit&r) or some settings won't be saved");
ConsoleUtilities.WriteColorText($"Running on &m{Functions.GetOperatingSystem()}"); ConsoleUtilities.WriteColorText($"Running on &m{Functions.GetOperatingSystem()}");
@@ -106,12 +102,12 @@ public class Program
{ {
if (AppSettings.ContainsKey("LaunchMessage")) if (AppSettings.ContainsKey("LaunchMessage"))
AppSettings.Add("LaunchMessage", AppSettings.Add("LaunchMessage",
"An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !" "An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
); "There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !");
Logger
.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"Bot", LogLevel.ERROR "There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !",
); "Bot", LogLevel.ERROR);
} }
} }
} }

View File

@@ -40,23 +40,46 @@ public static class ConsoleUtilities
{ {
T result = default; T result = default;
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns(new ProgressColumn[] .Columns(
{ new ProgressColumn[]
new TaskDescriptionColumn(), {
new ProgressBarColumn(), new TaskDescriptionColumn(),
new PercentageColumn(), new ProgressBarColumn(),
}) new PercentageColumn(),
.StartAsync(async ctx => }
{ )
var task = ctx.AddTask(message); .StartAsync(
task.IsIndeterminate = true; async ctx =>
result = await function; {
task.Increment(100); var task = ctx.AddTask(message);
task.IsIndeterminate = true;
}); result = await function;
task.Increment(100);
}
);
return result; return result;
} }
public static async Task ExecuteWithProgressBar(Task function, string message)
{
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
})
.StartAsync(async ctx =>
{
var task = ctx.AddTask(message);
task.IsIndeterminate = true;
await function;
task.Increment(100);
});
}
private static readonly Dictionary<char, ConsoleColor> Colors = new() private static readonly Dictionary<char, ConsoleColor> Colors = new()
{ {

View File

@@ -9,9 +9,9 @@ namespace PluginManager;
public class Config public class Config
{ {
private static bool IsLoaded; private static bool _isLoaded;
public static DBLogger Logger; public static DBLogger? Logger;
public static SettingsDictionary<string, string>? AppSettings; public static SettingsDictionary<string, string> AppSettings;
internal static Boot? _DiscordBotClient; internal static Boot? _DiscordBotClient;
@@ -19,8 +19,8 @@ public class Config
public static async Task Initialize() public static async Task Initialize()
{ {
if (IsLoaded) return; if (_isLoaded) return;
Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS"); Directory.CreateDirectory("./Data/PAKS");
@@ -36,7 +36,7 @@ public class Config
ArchiveManager.Initialize(); ArchiveManager.Initialize();
IsLoaded = true; _isLoaded = true;
Logger.Log("Config initialized", LogLevel.INFO); Logger.Log("Config initialized", LogLevel.INFO);
} }

View File

@@ -29,7 +29,7 @@ public class InternalActionManager
public async Task Refresh() public async Task Refresh()
{ {
Actions.Clear(); Actions.Clear();
await Initialize(); await Initialize();
} }