From 944d59d9a3ed8b761cd2b6ccc0cda7bd91948676 Mon Sep 17 00:00:00 2001 From: Andrei Tudor Date: Tue, 21 Nov 2023 22:04:38 +0200 Subject: [PATCH] Reformatting code --- DiscordBot/Bot/Actions/Clear.cs | 10 +- DiscordBot/Bot/Actions/Exit.cs | 12 +- DiscordBot/Bot/Actions/Extra/PluginMethods.cs | 302 +++++++++--------- .../Bot/Actions/Extra/SettingsConfigExtra.cs | 20 +- DiscordBot/Bot/Actions/Help.cs | 10 +- DiscordBot/Bot/Actions/Plugin.cs | 8 +- DiscordBot/Bot/Actions/SettingsConfig.cs | 28 +- .../Bot/Commands/NormalCommands/Help.cs | 4 +- DiscordBot/Bot/Commands/SlashCommands/Help.cs | 6 +- DiscordBot/DiscordBot.csproj | 8 +- DiscordBot/Entry.cs | 8 +- DiscordBot/Installer.cs | 10 +- DiscordBot/Program.cs | 36 ++- DiscordBot/Utilities/Console Utilities.cs | 102 +++--- PluginManager/Bot/Boot.cs | 4 +- PluginManager/Bot/CommandHandler.cs | 20 +- PluginManager/Config.cs | 15 +- PluginManager/Database/SqlDatabase.cs | 57 ++-- PluginManager/Interfaces/DBSlashCommand.cs | 2 +- PluginManager/Interfaces/Logger/ILog.cs | 7 +- PluginManager/Interfaces/Logger/ILogger.cs | 8 +- PluginManager/Loaders/Loader.cs | 49 +-- PluginManager/Loaders/PluginLoader.cs | 7 +- .../Online/Helpers/OnlineFunctions.cs | 10 +- PluginManager/Online/PluginsManager.cs | 28 +- PluginManager/Online/ServerCom.cs | 8 +- .../Others/Actions/InternalActionsManager.cs | 4 +- PluginManager/Others/ArchiveManager.cs | 16 +- .../Others/DBCommandExecutingArguments.cs | 14 +- PluginManager/Others/Enums.cs | 4 +- PluginManager/Others/Functions.cs | 6 +- PluginManager/Others/JsonManager.cs | 4 +- PluginManager/Others/Logger/Log.cs | 76 ++--- PluginManager/Others/Logger/Logger.cs | 60 ++-- PluginManager/Others/SettingsDictionary.cs | 20 +- PluginManager/PluginManager.csproj | 6 +- SethTests/SethTests.csproj | 6 +- 37 files changed, 509 insertions(+), 486 deletions(-) diff --git a/DiscordBot/Bot/Actions/Clear.cs b/DiscordBot/Bot/Actions/Clear.cs index a4bf0e3..1ae69ca 100644 --- a/DiscordBot/Bot/Actions/Clear.cs +++ b/DiscordBot/Bot/Actions/Clear.cs @@ -5,12 +5,12 @@ using PluginManager.Others; namespace DiscordBot.Bot.Actions; -public class Clear : ICommandAction +public class Clear: ICommandAction { - public string ActionName => "clear"; - public string Description => "Clears the console"; - public string Usage => "clear"; - public InternalActionRunType RunType => InternalActionRunType.ON_CALL; + public string ActionName => "clear"; + public string Description => "Clears the console"; + public string Usage => "clear"; + public InternalActionRunType RunType => InternalActionRunType.ON_CALL; public Task Execute(string[] args) { diff --git a/DiscordBot/Bot/Actions/Exit.cs b/DiscordBot/Bot/Actions/Exit.cs index 1caa641..fa21edf 100644 --- a/DiscordBot/Bot/Actions/Exit.cs +++ b/DiscordBot/Bot/Actions/Exit.cs @@ -6,12 +6,12 @@ using PluginManager.Others; namespace DiscordBot.Bot.Actions; -public class Exit : ICommandAction +public class Exit: ICommandAction { - public string ActionName => "exit"; - public string Description => "Exits the bot and saves the config. Use exit help for more info."; - public string Usage => "exit [help|force (-f)]"; - public InternalActionRunType RunType => InternalActionRunType.ON_CALL; + public string ActionName => "exit"; + public string Description => "Exits the bot and saves the config. Use exit help for more info."; + public string Usage => "exit [help|force (-f)]"; + public InternalActionRunType RunType => InternalActionRunType.ON_CALL; public async Task Execute(string[] args) { @@ -23,7 +23,7 @@ public class Exit : ICommandAction } else { - switch ( args[0] ) + switch (args[0]) { case "help": Console.WriteLine("Usage : exit [help|force]"); diff --git a/DiscordBot/Bot/Actions/Extra/PluginMethods.cs b/DiscordBot/Bot/Actions/Extra/PluginMethods.cs index 58f6868..89da9fe 100644 --- a/DiscordBot/Bot/Actions/Extra/PluginMethods.cs +++ b/DiscordBot/Bot/Actions/Extra/PluginMethods.cs @@ -19,20 +19,20 @@ internal static class PluginMethods internal static async Task List(PluginsManager manager) { var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetAvailablePlugins(), "Loading plugins..."); - + TableData tableData = new(new List { "Name", "Description", "Type", "Version" }); foreach (var plugin in data) tableData.AddRow(plugin); - + tableData.HasRoundBorders = false; tableData.PrintAsTable(); } - + internal static async Task RefreshPlugins(bool quiet) { await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty); await Program.internalActionManager.Refresh(); } - + internal static async Task DownloadPlugin(PluginsManager manager, string pluginName) { var pluginData = await manager.GetPluginLinkByName(pluginName); @@ -42,30 +42,32 @@ internal static class PluginMethods return; } - var pluginType = pluginData[0]; - var pluginLink = pluginData[1]; + var pluginType = pluginData[0]; + var pluginLink = pluginData[1]; var pluginRequirements = pluginData[2]; - - + + await AnsiConsole.Progress() - .Columns(new ProgressColumn[] - { - new TaskDescriptionColumn(), - new ProgressBarColumn(), - new PercentageColumn() - }) - .StartAsync(async ctx => - { - var downloadTask = ctx.AddTask("Downloading plugin..."); + .Columns(new ProgressColumn[] + { + new TaskDescriptionColumn(), + new ProgressBarColumn(), + new PercentageColumn() + } + ) + .StartAsync(async ctx => + { + var downloadTask = ctx.AddTask("Downloading plugin..."); - IProgress progress = new Progress(p => { downloadTask.Value = p; }); + IProgress progress = new Progress(p => { downloadTask.Value = p; }); - await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress); - - downloadTask.Increment(100); - - ctx.Refresh(); - }); + await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress); + + downloadTask.Increment(100); + + ctx.Refresh(); + } + ); if (pluginRequirements == string.Empty) { @@ -75,150 +77,162 @@ internal static class PluginMethods } List requirementsUrLs = new(); - + await AnsiConsole.Progress() - .Columns(new ProgressColumn[] - { - new TaskDescriptionColumn(), - new ProgressBarColumn(), - new PercentageColumn() - }) - .StartAsync(async ctx => - { - var gatherInformationTask = ctx.AddTask("Gathering info..."); - gatherInformationTask.IsIndeterminate = true; - requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements); - - gatherInformationTask.Increment(100); - }); + .Columns(new ProgressColumn[] + { + new TaskDescriptionColumn(), + new ProgressBarColumn(), + new PercentageColumn() + } + ) + .StartAsync(async ctx => + { + var gatherInformationTask = ctx.AddTask("Gathering info..."); + gatherInformationTask.IsIndeterminate = true; + requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements); + + gatherInformationTask.Increment(100); + } + ); List, string, string>> downloadTasks = new(); await AnsiConsole.Progress() - .Columns(new ProgressColumn[] - { - new TaskDescriptionColumn(), - new ProgressBarColumn(), - new PercentageColumn() - }) - .StartAsync(async ctx => - { - + .Columns(new ProgressColumn[] + { + new TaskDescriptionColumn(), + new ProgressBarColumn(), + new PercentageColumn() + } + ) + .StartAsync(async ctx => + { - foreach (var info in requirementsUrLs) - { - if (info.Length < 2) continue; - string[] data = info.Split(','); - string url = data[0]; - string fileName = data[1]; - - var task = ctx.AddTask($"Downloading {fileName}: "); - IProgress progress = new Progress(p => - { - task.Value = p; - }); - task.IsIndeterminate = true; - downloadTasks.Add(new Tuple, string, string>(task, progress, url, fileName)); - } + foreach (var info in requirementsUrLs) + { + if (info.Length < 2) continue; + string[] data = info.Split(','); + string url = data[0]; + string fileName = data[1]; - if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads)) - { - maxParallelDownloads = 5; - Config.AppSettings.Add("MaxParallelDownloads", "5"); - await Config.AppSettings.SaveToFile(); - } - - var options = new ParallelOptions() - { - MaxDegreeOfParallelism = maxParallelDownloads, - TaskScheduler = TaskScheduler.Default - }; + var task = ctx.AddTask($"Downloading {fileName}: "); + IProgress progress = new Progress(p => + { + task.Value = p; + } + ); - await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) => - { - tuple.Item1.IsIndeterminate = false; - await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2); - }); + task.IsIndeterminate = true; + downloadTasks.Add(new Tuple, string, string>(task, progress, url, fileName)); + } + + if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads)) + { + maxParallelDownloads = 5; + Config.AppSettings.Add("MaxParallelDownloads", "5"); + await Config.AppSettings.SaveToFile(); + } + + var options = new ParallelOptions() + { + MaxDegreeOfParallelism = maxParallelDownloads, + TaskScheduler = TaskScheduler.Default + }; + + await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) => + { + tuple.Item1.IsIndeterminate = false; + await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2); + } + ); + + + + } + ); - }); - - - await RefreshPlugins(false); } internal static async Task LoadPlugins(string[] args) { - var loader = new PluginLoader(Config.DiscordBot.client); - if (args.Length == 2 && args[1] == "-q") - { - loader.LoadPlugins(); - return true; - } + var loader = new PluginLoader(Config.DiscordBot.client); + if (args.Length == 2 && args[1] == "-q") + { + loader.LoadPlugins(); + return true; + } - var cc = Console.ForegroundColor; - loader.onCMDLoad += (name, typeName, success, exception) => - { - if (name == null || name.Length < 2) - name = typeName; - if (success) - { - Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction), - type: LogType.INFO); - } + var cc = Console.ForegroundColor; + loader.onCMDLoad += (name, typeName, success, exception) => + { + if (name == null || name.Length < 2) + name = typeName; + if (success) + { + Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction), + type: LogType.INFO + ); + } - else - { - Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message, - source: typeof(ICommandAction), type: LogType.ERROR); - } + else + { + Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message, + source: typeof(ICommandAction), type: LogType.ERROR + ); + } - Console.ForegroundColor = cc; - }; - loader.onEVELoad += (name, typeName, success, exception) => - { - if (name == null || name.Length < 2) - name = typeName; + Console.ForegroundColor = cc; + }; + loader.onEVELoad += (name, typeName, success, exception) => + { + if (name == null || name.Length < 2) + name = typeName; - if (success) - { - Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction), - type: LogType.INFO); - } - else - { - Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message, - source: typeof(ICommandAction), type: LogType.ERROR); - } + if (success) + { + Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction), + type: LogType.INFO + ); + } + else + { + Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message, + source: typeof(ICommandAction), type: LogType.ERROR + ); + } - Console.ForegroundColor = cc; - }; + Console.ForegroundColor = cc; + }; - loader.onSLSHLoad += (name, typeName, success, exception) => - { - if (name == null || name.Length < 2) - name = typeName; + loader.onSLSHLoad += (name, typeName, success, exception) => + { + if (name == null || name.Length < 2) + name = typeName; - if (success) - { - Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction), - type: LogType.INFO); - } - else - { - Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message, - source: typeof(ICommandAction), type: LogType.ERROR); - } + if (success) + { + Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction), + type: LogType.INFO + ); + } + else + { + Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message, + source: typeof(ICommandAction), type: LogType.ERROR + ); + } - Console.ForegroundColor = cc; - }; + Console.ForegroundColor = cc; + }; - loader.LoadPlugins(); - Console.ForegroundColor = cc; - return true; + loader.LoadPlugins(); + Console.ForegroundColor = cc; + return true; } - - + + } diff --git a/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs b/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs index b038e39..eac1966 100644 --- a/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs +++ b/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs @@ -5,26 +5,26 @@ namespace DiscordBot.Bot.Actions.Extra; internal static class SettingsConfigExtra { - internal static void SetSettings(string key, params string[] value) + internal static void SetSettings(string key, params string[] value) { if (key is null) return; if (value is null) return; - + if (!Config.AppSettings.ContainsKey(key)) return; - + Config.AppSettings[key] = string.Join(' ', value); - // Config.AppSettings.SaveToFile().Wait(); + // Config.AppSettings.SaveToFile().Wait(); } internal static void RemoveSettings(string key) { if (key is null) return; - - if(!Config.AppSettings.ContainsKey(key)) + + if (!Config.AppSettings.ContainsKey(key)) return; - + Config.AppSettings.Remove(key); } @@ -33,11 +33,11 @@ internal static class SettingsConfigExtra if (key is null) return; if (value is null) return; - + if (Config.AppSettings.ContainsKey(key)) return; - + Config.AppSettings.Add(key, string.Join(' ', value)); // Config.AppSettings.SaveToFile().Wait(); } -} \ No newline at end of file +} diff --git a/DiscordBot/Bot/Actions/Help.cs b/DiscordBot/Bot/Actions/Help.cs index f6e2ea5..ac8de2a 100644 --- a/DiscordBot/Bot/Actions/Help.cs +++ b/DiscordBot/Bot/Actions/Help.cs @@ -7,7 +7,7 @@ using PluginManager.Others; namespace DiscordBot.Bot.Actions; -public class Help : ICommandAction +public class Help: ICommandAction { public string ActionName => "help"; @@ -34,8 +34,8 @@ public class Help : ICommandAction items.Add(new[] { "-", "-", "-" }); ConsoleUtilities.FormatAndAlignTable(items, - TableFormat.CENTER_EACH_COLUMN_BASED - ); + TableFormat.CENTER_EACH_COLUMN_BASED + ); return; } @@ -56,7 +56,7 @@ public class Help : ICommandAction }; ConsoleUtilities.FormatAndAlignTable(actionData, - TableFormat.CENTER_EACH_COLUMN_BASED - ); + TableFormat.CENTER_EACH_COLUMN_BASED + ); } } diff --git a/DiscordBot/Bot/Actions/Plugin.cs b/DiscordBot/Bot/Actions/Plugin.cs index 1632b53..211158c 100644 --- a/DiscordBot/Bot/Actions/Plugin.cs +++ b/DiscordBot/Bot/Actions/Plugin.cs @@ -12,7 +12,7 @@ using Spectre.Console; namespace DiscordBot.Bot.Actions; -public class Plugin : ICommandAction +public class Plugin: ICommandAction { private bool pluginsLoaded; public string ActionName => "plugin"; @@ -46,7 +46,7 @@ public class Plugin : ICommandAction case "refresh": await PluginMethods.RefreshPlugins(true); break; - + case "list": await PluginMethods.List(manager); break; @@ -56,7 +56,7 @@ public class Plugin : ICommandAction Config.Logger.Log("Plugins already loaded", source: typeof(ICommandAction), type: LogType.WARNING); break; } - + if (Config.DiscordBot is null) { Config.Logger.Log("DiscordBot is null", source: typeof(ICommandAction), type: LogType.WARNING); @@ -84,4 +84,4 @@ public class Plugin : ICommandAction break; } } -} \ No newline at end of file +} diff --git a/DiscordBot/Bot/Actions/SettingsConfig.cs b/DiscordBot/Bot/Actions/SettingsConfig.cs index 332ed75..ef67bc8 100644 --- a/DiscordBot/Bot/Actions/SettingsConfig.cs +++ b/DiscordBot/Bot/Actions/SettingsConfig.cs @@ -7,7 +7,7 @@ using PluginManager.Others; namespace DiscordBot.Bot.Actions; -public class SettingsConfig : ICommandAction +public class SettingsConfig: ICommandAction { public string ActionName => "config"; public string Description => "Change the settings of the bot"; @@ -19,7 +19,7 @@ public class SettingsConfig : ICommandAction { foreach (var settings in Config.AppSettings) Console.WriteLine(settings.Key + ": " + settings.Value); - + return Task.CompletedTask; } @@ -27,25 +27,25 @@ public class SettingsConfig : ICommandAction { case "-s": case "set": - if(args.Length < 3) + if (args.Length < 3) return Task.CompletedTask; - SettingsConfigExtra.SetSettings(args[1],args[2..]); + SettingsConfigExtra.SetSettings(args[1], args[2..]); break; - + case "-r": case "remove": - if(args.Length < 2) + if (args.Length < 2) return Task.CompletedTask; SettingsConfigExtra.RemoveSettings(args[1]); break; - + case "-a": case "add": - if(args.Length < 3) + if (args.Length < 3) return Task.CompletedTask; SettingsConfigExtra.AddSettings(args[1], args[2..]); break; - + case "-h": case "-help": Console.WriteLine("Options:"); @@ -54,14 +54,14 @@ public class SettingsConfig : ICommandAction Console.WriteLine("-a : Add a setting"); Console.WriteLine("-h: Show this help message"); break; - + default: Console.WriteLine("Invalid option"); return Task.CompletedTask; } - - - + + + return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/DiscordBot/Bot/Commands/NormalCommands/Help.cs b/DiscordBot/Bot/Commands/NormalCommands/Help.cs index 0fa3256..8387dc5 100644 --- a/DiscordBot/Bot/Commands/NormalCommands/Help.cs +++ b/DiscordBot/Bot/Commands/NormalCommands/Help.cs @@ -10,7 +10,7 @@ namespace DiscordBot.Bot.Commands; /// /// The help command /// -internal class Help : DBCommand +internal class Help: DBCommand { /// /// Command name @@ -76,7 +76,7 @@ internal class Help : DBCommand var embedBuilder = new EmbedBuilder(); var cmd = PluginLoader.Commands.Find(p => p.Command == command || p.Aliases is not null && p.Aliases.Contains(command) - ); + ); if (cmd == null) return null; embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); diff --git a/DiscordBot/Bot/Commands/SlashCommands/Help.cs b/DiscordBot/Bot/Commands/SlashCommands/Help.cs index b733818..030d540 100644 --- a/DiscordBot/Bot/Commands/SlashCommands/Help.cs +++ b/DiscordBot/Bot/Commands/SlashCommands/Help.cs @@ -8,11 +8,11 @@ using PluginManager.Others; namespace DiscordBot.Bot.Commands.SlashCommands; -public class Help : DBSlashCommand +public class Help: DBSlashCommand { - public string Name => "help"; + public string Name => "help"; public string Description => "This command allows you to check all loaded commands"; - public bool canUseDM => true; + public bool canUseDM => true; public List Options => new() diff --git a/DiscordBot/DiscordBot.csproj b/DiscordBot/DiscordBot.csproj index fa3c2ed..3ae8395 100644 --- a/DiscordBot/DiscordBot.csproj +++ b/DiscordBot/DiscordBot.csproj @@ -29,13 +29,13 @@ - - + + - - + + diff --git a/DiscordBot/Entry.cs b/DiscordBot/Entry.cs index e3056be..eb61106 100644 --- a/DiscordBot/Entry.cs +++ b/DiscordBot/Entry.cs @@ -16,16 +16,16 @@ public static class Entry File.Delete(plugin); } } - + #endif - - + + var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += LoadFromSameFolder; static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) { - var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries"); + var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries"); var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll"); if (!File.Exists(assemblyPath)) return null; var assembly = Assembly.LoadFrom(assemblyPath); diff --git a/DiscordBot/Installer.cs b/DiscordBot/Installer.cs index 1e27dc9..e310590 100644 --- a/DiscordBot/Installer.cs +++ b/DiscordBot/Installer.cs @@ -9,9 +9,9 @@ public static class Installer { AnsiConsole.MarkupLine("Welcome to the [bold]SethBot[/] installer !"); AnsiConsole.MarkupLine("First, we need to configure the bot. Don't worry, it will be quick !"); - - var token = AnsiConsole.Ask("Please enter the bot [yellow]token[/]:"); - var prefix = AnsiConsole.Ask("Please enter the bot [yellow]prefix[/]:"); + + var token = AnsiConsole.Ask("Please enter the bot [yellow]token[/]:"); + var prefix = AnsiConsole.Ask("Please enter the bot [yellow]prefix[/]:"); var serverId = AnsiConsole.Ask("Please enter the [yellow]Server ID[/]:"); if (string.IsNullOrWhiteSpace(serverId)) serverId = "NULL"; @@ -20,9 +20,9 @@ public static class Installer Config.AppSettings.Add("ServerID", serverId); Config.AppSettings.SaveToFile(); - + AnsiConsole.MarkupLine("[bold]Config saved ![/]"); - + Config.Logger.Log("Config Saved", source: typeof(Installer)); } } diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index 818b4b7..42f3437 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -22,9 +22,9 @@ public class Program public static void Startup(string[] args) { PreLoadComponents(args).Wait(); - + if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix")) - Installer.GenerateStartupConfig(); + Installer.GenerateStartupConfig(); HandleInput().Wait(); } @@ -37,8 +37,8 @@ public class Program internalActionManager.Initialize().Wait(); internalActionManager.Execute("plugin", "load").Wait(); internalActionManager.Refresh().Wait(); - - + + while (true) { var cmd = Console.ReadLine(); @@ -64,21 +64,21 @@ public class Program Console.WriteLine($"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); 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($"Running on &m{Functions.GetOperatingSystem()}"); Console.WriteLine("============================ LOG ============================"); - + Console.ForegroundColor = ConsoleColor.White; try { - var token = AppSettings["token"]; + var token = AppSettings["token"]; var prefix = AppSettings["prefix"]; var discordbooter = new Boot(token, prefix); await discordbooter.Awake(); } - catch ( Exception ex ) + catch (Exception ex) { Logger.Log(ex.ToString(), source: typeof(Program), type: LogType.CRITICAL); } @@ -96,18 +96,20 @@ public class Program internalActionManager = new InternalActionManager("./Data/Plugins", "*.dll"); NoGUI(); } - catch ( IOException ex ) + catch (IOException ex) { if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) { if (AppSettings.ContainsKey("LaunchMessage")) AppSettings.Add("LaunchMessage", - "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 !"); - + "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 &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 !", - source: typeof(Program), type: LogType.ERROR); + "There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", + source: typeof(Program), type: LogType.ERROR + ); } } } @@ -115,7 +117,7 @@ public class Program private static async Task PreLoadComponents(string[] args) { await Initialize(); - + Logger.OnLog += (sender, logMessage) => { string messageColor = logMessage.Type switch @@ -133,10 +135,10 @@ public class Program Console.WriteLine(logMessage.Message); return; } - + AnsiConsole.MarkupLine($"{messageColor}{logMessage.ThrowTime} {logMessage.Message} [/]"); }; - + AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } diff --git a/DiscordBot/Utilities/Console Utilities.cs b/DiscordBot/Utilities/Console Utilities.cs index 5fdbe60..cd68bd0 100644 --- a/DiscordBot/Utilities/Console Utilities.cs +++ b/DiscordBot/Utilities/Console Utilities.cs @@ -9,24 +9,24 @@ namespace DiscordBot.Utilities; public class TableData { - public List Columns; + public List Columns; public List Rows; - + public bool IsEmpty => Rows.Count == 0; public bool HasRoundBorders { get; set; } = true; - + public TableData(List columns) { Columns = columns; Rows = new List(); } - + public TableData(string[] columns) { Columns = columns.ToList(); Rows = new List(); } - + public void AddRow(string[] row) { Rows.Add(row); @@ -41,23 +41,23 @@ public static class ConsoleUtilities T result = default; await AnsiConsole.Progress() .Columns( - new ProgressColumn[] - { - new TaskDescriptionColumn(), - new ProgressBarColumn(), - new PercentageColumn(), - } - ) + new ProgressColumn[] + { + new TaskDescriptionColumn(), + new ProgressBarColumn(), + new PercentageColumn(), + } + ) .StartAsync( - async ctx => - { - var task = ctx.AddTask(message); - task.IsIndeterminate = true; - result = await function; - task.Increment(100); + async ctx => + { + var task = ctx.AddTask(message); + task.IsIndeterminate = true; + result = await function; + task.Increment(100); - } - ); + } + ); return result; } @@ -66,21 +66,23 @@ public static class ConsoleUtilities { await AnsiConsole.Progress() .Columns(new ProgressColumn[] - { - new TaskDescriptionColumn(), - new ProgressBarColumn(), - new PercentageColumn(), - }) + { + new TaskDescriptionColumn(), + new ProgressBarColumn(), + new PercentageColumn(), + } + ) .StartAsync(async ctx => - { - var task = ctx.AddTask(message); - task.IsIndeterminate = true; - await function; - task.Increment(100); - - }); + { + var task = ctx.AddTask(message); + task.IsIndeterminate = true; + await function; + task.Increment(100); + + } + ); } - + private static readonly Dictionary Colors = new() { { 'g', ConsoleColor.Green }, @@ -91,7 +93,7 @@ public static class ConsoleUtilities }; private static readonly char ColorPrefix = '&'; - + private static bool CanAproximateTo(this float f, float y) { return MathF.Abs(f - y) < 0.000001; @@ -104,7 +106,7 @@ public static class ConsoleUtilities table.AddColumns(tableData.Columns.ToArray()); foreach (var row in tableData.Rows) table.AddRow(row); - + AnsiConsole.Write(table); } @@ -123,12 +125,12 @@ public static class ConsoleUtilities data.RemoveAt(0); foreach (var row in data) table.AddRow(row); - + AnsiConsole.Write(table); - + return; } - + if (format == TableFormat.CENTER_EACH_COLUMN_BASED) { var tableLine = '-'; @@ -317,18 +319,18 @@ public static class ConsoleUtilities Console.CursorVisible = false; isRunning = true; thread = new Thread(() => - { - while (isRunning) - { - Console.SetCursorPosition(0, Console.CursorTop); - Console.Write(" " + Sequence[position] + " " + Message + " "); - position++; - if (position >= Sequence.Length) - position = 0; - Thread.Sleep(100); - } - } - ); + { + while (isRunning) + { + Console.SetCursorPosition(0, Console.CursorTop); + Console.Write(" " + Sequence[position] + " " + Message + " "); + position++; + if (position >= Sequence.Length) + position = 0; + Thread.Sleep(100); + } + } + ); thread.Start(); } diff --git a/PluginManager/Bot/Boot.cs b/PluginManager/Bot/Boot.cs index 713693a..5ac16a3 100644 --- a/PluginManager/Bot/Boot.cs +++ b/PluginManager/Bot/Boot.cs @@ -78,7 +78,7 @@ public class Boot CommonTasks(); await client.LoginAsync(TokenType.Bot, botToken); - + await client.StartAsync(); commandServiceHandler = new CommandHandler(client, service, botPrefix); @@ -105,7 +105,7 @@ public class Boot if (arg.Message.Contains("401")) { Config.AppSettings.Remove("token"); - Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source:typeof(Boot), type: LogType.CRITICAL); + Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source: typeof(Boot), type: LogType.CRITICAL); await Config.AppSettings.SaveToFile(); await Task.Delay(4000); Environment.Exit(0); diff --git a/PluginManager/Bot/CommandHandler.cs b/PluginManager/Bot/CommandHandler.cs index 1a4e9fa..1a8b098 100644 --- a/PluginManager/Bot/CommandHandler.cs +++ b/PluginManager/Bot/CommandHandler.cs @@ -106,9 +106,11 @@ internal class CommandHandler ( plug.Aliases is not null && plug.Aliases.Contains(message.CleanContent - .Substring(mentionPrefix.Length + 1) - .Split(' ')[0]) - )); + .Substring(mentionPrefix.Length + 1) + .Split(' ')[0] + ) + ) + ); cleanMessage = message.Content.Substring(mentionPrefix.Length + 1); } @@ -120,11 +122,13 @@ internal class CommandHandler message.Content.Split(' ')[0].Substring(botPrefix.Length) || (p.Aliases is not null && p.Aliases.Contains( - message.Content.Split(' ')[0] - .Substring(botPrefix.Length)))); + message.Content.Split(' ')[0] + .Substring(botPrefix.Length) + )) + ); cleanMessage = message.Content.Substring(botPrefix.Length); } - + if (plugin is null) return; @@ -138,13 +142,13 @@ internal class CommandHandler argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' '); DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean); - + Config.Logger.Log( message: $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"", source: typeof(CommandHandler), type: LogType.INFO ); - + if (context.Channel is SocketDMChannel) plugin.ExecuteDM(cmd); else plugin.ExecuteServer(cmd); diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index b0dde70..2b32f52 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -20,18 +20,19 @@ public class Config public static async Task Initialize() { if (_isLoaded) return; - + Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Plugins"); - Directory.CreateDirectory("./Data/PAKS"); - Directory.CreateDirectory("./Data/Logs/Logs"); - Directory.CreateDirectory("./Data/Logs/Errors"); + Directory.CreateDirectory("./Data/Archives"); + Directory.CreateDirectory("./Data/Logs"); AppSettings = new SettingsDictionary("./Data/Resources/config.json"); - AppSettings["LogFolder"] = "./Data/Logs/Logs"; + AppSettings["LogFolder"] = "./Data/Logs"; - Logger = new Logger(false, true); + Logger = new Logger(false, true, + AppSettings["LogFolder"] + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log" + ); ArchiveManager.Initialize(); @@ -39,5 +40,5 @@ public class Config Logger.Log(message: "Config initialized", source: typeof(Config)); } - + } diff --git a/PluginManager/Database/SqlDatabase.cs b/PluginManager/Database/SqlDatabase.cs index 6b65a84..3c9fdd0 100644 --- a/PluginManager/Database/SqlDatabase.cs +++ b/PluginManager/Database/SqlDatabase.cs @@ -163,7 +163,8 @@ public class SqlDatabase throw new Exception($"Table {tableName} does not exist"); await ExecuteAsync( - $"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'"); + $"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'" + ); } /// @@ -238,7 +239,7 @@ public class SqlDatabase { var command = _connection.CreateCommand(); command.CommandText = $"SELECT * FROM {tableName}"; - var reader = await command.ExecuteReaderAsync(); + var reader = await command.ExecuteReaderAsync(); var tableColumns = new List(); for (var i = 0; i < reader.FieldCount; i++) tableColumns.Add(reader.GetName(i)); @@ -262,7 +263,7 @@ public class SqlDatabase { var command = _connection.CreateCommand(); command.CommandText = $"SELECT * FROM {tableName}"; - var reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); var tableColumns = new List(); for (var i = 0; i < reader.FieldCount; i++) tableColumns.Add(reader.GetName(i)); @@ -343,7 +344,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); var command = new SQLiteCommand(query, _connection); - var answer = await command.ExecuteNonQueryAsync(); + var answer = await command.ExecuteNonQueryAsync(); return answer; } @@ -357,7 +358,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) _connection.Open(); var command = new SQLiteCommand(query, _connection); - var r = command.ExecuteNonQuery(); + var r = command.ExecuteNonQuery(); return r; } @@ -372,7 +373,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); var command = new SQLiteCommand(query, _connection); - var reader = await command.ExecuteReaderAsync(); + var reader = await command.ExecuteReaderAsync(); var values = new object[reader.FieldCount]; if (reader.Read()) @@ -394,7 +395,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) _connection.Open(); var command = new SQLiteCommand(query, _connection); - var reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); var values = new object[reader.FieldCount]; if (reader.Read()) @@ -416,7 +417,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); var command = new SQLiteCommand(query, _connection); - var reader = await command.ExecuteReaderAsync(); + var reader = await command.ExecuteReaderAsync(); var values = new object[reader.FieldCount]; if (reader.Read()) @@ -439,7 +440,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) _connection.Open(); var command = new SQLiteCommand(query, _connection); - var reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); var values = new object[reader.FieldCount]; if (reader.Read()) @@ -462,7 +463,7 @@ public class SqlDatabase if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); var command = new SQLiteCommand(query, _connection); - var reader = await command.ExecuteReaderAsync(); + var reader = await command.ExecuteReaderAsync(); if (!reader.HasRows) return null; @@ -479,7 +480,7 @@ public class SqlDatabase return rows; } - + /// /// Create a parameter for a query /// @@ -490,7 +491,7 @@ public class SqlDatabase { var parameter = new SQLiteParameter(name); parameter.Value = value; - + if (value is string) parameter.DbType = DbType.String; else if (value is int) @@ -531,13 +532,13 @@ public class SqlDatabase parameter.DbType = DbType.StringFixedLength; else if (value is char[]) parameter.DbType = DbType.StringFixedLength; - else + else return null; return parameter; } - - + + /// /// Create a parameter for a query. The function automatically detects the type of the value. /// @@ -545,7 +546,7 @@ public class SqlDatabase /// The SQLiteParameter that has the name, value and DBType set according to your inputs private SQLiteParameter? CreateParameter(KeyValuePair parameterValues) => CreateParameter(parameterValues.Key, parameterValues.Value); - + /// /// Execute a query with parameters /// @@ -556,7 +557,7 @@ public class SqlDatabase { if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); - + var command = new SQLiteCommand(query, _connection); foreach (var parameter in parameters) { @@ -564,10 +565,10 @@ public class SqlDatabase if (p is not null) command.Parameters.Add(p); } - + return await command.ExecuteNonQueryAsync(); } - + /// /// Execute a query with parameters that returns a specific type of object. The function will return the first row of the result transformed into the specified type. /// @@ -576,11 +577,11 @@ public class SqlDatabase /// The parameters of the query /// The return object type /// An object of type T that represents the output of the convertor function based on the array of objects that the first row of the result has - public async Task ReadObjectOfTypeAsync (string query, Func convertor, params KeyValuePair[] parameters) + public async Task ReadObjectOfTypeAsync(string query, Func convertor, params KeyValuePair[] parameters) { if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); - + var command = new SQLiteCommand(query, _connection); foreach (var parameter in parameters) { @@ -588,7 +589,7 @@ public class SqlDatabase if (p is not null) command.Parameters.Add(p); } - + var reader = await command.ExecuteReaderAsync(); var values = new object[reader.FieldCount]; if (reader.Read()) @@ -599,8 +600,8 @@ public class SqlDatabase return default; } - - + + /// /// Execute a query with parameters that returns a specific type of object. The function will return a list of objects of the specified type. /// @@ -614,7 +615,7 @@ public class SqlDatabase { if (!_connection.State.HasFlag(ConnectionState.Open)) await _connection.OpenAsync(); - + var command = new SQLiteCommand(query, _connection); foreach (var parameter in parameters) { @@ -622,12 +623,12 @@ public class SqlDatabase if (p is not null) command.Parameters.Add(p); } - + var reader = await command.ExecuteReaderAsync(); // if (!reader.HasRows) return null; - + List rows = new(); while (await reader.ReadAsync()) { @@ -638,4 +639,4 @@ public class SqlDatabase return rows; } -} \ No newline at end of file +} diff --git a/PluginManager/Interfaces/DBSlashCommand.cs b/PluginManager/Interfaces/DBSlashCommand.cs index eb2df8a..7cb1782 100644 --- a/PluginManager/Interfaces/DBSlashCommand.cs +++ b/PluginManager/Interfaces/DBSlashCommand.cs @@ -6,7 +6,7 @@ namespace PluginManager.Interfaces; public interface DBSlashCommand { - string Name { get; } + string Name { get; } string Description { get; } bool canUseDM { get; } diff --git a/PluginManager/Interfaces/Logger/ILog.cs b/PluginManager/Interfaces/Logger/ILog.cs index fd5a300..19c4b8a 100644 --- a/PluginManager/Interfaces/Logger/ILog.cs +++ b/PluginManager/Interfaces/Logger/ILog.cs @@ -5,11 +5,10 @@ namespace PluginManager.Interfaces.Logger; internal interface ILog { - string Message { get; set; } - string OutputFile { get; set; } - + string Message { get; set; } + Type? Source { get; set; } - LogType Type { get; set; } + LogType Type { get; set; } DateTime ThrowTime { get; set; } } diff --git a/PluginManager/Interfaces/Logger/ILogger.cs b/PluginManager/Interfaces/Logger/ILogger.cs index c513cc6..d45e527 100644 --- a/PluginManager/Interfaces/Logger/ILogger.cs +++ b/PluginManager/Interfaces/Logger/ILogger.cs @@ -7,11 +7,13 @@ namespace PluginManager.Interfaces.Logger; internal interface ILogger { - bool IsEnabled { get; init; } - bool OutputToFile { get; init; } + bool IsEnabled { get; init; } + bool OutputToFile { get; init; } + + string OutputFile { get; init; } event EventHandler OnLog; void Log( - string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO, + string message = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default); } diff --git a/PluginManager/Loaders/Loader.cs b/PluginManager/Loaders/Loader.cs index fe3a716..946e5de 100644 --- a/PluginManager/Loaders/Loader.cs +++ b/PluginManager/Loaders/Loader.cs @@ -8,13 +8,13 @@ using PluginManager.Others; namespace PluginManager.Loaders; -internal class LoaderArgs : EventArgs +internal class LoaderArgs: EventArgs { - internal string? PluginName { get; init; } - internal string? TypeName { get; init; } - internal bool IsLoaded { get; init; } - internal Exception? Exception { get; init; } - internal object? Plugin { get; init; } + internal string? PluginName { get; init; } + internal string? TypeName { get; init; } + internal bool IsLoaded { get; init; } + internal Exception? Exception { get; init; } + internal object? Plugin { get; init; } } internal class Loader @@ -26,7 +26,7 @@ internal class Loader } - private string Path { get; } + private string Path { get; } private string Extension { get; } internal event FileLoadedEventHandler? FileLoaded; @@ -101,28 +101,29 @@ internal class Loader if (PluginLoaded != null) PluginLoaded.Invoke(new LoaderArgs - { - Exception = null, - IsLoaded = true, - PluginName = type.FullName, - TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" : - typeof(T) == typeof(DBEvent) ? "DBEvent" : - typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" : - null, - Plugin = plugin - } - ); + { + Exception = null, + IsLoaded = true, + PluginName = type.FullName, + TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" : + typeof(T) == typeof(DBEvent) ? "DBEvent" : + typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" : + null, + Plugin = plugin + } + ); } catch (Exception ex) { if (PluginLoaded != null) PluginLoaded.Invoke(new LoaderArgs - { - Exception = ex, - IsLoaded = false, - PluginName = type.FullName, - TypeName = nameof(T) - }); + { + Exception = ex, + IsLoaded = false, + PluginName = type.FullName, + TypeName = nameof(T) + } + ); } return list; diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index 409edb4..58e73ff 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -131,7 +131,8 @@ public class PluginLoader builder.Options = slash.Options; onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded, - args.Exception); + args.Exception + ); await _client.CreateGlobalApplicationCommandAsync(builder.Build()); } @@ -161,7 +162,7 @@ public class PluginLoader else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type)) { var instance = (DBSlashCommand)Activator.CreateInstance(type); - var builder = new SlashCommandBuilder(); + var builder = new SlashCommandBuilder(); builder.WithName(instance.Name); builder.WithDescription(instance.Description); builder.WithDMPermission(instance.canUseDM); @@ -177,6 +178,6 @@ public class PluginLoader //Console.WriteLine(ex.Message); Config.Logger.Log(ex.Message, source: typeof(PluginLoader), type: LogType.ERROR); } - + } } diff --git a/PluginManager/Online/Helpers/OnlineFunctions.cs b/PluginManager/Online/Helpers/OnlineFunctions.cs index 03faa29..0762d14 100644 --- a/PluginManager/Online/Helpers/OnlineFunctions.cs +++ b/PluginManager/Online/Helpers/OnlineFunctions.cs @@ -19,10 +19,10 @@ internal static class OnlineFunctions /// The cancellation token /// internal static async Task DownloadFileAsync( - this HttpClient client, string url, Stream destination, - IProgress? progress = null, - IProgress? downloadedBytes = null, int bufferSize = 81920, - CancellationToken cancellation = default) + this HttpClient client, string url, Stream destination, + IProgress? progress = null, + IProgress? downloadedBytes = null, int bufferSize = 81920, + CancellationToken cancellation = default) { using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation)) { @@ -35,7 +35,7 @@ internal static class OnlineFunctions if (progress == null || !contentLength.HasValue) { await download.CopyToAsync(destination, cancellation); - if(!contentLength.HasValue) + if (!contentLength.HasValue) progress?.Report(100f); return; } diff --git a/PluginManager/Online/PluginsManager.cs b/PluginManager/Online/PluginsManager.cs index 6737579..482b398 100644 --- a/PluginManager/Online/PluginsManager.cs +++ b/PluginManager/Online/PluginsManager.cs @@ -10,7 +10,7 @@ namespace PluginManager.Online; public class PluginsManager { - + #if DEBUG /// /// The Plugin Manager constructor @@ -22,16 +22,16 @@ public class PluginsManager PluginsLink = plink; VersionsLink = vlink; } - + #endif - + /// /// The Plugin Manager constructor. It uses the default links and the default branch. /// /// The main branch from where the plugin manager gets its info public PluginsManager(string? branch = "releases") { - PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList"; + PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList"; VersionsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/Versions"; } @@ -95,7 +95,7 @@ public class PluginsManager } catch (Exception exception) { - Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR ); + Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR); } return null; @@ -135,16 +135,18 @@ public class PluginsManager for (var i = 0; i < len; i++) { var contents = lines[i].Split(','); - if(Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows")) - {if (contents[0].ToLowerInvariant() == name.ToLowerInvariant()) + if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows")) { - if (contents.Length == 6) - return new[] { contents[2], contents[3], contents[5] }; - if (contents.Length == 5) - return new[] { contents[2], contents[3], string.Empty }; - throw new Exception("Failed to download plugin. Invalid Argument Length"); + if (contents[0].ToLowerInvariant() == name.ToLowerInvariant()) + { + if (contents.Length == 6) + return new[] { contents[2], contents[3], contents[5] }; + if (contents.Length == 5) + return new[] { contents[2], contents[3], string.Empty }; + throw new Exception("Failed to download plugin. Invalid Argument Length"); + } } - }else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux")) + else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux")) { if (contents.Length == 6) return new[] { contents[2], contents[3], contents[5] }; diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs index 25ccae4..340825b 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/PluginManager/Online/ServerCom.cs @@ -30,7 +30,7 @@ public static class ServerCom /// The to track the download /// public static async Task DownloadFileAsync( - string URL, string location, IProgress progress, + string URL, string location, IProgress progress, IProgress? downloadedBytes) { using (var client = new HttpClient()) @@ -48,15 +48,15 @@ public static class ServerCom { await DownloadFileAsync(URl, location, progress, null); } - + public static Task CreateDownloadTask(string URl, string location) { return DownloadFileAsync(URl, location, null, null); } - + public static Task CreateDownloadTask(string URl, string location, IProgress progress) { return DownloadFileAsync(URl, location, progress, null); } - + } diff --git a/PluginManager/Others/Actions/InternalActionsManager.cs b/PluginManager/Others/Actions/InternalActionsManager.cs index 8b67091..8c8563b 100644 --- a/PluginManager/Others/Actions/InternalActionsManager.cs +++ b/PluginManager/Others/Actions/InternalActionsManager.cs @@ -26,7 +26,7 @@ public class InternalActionManager Actions.TryAdd(action.ActionName, action); } } - + public async Task Refresh() { Actions.Clear(); @@ -59,7 +59,7 @@ public class InternalActionManager } catch (Exception e) { - Config.Logger.Log(e.Message , type: LogType.ERROR, source: typeof(InternalActionManager)); + Config.Logger.Log(e.Message, type: LogType.ERROR, source: typeof(InternalActionManager)); return e.Message; } } diff --git a/PluginManager/Others/ArchiveManager.cs b/PluginManager/Others/ArchiveManager.cs index 24f9c64..d2affa9 100644 --- a/PluginManager/Others/ArchiveManager.cs +++ b/PluginManager/Others/ArchiveManager.cs @@ -37,24 +37,24 @@ public static class ArchiveManager if (!File.Exists(archName)) throw new Exception("Failed to load file !"); - + byte[]? data = null; - + using (var zip = ZipFile.OpenRead(archName)) { var entry = zip.Entries.FirstOrDefault(entry => entry.FullName == fileName || entry.Name == fileName); if (entry is null) throw new Exception("File not found in archive"); - + var MemoryStream = new MemoryStream(); - + var stream = entry.Open(); await stream.CopyToAsync(MemoryStream); data = MemoryStream.ToArray(); - + stream.Close(); MemoryStream.Close(); } - + return data; } @@ -117,7 +117,7 @@ public static class ArchiveManager { if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES) { - var totalZIPFiles = archive.Entries.Count(); + var totalZIPFiles = archive.Entries.Count(); var currentZIPFile = 0; foreach (var entry in archive.Entries) { @@ -173,4 +173,4 @@ public static class ArchiveManager } } } -} \ No newline at end of file +} diff --git a/PluginManager/Others/DBCommandExecutingArguments.cs b/PluginManager/Others/DBCommandExecutingArguments.cs index 4b44a8f..bd8b5e6 100644 --- a/PluginManager/Others/DBCommandExecutingArguments.cs +++ b/PluginManager/Others/DBCommandExecutingArguments.cs @@ -29,19 +29,19 @@ public class DBCommandExecutingArguments { this.cleanContent = message.Content.Substring(Config.DiscordBot.botPrefix.Length); } - + var split = this.cleanContent.Split(' '); string[]? argsClean = null; if (split.Length > 1) argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' '); - + this.commandUsed = split[0]; - this.arguments = argsClean; + this.arguments = argsClean; } - public SocketCommandContext context { get; init; } - public string cleanContent { get; init; } - public string commandUsed { get; init; } - public string[]? arguments { get; init; } + public SocketCommandContext context { get; init; } + public string cleanContent { get; init; } + public string commandUsed { get; init; } + public string[]? arguments { get; init; } } diff --git a/PluginManager/Others/Enums.cs b/PluginManager/Others/Enums.cs index ac601dc..4f080ad 100644 --- a/PluginManager/Others/Enums.cs +++ b/PluginManager/Others/Enums.cs @@ -40,8 +40,8 @@ public enum InternalActionRunType ON_CALL } -internal enum ExceptionExitCode : int +internal enum ExceptionExitCode: int { CONFIG_FAILED_TO_LOAD = 1, - CONFIG_KEY_NOT_FOUND = 2, + CONFIG_KEY_NOT_FOUND = 2, } diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 64503b3..7c71576 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -54,8 +54,8 @@ public static class Functions /// Triggered if is not readable /// Triggered in is not writable public static async Task CopyToOtherStreamAsync( - this Stream stream, Stream destination, int bufferSize, - IProgress? progress = null, + this Stream stream, Stream destination, int bufferSize, + IProgress? progress = null, CancellationToken cancellationToken = default) { if (stream == null) throw new ArgumentNullException(nameof(stream)); @@ -76,7 +76,7 @@ public static class Functions progress?.Report(totalBytesRead); } } - + public static T SelectRandomValueOf() { diff --git a/PluginManager/Others/JsonManager.cs b/PluginManager/Others/JsonManager.cs index 1950346..11fc42b 100644 --- a/PluginManager/Others/JsonManager.cs +++ b/PluginManager/Others/JsonManager.cs @@ -38,10 +38,10 @@ public class JsonManager else text = new MemoryStream(Encoding.ASCII.GetBytes(input)); text.Position = 0; - + var obj = await JsonSerializer.DeserializeAsync(text); await text.FlushAsync(); text.Close(); return (obj ?? default)!; } -} \ No newline at end of file +} diff --git a/PluginManager/Others/Logger/Log.cs b/PluginManager/Others/Logger/Log.cs index 03e2921..1048004 100644 --- a/PluginManager/Others/Logger/Log.cs +++ b/PluginManager/Others/Logger/Log.cs @@ -4,60 +4,46 @@ using PluginManager.Interfaces.Logger; namespace PluginManager.Others.Logger; -public class Log : ILog +public class Log: ILog { - public string Message { get; set; } - public string OutputFile { get; set; } - public Type? Source { get; set; } - public LogType Type { get; set; } - public DateTime ThrowTime { get; set; } - - public Log(string message, string outputFile, Type? source, LogType type, DateTime throwTime) + public string Message { get; set; } + public Type? Source { get; set; } + public LogType Type { get; set; } + public DateTime ThrowTime { get; set; } + + public Log(string message, Type? source, LogType type, DateTime throwTime) { - Message = message; - OutputFile = outputFile; - Source = source; - Type = type; - ThrowTime = throwTime; + Message = message; + Source = source; + Type = type; + ThrowTime = throwTime; } - - public Log(string message, string outputFile, Type? source, LogType type) + + public Log(string message, Type? source, LogType type) { - Message = message; - OutputFile = outputFile; - Source = source; - Type = type; - ThrowTime = DateTime.Now; + Message = message; + Source = source; + Type = type; + ThrowTime = DateTime.Now; } - - public Log(string message, string outputFile, Type? source) + + public Log(string message, Type? source) { - Message = message; - OutputFile = outputFile; - Source = source; - Type = LogType.INFO; - ThrowTime = DateTime.Now; + Message = message; + Source = source; + Type = LogType.INFO; + ThrowTime = DateTime.Now; } - - public Log(string message, string outputFile) - { - Message = message; - OutputFile = outputFile; - Source = typeof(Log); - Type = LogType.INFO; - ThrowTime = DateTime.Now; - } - + public Log(string message) { - Message = message; - OutputFile = ""; - Source = typeof(Log); - Type = LogType.INFO; - ThrowTime = DateTime.Now; + Message = message; + Source = typeof(Log); + Type = LogType.INFO; + ThrowTime = DateTime.Now; } - - public static implicit operator Log(string message) => new (message); + + public static implicit operator Log(string message) => new(message); public static implicit operator string(Log log) => $"[{log.ThrowTime}] {log.Message}"; @@ -65,7 +51,7 @@ public class Log : ILog { return $"[{ThrowTime}] [{Source}] [{Type}] {Message}"; } - + public string AsShortString() { return this; diff --git a/PluginManager/Others/Logger/Logger.cs b/PluginManager/Others/Logger/Logger.cs index 33462f7..b4f543b 100644 --- a/PluginManager/Others/Logger/Logger.cs +++ b/PluginManager/Others/Logger/Logger.cs @@ -6,64 +6,72 @@ using PluginManager.Interfaces.Logger; namespace PluginManager.Others.Logger; -public sealed class Logger : ILogger +public sealed class Logger: ILogger { - public bool IsEnabled { get; init; } - public bool OutputToFile { get; init; } + public bool IsEnabled { get; init; } + public bool OutputToFile { get; init; } + public string? OutputFile { get; init; } - private LogType LowestLogLevel { get; } - private bool UseShortVersion { get; } - - public Logger(bool useShortVersion, bool outputToFile, LogType lowestLogLevel = LogType.INFO) + private LogType LowestLogLevel { get; } + private bool UseShortVersion { get; } + + public Logger(bool useShortVersion, bool outputToFile, string outputFile, LogType lowestLogLevel = LogType.INFO) { UseShortVersion = useShortVersion; OutputToFile = outputToFile; IsEnabled = true; LowestLogLevel = lowestLogLevel; + OutputFile = outputFile; + } + + public Logger(bool useShortVersion, LogType lowestLogLevel = LogType.INFO) + { + UseShortVersion = useShortVersion; + OutputToFile = false; + IsEnabled = true; + LowestLogLevel = lowestLogLevel; + OutputFile = null; } public event EventHandler? OnLog; - + private async Task Log(Log logMessage) { if (!IsEnabled) return; - + OnLog?.Invoke(this, logMessage); - + if (logMessage.Type < LowestLogLevel) return; if (OutputToFile) await File.AppendAllTextAsync( - logMessage.OutputFile, - (UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n"); + OutputFile!, + (UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n" + ); } - - public async void Log(string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default) + + public async void Log(string message = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default) { if (!IsEnabled) return; - + if (type < LowestLogLevel) return; if (string.IsNullOrEmpty(message)) return; - if (string.IsNullOrEmpty(outputFile)) outputFile = Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; - - if(throwTime == default) throwTime = DateTime.Now; - + if (throwTime == default) throwTime = DateTime.Now; + if (source == default) source = typeof(Log); - - await Log(new Log(message, outputFile, source, type, throwTime)); - + + await Log(new Log(message, source, type, throwTime)); + } public async void Log(Exception exception, LogType logType = LogType.ERROR, Type? source = null) { if (!IsEnabled) return; - + if (logType < LowestLogLevel) return; - await Log(new Log(exception.Message, - Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log", - source, logType, DateTime.Now)); + await Log(new Log(exception.Message, source, logType, DateTime.Now)); } } diff --git a/PluginManager/Others/SettingsDictionary.cs b/PluginManager/Others/SettingsDictionary.cs index 23834de..e913c69 100644 --- a/PluginManager/Others/SettingsDictionary.cs +++ b/PluginManager/Others/SettingsDictionary.cs @@ -5,11 +5,11 @@ using System.Threading.Tasks; namespace PluginManager.Others; -public class SettingsDictionary : IDictionary +public class SettingsDictionary: IDictionary { public string? _file { get; } private IDictionary? _dictionary; - + public SettingsDictionary(string? file) { _file = file; @@ -19,7 +19,7 @@ public class SettingsDictionary : IDictionary SaveToFile(); } } - + public async Task SaveToFile() { if (!string.IsNullOrEmpty(_file)) @@ -36,8 +36,8 @@ public class SettingsDictionary : IDictionary string FileContent = File.ReadAllText(_file); if (string.IsNullOrEmpty(FileContent)) File.WriteAllText(_file, "{}"); - - if(!FileContent.Contains("{") || !FileContent.Contains("}")) + + if (!FileContent.Contains("{") || !FileContent.Contains("}")) File.WriteAllText(_file, "{}"); } else @@ -61,7 +61,7 @@ public class SettingsDictionary : IDictionary IEnumerator IEnumerable.GetEnumerator() { - return ((IEnumerable) _dictionary!).GetEnumerator(); + return ((IEnumerable)_dictionary!).GetEnumerator(); } public void Add(KeyValuePair item) @@ -89,7 +89,7 @@ public class SettingsDictionary : IDictionary return this._dictionary!.Remove(item); } - public int Count => _dictionary!.Count; + public int Count => _dictionary!.Count; public bool IsReadOnly => _dictionary!.IsReadOnly; public void Add(TKey key, TValue value) { @@ -116,9 +116,9 @@ public class SettingsDictionary : IDictionary get { if (this._dictionary!.ContainsKey(key)) - if(this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s)) + if (this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s)) return this._dictionary[key]; - + return default!; } set => this._dictionary![key] = value; @@ -126,4 +126,4 @@ public class SettingsDictionary : IDictionary public ICollection Keys => _dictionary!.Keys; public ICollection Values => _dictionary!.Values; -} \ No newline at end of file +} diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj index bc8dbce..4ec873e 100644 --- a/PluginManager/PluginManager.csproj +++ b/PluginManager/PluginManager.csproj @@ -9,10 +9,10 @@ false - + - - + + \ No newline at end of file diff --git a/SethTests/SethTests.csproj b/SethTests/SethTests.csproj index f55c2d1..e2d19d2 100644 --- a/SethTests/SethTests.csproj +++ b/SethTests/SethTests.csproj @@ -22,12 +22,12 @@ - + - - + +