From 5edcf933715d56b323e04b8c002deb25be852658 Mon Sep 17 00:00:00 2001 From: Tudor Andrei Date: Tue, 25 Apr 2023 14:27:55 +0300 Subject: [PATCH] cleaning up PluginManager (phase 1) --- DiscordBot/Discord/Commands/Help.cs | 2 +- DiscordBot/Program.cs | 19 +-- .../Items => DiscordBot/Utilities}/Command.cs | 2 +- .../Utilities}/Console Utilities.cs | 112 ++++++++---------- .../Utilities}/ConsoleCommandsHandler.cs | 104 ++++++++-------- DiscordBot/Utilities/Enums.cs | 21 ++++ .../DiscordBotUI/DiscordBot/Commands/Help.cs | 2 +- PluginManager/Bot/CommandHandler.cs | 2 +- PluginManager/Interfaces/DBCommand.cs | 10 +- PluginManager/Online/PluginsManager.cs | 16 +-- PluginManager/Online/ServerCom.cs | 44 +------ PluginManager/Others/Actions/ActionManager.cs | 51 ++++++++ .../Others/Actions/InternalAction.cs | 40 +++++++ PluginManager/Others/ArchiveManager.cs | 2 +- ...Args.cs => DBCommandExecutingArguments.cs} | 4 +- PluginManager/Others/Enums.cs | 13 -- PluginManager/PluginManager.csproj | 3 - 17 files changed, 247 insertions(+), 200 deletions(-) rename {PluginManager/Items => DiscordBot/Utilities}/Command.cs (90%) rename {PluginManager/Others => DiscordBot/Utilities}/Console Utilities.cs (73%) rename {PluginManager/Items => DiscordBot/Utilities}/ConsoleCommandsHandler.cs (82%) create mode 100644 DiscordBot/Utilities/Enums.cs create mode 100644 PluginManager/Others/Actions/ActionManager.cs create mode 100644 PluginManager/Others/Actions/InternalAction.cs rename PluginManager/Others/{CmdArgs.cs => DBCommandExecutingArguments.cs} (77%) diff --git a/DiscordBot/Discord/Commands/Help.cs b/DiscordBot/Discord/Commands/Help.cs index 52855c6..0b38d15 100644 --- a/DiscordBot/Discord/Commands/Help.cs +++ b/DiscordBot/Discord/Commands/Help.cs @@ -40,7 +40,7 @@ internal class Help : DBCommand /// The main body of the command /// /// The command context - public void ExecuteServer(CmdArgs args) + public void ExecuteServer(DBCommandExecutingArguments args) { if (args.arguments is not null) { diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index dbe55d4..f7ef03a 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -8,12 +8,13 @@ using System.Threading.Tasks; using PluginManager; using PluginManager.Bot; -using PluginManager.Items; using PluginManager.Online; using PluginManager.Online.Helpers; using PluginManager.Others; using PluginManager.WindowManagement; +using DiscordBot.Utilities; + using OperatingSystem = PluginManager.Others.OperatingSystem; namespace DiscordBot; @@ -89,15 +90,15 @@ public class Program $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}"); - Utilities.WriteColorText( + Utilities.Utilities.WriteColorText( "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); Console.ForegroundColor = ConsoleColor.White; if (Config.Data.ContainsKey("LaunchMessage")) - Utilities.WriteColorText(Config.Data["LaunchMessage"]); + Utilities.Utilities.WriteColorText(Config.Data["LaunchMessage"]); - Utilities.WriteColorText( + Utilities.Utilities.WriteColorText( "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); Logger.WriteLine(); @@ -172,7 +173,7 @@ public class Program Logger.WriteLine("Loading resources ..."); - var main = new Utilities.ProgressBar(ProgressBarType.NO_END); + var main = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END); main.Start(); if (Config.Data.ContainsKey("DeleteLogsAtStartup")) @@ -257,7 +258,7 @@ public class Program List changeLog = await ServerCom.ReadTextFromURL( "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot"); foreach (var item in changeLog) - Utilities.WriteColorText(item); + Utilities.Utilities.WriteColorText(item); Logger.WriteLine("Do you want to update the bot ? (y/n)"); if (Console.ReadKey().Key == ConsoleKey.Y) { @@ -311,11 +312,11 @@ public class Program { Console.Clear(); Logger.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !"); - var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); + var bar = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); - await ServerCom.DownloadFileNoProgressAsync( + await ServerCom.DownloadFileAsync( "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Launcher.exe", - $"./Launcher.exe"); + $"./Launcher.exe", null); //await ArchiveManager.ExtractArchive("./Updater.zip", "./", null, // UnzipProgressType.PercentageFromTotalSize); Config.Data["LauncherVersion"] = updaternewversion; diff --git a/PluginManager/Items/Command.cs b/DiscordBot/Utilities/Command.cs similarity index 90% rename from PluginManager/Items/Command.cs rename to DiscordBot/Utilities/Command.cs index 5af209c..a52fca5 100644 --- a/PluginManager/Items/Command.cs +++ b/DiscordBot/Utilities/Command.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using Discord.Commands; using Discord.WebSocket; -namespace PluginManager.Items; +namespace DiscordBot.Utilities; public class ConsoleCommand { diff --git a/PluginManager/Others/Console Utilities.cs b/DiscordBot/Utilities/Console Utilities.cs similarity index 73% rename from PluginManager/Others/Console Utilities.cs rename to DiscordBot/Utilities/Console Utilities.cs index 881dfce..1834cbc 100644 --- a/PluginManager/Others/Console Utilities.cs +++ b/DiscordBot/Utilities/Console Utilities.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using PluginManager; -namespace PluginManager.Others; +namespace DiscordBot.Utilities; public static class Utilities { @@ -48,38 +48,38 @@ public static class Utilities foreach (var row in data) { if (row[0][0] == tableLine) - PluginManager.Logger.Write(tableCross); + Console.Write(tableCross); else - PluginManager.Logger.Write(tableWall); + Console.Write(tableWall); for (var l = 0; l < row.Length; l++) { if (row[l][0] == tableLine) { for (var i = 0; i < len[l] + 4; ++i) - PluginManager.Logger.Write(tableLine); + Console.Write(tableLine); } else if (row[l].Length == len[l]) { - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write(row[l]); - PluginManager.Logger.Write(" "); + Console.Write(" "); + Console.Write(row[l]); + Console.Write(" "); } else { var lenHalf = row[l].Length / 2; for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write(row[l]); + Console.Write(" "); + Console.Write(row[l]); for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) - PluginManager.Logger.Write(" "); + Console.Write(" "); if (row[l].Length % 2 == 0) - PluginManager.Logger.Write(" "); + Console.Write(" "); } - PluginManager.Logger.Write(row[l][0] == tableLine ? tableCross : tableWall); + Console.Write(row[l][0] == tableLine ? tableCross : tableWall); } - PluginManager.Logger.WriteLine(); //end line + Console.WriteLine(); //end line } return; @@ -97,44 +97,44 @@ public static class Utilities foreach (var row in data) { - PluginManager.Logger.Write("\t"); + Console.Write("\t"); if (row[0] == "-") - PluginManager.Logger.Write("+"); + Console.Write("+"); else - PluginManager.Logger.Write("|"); + Console.Write("|"); foreach (var s in row) { if (s == "-") { for (var i = 0; i < maxLen + 4; ++i) - PluginManager.Logger.Write("-"); + Console.Write("-"); } else if (s.Length == maxLen) { - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write(s); - PluginManager.Logger.Write(" "); + Console.Write(" "); + Console.Write(s); + Console.Write(" "); } else { var lenHalf = s.Length / 2; for (var i = 0; i < div - lenHalf; ++i) - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write(s); + Console.Write(" "); + Console.Write(s); for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) - PluginManager.Logger.Write(" "); + Console.Write(" "); if (s.Length % 2 == 0) - PluginManager.Logger.Write(" "); + Console.Write(" "); } if (s == "-") - PluginManager.Logger.Write("+"); + Console.Write("+"); else - PluginManager.Logger.Write("|"); + Console.Write("|"); } - PluginManager.Logger.WriteLine(); //end line + Console.WriteLine(); //end line } return; @@ -155,12 +155,12 @@ public static class Utilities { if (data[i][j] == "-") data[i][j] = " "; - PluginManager.Logger.Write(data[i][j]); + Console.Write(data[i][j]); for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) - PluginManager.Logger.Write(" "); + Console.Write(" "); } - PluginManager.Logger.WriteLine(); + Console.WriteLine(); } return; @@ -171,16 +171,6 @@ public static class Utilities public static void WriteColorText(string text, bool appendNewLineAtEnd = true) { - if (!PluginManager.Logger.isConsole) - { - foreach (var item in Colors) - text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", ""); - PluginManager.Logger.Write(text); - if (appendNewLineAtEnd) - PluginManager.Logger.WriteLine(); - return; - - } var initialForeGround = Console.ForegroundColor; var input = text.ToCharArray(); for (var i = 0; i < input.Length; i++) @@ -202,12 +192,12 @@ public static class Utilities } else { - PluginManager.Logger.Write(input[i]); + Console.Write(input[i]); } Console.ForegroundColor = initialForeGround; if (appendNewLineAtEnd) - PluginManager.Logger.WriteLine(); + Console.WriteLine(); } @@ -224,8 +214,6 @@ public static class Utilities public ProgressBar(ProgressBarType type) { - if (!PluginManager.Logger.isConsole) - throw new Exception("This class (or function) can be used with console only. For UI please use another approach."); this.type = type; } @@ -286,9 +274,9 @@ public static class Utilities { Console.CursorLeft = 0; for (var i = 0; i < BarLength + message.Length + 1; i++) - PluginManager.Logger.Write(" "); + Console.Write(" "); Console.CursorLeft = 0; - PluginManager.Logger.WriteLine(message); + Console.WriteLine(message); } } @@ -303,14 +291,14 @@ public static class Utilities private void UpdateNoEnd(string message) { Console.CursorLeft = 0; - PluginManager.Logger.Write("["); + Console.Write("["); for (var i = 1; i <= position; i++) - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write("<==()==>"); + Console.Write(" "); + Console.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write("] " + message); + Console.Write(" "); + Console.Write("] " + message); if (position == BarLength - 1 || position == 1) @@ -320,14 +308,14 @@ public static class Utilities private void UpdateNoEnd() { Console.CursorLeft = 0; - PluginManager.Logger.Write("["); + Console.Write("["); for (var i = 1; i <= position; i++) - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write("<==()==>"); + Console.Write(" "); + Console.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - PluginManager.Logger.Write(" "); - PluginManager.Logger.Write("]"); + Console.Write(" "); + Console.Write("]"); if (position == BarLength - 1 || position == 1) @@ -337,9 +325,9 @@ public static class Utilities private void UpdateNormal(float progress) { Console.CursorLeft = 0; - PluginManager.Logger.Write("["); + Console.Write("["); Console.CursorLeft = BarLength; - PluginManager.Logger.Write("]"); + Console.Write("]"); Console.CursorLeft = 1; var onechunk = 30.0f / Max; @@ -349,22 +337,22 @@ public static class Utilities { Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.CursorLeft = position++; - PluginManager.Logger.Write("#"); + Console.Write("#"); } for (var i = position; i < BarLength; i++) { Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.CursorLeft = position++; - PluginManager.Logger.Write(" "); + Console.Write(" "); } Console.CursorLeft = BarLength + 4; Console.BackgroundColor = ConsoleColor.Black; if (progress.CanAproximateTo(Max)) - PluginManager.Logger.Write(progress + " % ✓"); + Console.Write(progress + " % ✓"); else - PluginManager.Logger.Write(MathF.Round(progress, 2) + " % "); + Console.Write(MathF.Round(progress, 2) + " % "); } } } \ No newline at end of file diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/DiscordBot/Utilities/ConsoleCommandsHandler.cs similarity index 82% rename from PluginManager/Items/ConsoleCommandsHandler.cs rename to DiscordBot/Utilities/ConsoleCommandsHandler.cs index 9753ed6..f2d50b8 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/DiscordBot/Utilities/ConsoleCommandsHandler.cs @@ -9,13 +9,14 @@ using System.Threading.Tasks; using Discord.WebSocket; +using PluginManager; using PluginManager.Loaders; using PluginManager.Online; using PluginManager.Others; using OperatingSystem = PluginManager.Others.OperatingSystem; -namespace PluginManager.Items; +namespace DiscordBot.Utilities; public class ConsoleCommandsHandler { @@ -31,12 +32,11 @@ public class ConsoleCommandsHandler public ConsoleCommandsHandler(DiscordSocketClient client) { - if (!Logger.isConsole) throw new Exception("Can not use ConsoleCommandsHandler for Non console apps"); this.client = client; InitializeBasicCommands(); - //Logger.WriteLine("Initialized console command handler !"); + //Console.WriteLine("Initialized console command handler !"); } private void InitializeBasicCommands() @@ -47,7 +47,7 @@ public class ConsoleCommandsHandler { if (args.Length <= 1) { - Logger.WriteLine("Available commands:"); + Console.WriteLine("Available commands:"); var items = new List { new[] { "-", "-", "-" }, @@ -70,12 +70,12 @@ public class ConsoleCommandsHandler foreach (var command in commandList) if (command.CommandName == args[1]) { - Logger.WriteLine("Command description: " + command.Description); - Logger.WriteLine("Command execution format:" + command.Usage); + Console.WriteLine("Command description: " + command.Description); + Console.WriteLine("Command execution format:" + command.Usage); return; } - Logger.WriteLine("Command not found"); + Console.WriteLine("Command not found"); } } ); @@ -94,16 +94,16 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Logger.WriteLine("[CMD] Successfully loaded command : " + name); + Console.WriteLine("[CMD] Successfully loaded command : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; if (exception is null) - Logger.WriteLine("An error occured while loading: " + name); + Console.WriteLine("An error occured while loading: " + name); else - Logger.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); + Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -116,12 +116,12 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Logger.WriteLine("[EVENT] Successfully loaded event : " + name); + Console.WriteLine("[EVENT] Successfully loaded event : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; - Logger.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); + Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -135,12 +135,12 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Logger.WriteLine("[SLASH] Successfully loaded command : " + name); + Console.WriteLine("[SLASH] Successfully loaded command : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; - Logger.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); + Console.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -152,7 +152,23 @@ public class ConsoleCommandsHandler } ); - AddCommand("listplugs", "list available plugins", () => { manager.ListAvailablePlugins().Wait(); }); + AddCommand("listplugs", "list available plugins", async () => { + var data = await manager.GetAvailablePlugins(); + var items = new List + { + new[] { "-", "-", "-", "-" }, + new[] { "Name", "Type", "Description", "Required" }, + new[] { "-", "-", "-", "-" } + }; + + foreach (var plugin in data) + { + items.Add(new[] { plugin[0], plugin[1], plugin[2], plugin[3] }); + } + + items.Add(new[] { "-", "-", "-", "-" }); + Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT); + }); AddCommand("dwplug", "download plugin", "dwplug [name]", async args => { @@ -160,7 +176,7 @@ public class ConsoleCommandsHandler if (args.Length == 1) { isDownloading = false; - Logger.WriteLine("Please specify plugin name"); + Console.WriteLine("Please specify plugin name"); return; } @@ -192,24 +208,24 @@ public class ConsoleCommandsHandler if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { - await ServerCom.DownloadFileAsync(info[1], path); + await ServerCom.DownloadFileAsync(info[1], path, null); } else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) { var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); - await ServerCom.DownloadFileNoProgressAsync(info[1], path); + await ServerCom.DownloadFileAsync(info[1], path, null); bar.Stop("Plugin Downloaded !"); } - Logger.WriteLine("\n"); + Console.WriteLine("\n"); // check requirements if any if (info.Length == 3 && info[2] != string.Empty && info[2] != null) { - Logger.WriteLine($"Downloading requirements for plugin : {name}"); + Console.WriteLine($"Downloading requirements for plugin : {name}"); var lines = await ServerCom.ReadTextFromURL(info[2]); @@ -218,45 +234,45 @@ public class ConsoleCommandsHandler if (!(line.Length > 0 && line.Contains(","))) continue; var split = line.Split(','); - Logger.WriteLine($"\nDownloading item: {split[1]}"); + Console.WriteLine($"\nDownloading item: {split[1]}"); if (File.Exists("./" + split[1])) File.Delete("./" + split[1]); if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { - await ServerCom.DownloadFileAsync(split[0], "./" + split[1]); + await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null); } else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) { var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); - await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]); + await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null); bar.Stop("Item downloaded !"); } - Logger.WriteLine(); + Console.WriteLine(); if (split[0].EndsWith(".pak")) { File.Move("./" + split[1], "./Data/PAKS/" + split[1], true); } else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg")) { - Logger.WriteLine($"Extracting {split[1]} ..."); + Console.WriteLine($"Extracting {split[1]} ..."); var bar = new Utilities.ProgressBar( ProgressBarType.NO_END); bar.Start(); await ArchiveManager.ExtractArchive("./" + split[1], "./", null, UnzipProgressType.PercentageFromTotalSize); bar.Stop("Extracted"); - Logger.WriteLine("\n"); + Console.WriteLine("\n"); File.Delete("./" + split[1]); } } - Logger.WriteLine(); + Console.WriteLine(); } var ver = await ServerCom.GetVersionOfPackageFromWeb(name); if (ver is null) throw new Exception("Incorrect version"); - Config.Plugins[name] = ver.ToShortString(); + Config.Plugins[name] = ver.ToShortString(); isDownloading = false; @@ -273,7 +289,7 @@ public class ConsoleCommandsHandler return; var data = Config.Data[args[1]]; - Logger.WriteLine($"{args[1]} => {data}"); + Console.WriteLine($"{args[1]} => {data}"); } ); @@ -288,11 +304,11 @@ public class ConsoleCommandsHandler try { Config.Data[key] = value; - Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); + Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); } catch (Exception ex) { - Logger.WriteLine(ex.ToString()); + Console.WriteLine(ex.ToString()); } } ); @@ -341,7 +357,7 @@ public class ConsoleCommandsHandler } catch (Exception ex) { - Logger.WriteLine(ex.Message); + Console.WriteLine(ex.Message); } }); @@ -357,8 +373,8 @@ public class ConsoleCommandsHandler } catch (Exception ex) { - Logger.WriteLine(ex.Message); - Logger.WriteErrFile(ex); + Console.WriteLine(ex.Message); + Config.Logger.Log(ex.Message, this, TextType.ERROR); } }); @@ -392,13 +408,13 @@ public class ConsoleCommandsHandler if (!File.Exists(location)) { - Logger.WriteLine("The plugin does not exist"); + Console.WriteLine("The plugin does not exist"); return; } File.Delete(location); - Logger.WriteLine("Removed the plugin DLL. Checking for other files ..."); + Console.WriteLine("Removed the plugin DLL. Checking for other files ..."); var info = await manager.GetPluginLinkByName(plugName); if (info[2] != string.Empty) @@ -413,7 +429,7 @@ public class ConsoleCommandsHandler File.Delete("./" + split[1]); - Logger.WriteLine("Removed: " + split[1]); + Console.WriteLine("Removed: " + split[1]); } if (Directory.Exists($"./Data/Plugins/{plugName}")) @@ -424,7 +440,7 @@ public class ConsoleCommandsHandler } isDownloading = false; - Logger.WriteLine(plugName + " has been successfully deleted !"); + Console.WriteLine(plugName + " has been successfully deleted !"); }); AddCommand("reload", "Reload the bot with all plugins", () => @@ -484,7 +500,7 @@ public class ConsoleCommandsHandler foreach (var item in commandList) if (item.CommandName == args[0]) { - Logger.WriteLine(); + Console.WriteLine(); item.Action(args); } @@ -492,8 +508,6 @@ public class ConsoleCommandsHandler public static async Task ExecuteCommad(string command) { - if (!Logger.isConsole) - throw new Exception("Can not use console based commands on non console based application !"); var args = command.Split(' '); foreach (var item in commandList.ToList()) if (item.CommandName == args[0]) @@ -505,8 +519,6 @@ public class ConsoleCommandsHandler public bool HandleCommand(string command, bool removeCommandExecution = true) { - if (!Logger.isConsole) - throw new Exception("Can not use console based commands on non console based application !"); Console.ForegroundColor = ConsoleColor.White; var args = command.Split(' '); foreach (var item in commandList.ToList()) @@ -515,22 +527,20 @@ public class ConsoleCommandsHandler if (args[0].StartsWith("_")) throw new Exception("This command is reserved for internal worker and can not be executed manually !"); - if (Logger.isConsole) if (removeCommandExecution) { Console.SetCursorPosition(0, Console.CursorTop - 1); for (var i = 0; i < command.Length + 30; i++) - Logger.Write(" "); + Console.Write(" "); Console.SetCursorPosition(0, Console.CursorTop); } - Logger.WriteLine(); + Console.WriteLine(); item.Action(args); return true; } return false; - //Logger.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); } } \ No newline at end of file diff --git a/DiscordBot/Utilities/Enums.cs b/DiscordBot/Utilities/Enums.cs new file mode 100644 index 0000000..7a42cc4 --- /dev/null +++ b/DiscordBot/Utilities/Enums.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DiscordBot.Utilities +{ + public enum TableFormat + { + CENTER_EACH_COLUMN_BASED, + CENTER_OVERALL_LENGTH, + DEFAULT + } + + public enum ProgressBarType + { + NORMAL, + NO_END + } +} diff --git a/DiscordBotPlugins/DiscordBotUI/DiscordBot/Commands/Help.cs b/DiscordBotPlugins/DiscordBotUI/DiscordBot/Commands/Help.cs index 65d1300..adca615 100644 --- a/DiscordBotPlugins/DiscordBotUI/DiscordBot/Commands/Help.cs +++ b/DiscordBotPlugins/DiscordBotUI/DiscordBot/Commands/Help.cs @@ -40,7 +40,7 @@ internal class Help : DBCommand /// The main body of the command /// /// The command context - public void ExecuteServer(CmdArgs args) + public void ExecuteServer(DBCommandExecutingArguments args) { if (args.arguments is not null) { diff --git a/PluginManager/Bot/CommandHandler.cs b/PluginManager/Bot/CommandHandler.cs index d85923d..4c9d2ca 100644 --- a/PluginManager/Bot/CommandHandler.cs +++ b/PluginManager/Bot/CommandHandler.cs @@ -138,7 +138,7 @@ internal class CommandHandler if(split.Length > 1) argsClean = string.Join(' ', split, 1, split.Length-1).Split(' '); - CmdArgs cmd = new(context, cleanMessage, split[0], argsClean); + DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean); if (context.Channel is SocketDMChannel) plugin.ExecuteDM(cmd); diff --git a/PluginManager/Interfaces/DBCommand.cs b/PluginManager/Interfaces/DBCommand.cs index ee90e9f..67a7c09 100644 --- a/PluginManager/Interfaces/DBCommand.cs +++ b/PluginManager/Interfaces/DBCommand.cs @@ -1,6 +1,4 @@ using System.Collections.Generic; - -using Discord.Commands; using PluginManager.Others; namespace PluginManager.Interfaces; @@ -37,16 +35,16 @@ public interface DBCommand /// /// The main body of the command. This is what is executed when user calls the command in Server /// - /// The disocrd Context - void ExecuteServer(CmdArgs args) + /// The disocrd Context + void ExecuteServer(DBCommandExecutingArguments args) { } /// /// The main body of the command. This is what is executed when user calls the command in DM /// - /// The disocrd Context - void ExecuteDM(CmdArgs args) + /// The disocrd Context + void ExecuteDM(DBCommandExecutingArguments args) { } } \ No newline at end of file diff --git a/PluginManager/Online/PluginsManager.cs b/PluginManager/Online/PluginsManager.cs index fa71239..8e38d99 100644 --- a/PluginManager/Online/PluginsManager.cs +++ b/PluginManager/Online/PluginsManager.cs @@ -29,7 +29,7 @@ public class PluginsManager /// The method to load all plugins /// /// - public async Task> ListAvailablePlugins() + public async Task> GetAvailablePlugins() { try { @@ -40,16 +40,12 @@ public class PluginsManager var op = Functions.GetOperatingSystem(); var len = lines.Length; - string[] titles = { "Name", "Description", "Type", "Version" }; - data.Add(new[] { "-", "-", "-", "-" }); - data.Add(titles); - data.Add(new[] { "-", "-", "-", "-" }); for (var i = 0; i < len; i++) { if (lines[i].Length <= 2) continue; var content = lines[i].Split(','); - var display = new string[titles.Length]; + var display = new string[4]; // 4 columns if (op == OperatingSystem.WINDOWS) { if (content[4].Contains("Windows")) @@ -80,14 +76,11 @@ public class PluginsManager data.Add(new[] { "-", "-", "-", "-" }); - Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED); - return data; } catch (Exception exception) { - Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); - Logger.WriteErrFile(exception.ToString()); + Config.Logger.Log("Failed to execute command: listplugs\nReason: " + exception.Message, this, TextType.ERROR); } return null; @@ -120,8 +113,7 @@ public class PluginsManager } catch (Exception exception) { - Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); - Logger.WriteErrFile(exception.ToString()); + Config.Logger.Log("Failed to execute command: listplugs\nReason: " + exception.Message, this, TextType.ERROR); } return new string[] { null!, null!, null! }; diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs index c1f3b90..89d41d8 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/PluginManager/Online/ServerCom.cs @@ -33,7 +33,7 @@ public static class ServerCom /// The to track the download /// public static async Task DownloadFileAsync(string URL, string location, IProgress progress, - IProgress? downloadedBytes = null) + IProgress? downloadedBytes) { using (var client = new HttpClient()) { @@ -46,47 +46,9 @@ public static class ServerCom } } - /// - /// Download file from url - /// - /// The url to the file - /// The location where to store the downloaded data - /// - public static async Task DownloadFileAsync(string URL, string location) + public static async Task DownloadFileAsync(string URl, string location, IProgress progress) { - var isDownloading = true; - float c_progress = 0; - - var pbar = new Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true }; - - IProgress progress = new Progress(percent => { c_progress = percent; }); - - - var updateProgressBarTask = new Task(() => - { - while (isDownloading) - { - pbar.Update(c_progress); - if (c_progress == 100f) - break; - Thread.Sleep(500); - } - } - ); - - new Thread(updateProgressBarTask.Start).Start(); - await DownloadFileAsync(URL, location, progress); - - - c_progress = pbar.Max; - pbar.Update(100f); - isDownloading = false; - } - - public static async Task DownloadFileNoProgressAsync(string URL, string location) - { - IProgress progress = new Progress(); - await DownloadFileAsync(URL, location, progress); + await DownloadFileAsync(URl, location, progress, null); } public static async Task GetVersionOfPackageFromWeb(string pakName) diff --git a/PluginManager/Others/Actions/ActionManager.cs b/PluginManager/Others/Actions/ActionManager.cs new file mode 100644 index 0000000..b2bcae6 --- /dev/null +++ b/PluginManager/Others/Actions/ActionManager.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace PluginManager.Others.Actions +{ + public class ActionManager + { + public List Actions { get; private set; } + + private bool _isInitialized = false; + + public ActionManager() + { + if(_isInitialized) return; + + Actions = new List(); + + _isInitialized = true; + } + + public bool ActionExists(string name) + { + if(!_isInitialized) throw new Exception("ActionManager is not initialized"); + return Actions.Any(x => x.Name == name); + } + + public void AddAction(InternalAction action) + { + if(!_isInitialized) throw new Exception("ActionManager is not initialized"); + Actions.Add(action); + } + + public void ExecuteAction(string name, string[] args) + { + if(!_isInitialized) throw new Exception("ActionManager is not initialized"); + var action = Actions.FirstOrDefault(x => x.Name == name); + if(action == null) throw new Exception($"Action {name} not found"); + action.Invoke(args); + } + + public async Task ExecuteActionAsync(string name, string[] args) + { + if(!_isInitialized) throw new Exception("ActionManager is not initialized"); + var action = Actions.FirstOrDefault(x => x.Name == name); + if(action == null) throw new Exception($"Action {name} not found"); + await action.InvokeAsync(args); + } + } +} diff --git a/PluginManager/Others/Actions/InternalAction.cs b/PluginManager/Others/Actions/InternalAction.cs new file mode 100644 index 0000000..c43d684 --- /dev/null +++ b/PluginManager/Others/Actions/InternalAction.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PluginManager.Others.Actions +{ + public class InternalAction + { + public string? Name { get; init; } + public Action Action { get; init; } + + public InternalAction(string name, Action action) + { + Name = name; + Action = action; + } + + public InternalAction(string name, Action action) + { + Name = name; + Action = (o) => + { + action(); + return; + }; + } + + public void Invoke(string[] args) + { + Action(args); + } + + public async Task InvokeAsync(string[] args) + { + await Task.Run(() => Action(args)); + } + } +} diff --git a/PluginManager/Others/ArchiveManager.cs b/PluginManager/Others/ArchiveManager.cs index 4d97666..6f32cf3 100644 --- a/PluginManager/Others/ArchiveManager.cs +++ b/PluginManager/Others/ArchiveManager.cs @@ -58,7 +58,7 @@ namespace PluginManager.Others } catch (Exception ex) { - ex.WriteErrFile(); // Write the error to a file + Config.Logger.Log(ex.Message, "Archive Manager", TextType.ERROR); // Write the error to a file await Task.Delay(100); return await ReadFromPakAsync(FileName, archFile); } diff --git a/PluginManager/Others/CmdArgs.cs b/PluginManager/Others/DBCommandExecutingArguments.cs similarity index 77% rename from PluginManager/Others/CmdArgs.cs rename to PluginManager/Others/DBCommandExecutingArguments.cs index 14ad428..a2cee9d 100644 --- a/PluginManager/Others/CmdArgs.cs +++ b/PluginManager/Others/DBCommandExecutingArguments.cs @@ -8,14 +8,14 @@ using System.Threading.Tasks; namespace PluginManager.Others { - public class CmdArgs + public class DBCommandExecutingArguments { public SocketCommandContext context { get; init; } public string cleanContent { get; init; } public string commandUsed { get;init; } public string[] arguments { get;init; } - public CmdArgs(SocketCommandContext context, string cleanContent, string commandUsed, string[] arguments) + public DBCommandExecutingArguments(SocketCommandContext context, string cleanContent, string commandUsed, string[] arguments) { this.context = context; this.cleanContent = cleanContent; diff --git a/PluginManager/Others/Enums.cs b/PluginManager/Others/Enums.cs index 1e71fa6..6f5a85d 100644 --- a/PluginManager/Others/Enums.cs +++ b/PluginManager/Others/Enums.cs @@ -42,25 +42,12 @@ public enum UnzipProgressType PercentageFromTotalSize } -public enum TableFormat -{ - CENTER_EACH_COLUMN_BASED, - CENTER_OVERALL_LENGTH, - DEFAULT -} - public enum SaveType { NORMAL, BACKUP } -public enum ProgressBarType -{ - NORMAL, - NO_END -} - public enum TextType { NORMAL, diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj index bfa82b3..42446cf 100644 --- a/PluginManager/PluginManager.csproj +++ b/PluginManager/PluginManager.csproj @@ -15,7 +15,4 @@ - - - \ No newline at end of file