From 5bb13aa4a69b19542f14deb6cd635e521eb7ab7e Mon Sep 17 00:00:00 2001 From: Wizzy69 Date: Sun, 13 Nov 2022 16:28:44 +0200 Subject: [PATCH] The library can now be used for Windows exclusive bots (Made with WinForm or Wpf) --- DiscordBot/Program.cs | 40 ++++--- PluginManager/Items/ConsoleCommandsHandler.cs | 64 +++++----- PluginManager/Loaders/PluginLoader.cs | 16 +-- PluginManager/Logger.cs | 65 +++++++++++ .../Online/Helpers/OnlineFunctions.cs | 13 ++- PluginManager/Online/PluginsManager.cs | 4 +- PluginManager/Online/Updates/PluginUpdater.cs | 2 +- PluginManager/Others/Console Utilities.cs | 109 +++++++++--------- PluginManager/Others/Functions.cs | 4 +- PluginManager/Variables.cs | 6 +- SethDiscordBot.sln | 6 + 11 files changed, 202 insertions(+), 127 deletions(-) create mode 100644 PluginManager/Logger.cs diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index b64dfae..adcfcea 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -195,7 +195,7 @@ public class Program private static void NoGUI() { #if DEBUG - Settings.Variables.outputStream.WriteLine(); + Logger.WriteLine(); ConsoleCommandsHandler.ExecuteCommad("lp").Wait(); #else if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); @@ -211,7 +211,7 @@ public class Program #endif ) && cmd.Length > 0) - Settings.Variables.outputStream.WriteLine("Failed to run command " + cmd); + Logger.WriteLine("Failed to run command " + cmd); } } @@ -229,11 +229,11 @@ public class Program "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage"); foreach (var message in startupMessageList) - Settings.Variables.outputStream.WriteLine(message); + Logger.WriteLine(message); - Settings.Variables.outputStream.WriteLine( + Logger.WriteLine( $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); - Settings.Variables.outputStream.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); + Logger.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); Utilities.WriteColorText( "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); @@ -245,7 +245,7 @@ public class Program Utilities.WriteColorText( "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); - Settings.Variables.outputStream.WriteLine("============================ LOG ============================"); + Logger.WriteLine("============================ LOG ============================"); try { @@ -254,7 +254,7 @@ public class Program if (await Settings.sqlDatabase.TableExistsAsync("BetaTest")) { - Settings.Variables.outputStream.WriteLine("Starting in DEBUG MODE"); + Logger.WriteLine("Starting in DEBUG MODE"); token = await Settings.sqlDatabase.GetValueAsync("BetaTest", "VariableName", "Token", "Value"); } else token = Config.Variables.GetValue("token"); @@ -268,7 +268,7 @@ public class Program } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine(ex); + Logger.LogError(ex); return null; } } @@ -287,7 +287,7 @@ public class Program if (len > 0 && args[0] == "/remplug") { var plugName = string.Join(' ', args, 1, args.Length - 1); - Settings.Variables.outputStream.WriteLine("Starting to remove " + plugName); + Logger.WriteLine("Starting to remove " + plugName); await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName); loadPluginsOnStartup = true; } @@ -318,8 +318,12 @@ public class Program private static async Task PreLoadComponents() { - Settings.Variables.outputStream = Console.Out; - Settings.Variables.outputStream.WriteLine("Loading resources ..."); + Logger.LogEvent += (message) => + { + Console.Write(message); + }; + + Logger.WriteLine("Loading resources ..."); var main = new Utilities.ProgressBar(ProgressBarType.NO_END); main.Start(); Directory.CreateDirectory("./Data/Resources"); @@ -390,19 +394,19 @@ public class Program Console.Clear(); Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("A new version of the bot is available !"); + Logger.WriteLine("A new version of the bot is available !"); Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("Current version : " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); + Logger.WriteLine("Current version : " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("New version : " + newVersion); + Logger.WriteLine("New version : " + newVersion); Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine("Changelog :"); + Logger.WriteLine("Changelog :"); List changeLog = await ServerCom.ReadTextFromURL("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot"); foreach (var item in changeLog) Utilities.WriteColorText(item); - Console.WriteLine("Do you want to update the bot ? (y/n)"); + Logger.WriteLine("Do you want to update the bot ? (y/n)"); if (Console.ReadKey().Key == ConsoleKey.Y) { @@ -418,7 +422,7 @@ public class Program { var url = $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip"; - Settings.Variables.outputStream.WriteLine("Downloading update ..."); + Logger.WriteLine("Downloading update ..."); await ServerCom.DownloadFileNoProgressAsync(url, "./update.zip"); await File.WriteAllTextAsync("Install.sh", "#!/bin/bash\nunzip -qq update.zip -d ./\nrm update.zip\nchmod +x SethDiscordBot\n./DiscordBot"); @@ -441,7 +445,7 @@ public class Program !File.Exists("./Updater/Updater.exe")) { Console.Clear(); - Settings.Variables.outputStream.WriteLine("Installing updater ...\nDo NOT close the bot during update !"); + Logger.WriteLine("Installing updater ...\nDo NOT close the bot during update !"); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); await ServerCom.DownloadFileNoProgressAsync( diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 36589e0..475ea69 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -35,7 +35,7 @@ public class ConsoleCommandsHandler InitializeBasicCommands(); - //Settings.Variables.outputStream.WriteLine("Initialized console command handler !"); + //Logger.WriteLine("Initialized console command handler !"); } private void InitializeBasicCommands() @@ -46,7 +46,7 @@ public class ConsoleCommandsHandler { if (args.Length <= 1) { - Settings.Variables.outputStream.WriteLine("Available commands:"); + Logger.WriteLine("Available commands:"); var items = new List(); items.Add(new[] { "-", "-", "-" }); items.Add(new[] { "Command", "Description", "Usage" }); @@ -69,12 +69,12 @@ public class ConsoleCommandsHandler foreach (var command in commandList) if (command.CommandName == args[1]) { - Settings.Variables.outputStream.WriteLine("Command description: " + command.Description); - Settings.Variables.outputStream.WriteLine("Command execution format:" + command.Usage); + Logger.WriteLine("Command description: " + command.Description); + Logger.WriteLine("Command execution format:" + command.Usage); return; } - Settings.Variables.outputStream.WriteLine("Command not found"); + Logger.WriteLine("Command not found"); } } ); @@ -93,16 +93,16 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Settings.Variables.outputStream.WriteLine("[CMD] Successfully loaded command : " + name); + Logger.WriteLine("[CMD] Successfully loaded command : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; if (exception is null) - Settings.Variables.outputStream.WriteLine("An error occured while loading: " + name); + Logger.WriteLine("An error occured while loading: " + name); else - Settings.Variables.outputStream.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); + Logger.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -115,12 +115,12 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Settings.Variables.outputStream.WriteLine("[EVENT] Successfully loaded event : " + name); + Logger.WriteLine("[EVENT] Successfully loaded event : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; - Settings.Variables.outputStream.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); + Logger.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -134,12 +134,12 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Settings.Variables.outputStream.WriteLine("[SLASH] Successfully loaded command : " + name); + Logger.WriteLine("[SLASH] Successfully loaded command : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; - Settings.Variables.outputStream.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); + Logger.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -159,7 +159,7 @@ public class ConsoleCommandsHandler if (args.Length == 1) { isDownloading = false; - Settings.Variables.outputStream.WriteLine("Please specify plugin name"); + Logger.WriteLine("Please specify plugin name"); return; } @@ -202,13 +202,13 @@ public class ConsoleCommandsHandler } - Settings.Variables.outputStream.WriteLine("\n"); + Logger.WriteLine("\n"); // check requirements if any if (info.Length == 3 && info[2] != string.Empty && info[2] != null) { - Settings.Variables.outputStream.WriteLine($"Downloading requirements for plugin : {name}"); + Logger.WriteLine($"Downloading requirements for plugin : {name}"); var lines = await ServerCom.ReadTextFromURL(info[2]); @@ -217,7 +217,7 @@ public class ConsoleCommandsHandler if (!(line.Length > 0 && line.Contains(","))) continue; var split = line.Split(','); - Settings.Variables.outputStream.WriteLine($"\nDownloading item: {split[1]}"); + Logger.WriteLine($"\nDownloading item: {split[1]}"); if (File.Exists("./" + split[1])) File.Delete("./" + split[1]); if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { @@ -231,26 +231,26 @@ public class ConsoleCommandsHandler bar.Stop("Item downloaded !"); } - Settings.Variables.outputStream.WriteLine(); + Logger.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")) { - Settings.Variables.outputStream.WriteLine($"Extracting {split[1]} ..."); + Logger.WriteLine($"Extracting {split[1]} ..."); var bar = new Utilities.ProgressBar( ProgressBarType.NO_END); bar.Start(); await Functions.ExtractArchive("./" + split[1], "./", null, UnzipProgressType.PercentageFromTotalSize); bar.Stop("Extracted"); - Settings.Variables.outputStream.WriteLine("\n"); + Logger.WriteLine("\n"); File.Delete("./" + split[1]); } } - Settings.Variables.outputStream.WriteLine(); + Logger.WriteLine(); } var ver = await ServerCom.GetVersionOfPackageFromWeb(name); @@ -272,7 +272,7 @@ public class ConsoleCommandsHandler return; var data = Config.Variables.GetValue(args[1]); - Settings.Variables.outputStream.WriteLine($"{args[1]} => {data}"); + Logger.WriteLine($"{args[1]} => {data}"); } ); @@ -287,11 +287,11 @@ public class ConsoleCommandsHandler try { Config.Variables.Add(key, value, isReadOnly); - Settings.Variables.outputStream.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); + Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine(ex.ToString()); + Logger.WriteLine(ex.ToString()); } } ); @@ -335,7 +335,7 @@ public class ConsoleCommandsHandler } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine(ex.Message); + Logger.WriteLine(ex.Message); } }); @@ -351,7 +351,7 @@ public class ConsoleCommandsHandler } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine(ex.Message); + Logger.WriteLine(ex.Message); } }); @@ -385,13 +385,13 @@ public class ConsoleCommandsHandler if (!File.Exists(location)) { - Settings.Variables.outputStream.WriteLine("The plugin does not exist"); + Logger.WriteLine("The plugin does not exist"); return; } File.Delete(location); - Settings.Variables.outputStream.WriteLine("Removed the plugin DLL. Checking for other files ..."); + Logger.WriteLine("Removed the plugin DLL. Checking for other files ..."); var info = await manager.GetPluginLinkByName(plugName); if (info[2] != string.Empty) @@ -406,7 +406,7 @@ public class ConsoleCommandsHandler File.Delete("./" + split[1]); - Settings.Variables.outputStream.WriteLine("Removed: " + split[1]); + Logger.WriteLine("Removed: " + split[1]); } if (Directory.Exists($"./Data/Plugins/{plugName}")) @@ -417,7 +417,7 @@ public class ConsoleCommandsHandler } isDownloading = false; - Settings.Variables.outputStream.WriteLine(plugName + " has been successfully deleted !"); + Logger.WriteLine(plugName + " has been successfully deleted !"); }); AddCommand("reload", "Reload the bot with all plugins", () => @@ -491,17 +491,17 @@ public class ConsoleCommandsHandler { Console.SetCursorPosition(0, Console.CursorTop - 1); for (var i = 0; i < command.Length + 30; i++) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); Console.SetCursorPosition(0, Console.CursorTop); } - Settings.Variables.outputStream.WriteLine(); + Logger.WriteLine(); item.Action(args); return true; } return false; - //Settings.Variables.outputStream.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); + //Logger.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); } } \ No newline at end of file diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index 98ea502..da303e1 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -96,7 +96,7 @@ public class PluginLoader SlashCommands = new List(); Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); - Settings.Variables.outputStream.WriteLine("Loading plugins"); + Logger.WriteLine("Loading plugins"); var loader = new LoaderV2("./Data/Plugins", "dll"); loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded"); @@ -125,10 +125,10 @@ public class PluginLoader } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine(ex.ToString()); - Settings.Variables.outputStream.WriteLine("Plugin: " + args.PluginName); - Settings.Variables.outputStream.WriteLine("Type: " + args.TypeName); - Settings.Variables.outputStream.WriteLine("IsLoaded: " + args.IsLoaded); + Logger.WriteLine(ex.ToString()); + Logger.WriteLine("Plugin: " + args.PluginName); + Logger.WriteLine("Type: " + args.TypeName); + Logger.WriteLine("IsLoaded: " + args.IsLoaded); } break; case "DBSlashCommand": @@ -158,13 +158,13 @@ public class PluginLoader var instance = (DBEvent)Activator.CreateInstance(type); instance.Start(client); PluginLoader.Events.Add(instance); - Settings.Variables.outputStream.WriteLine($"[EVENT] Loaded external {type.FullName}!"); + Logger.WriteLine($"[EVENT] Loaded external {type.FullName}!"); } else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type)) { var instance = (DBCommand)Activator.CreateInstance(type); PluginLoader.Commands.Add(instance); - Settings.Variables.outputStream.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); + Logger.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); } else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type)) { @@ -177,7 +177,7 @@ public class PluginLoader await client.CreateGlobalApplicationCommandAsync(builder.Build()); PluginLoader.SlashCommands.Add(instance); - Settings.Variables.outputStream.WriteLine($"[SLASH] Instance: {type.FullName} loaded !"); + Logger.WriteLine($"[SLASH] Instance: {type.FullName} loaded !"); } } diff --git a/PluginManager/Logger.cs b/PluginManager/Logger.cs new file mode 100644 index 0000000..c643aa8 --- /dev/null +++ b/PluginManager/Logger.cs @@ -0,0 +1,65 @@ +using Discord; + +namespace PluginManager +{ + public static class Logger + { + + public static bool isConsole = true; + + + public delegate void LogEventHandler(string Message); + public static event LogEventHandler LogEvent; + + public static void Log(string Message) + { + LogEvent?.Invoke(Message); + } + + public static void Log(string Message, params object[] Args) + { + LogEvent?.Invoke(string.Format(Message, Args)); + } + + public static void Log(IMessage message, bool newLine) + { + LogEvent?.Invoke(message.Content); + if (newLine) + LogEvent?.Invoke("\n"); + } + + public static void WriteLine(string? message) + { + if (message is not null) + LogEvent?.Invoke(message + '\n'); + } + + public static void LogError(System.Exception ex) + { + string message = "[ERROR]" + ex.Message; + LogEvent?.Invoke(message + '\n'); + } + + public static void LogError(string? message) + { + if (message is not null) + LogEvent?.Invoke("[ERROR]" + message + '\n'); + } + + + public static void WriteLine() + { + LogEvent?.Invoke("\n"); + } + + public static void Write(string message) + { + LogEvent?.Invoke(message); + } + + public static void Write(char c) + { + LogEvent?.Invoke($"{c}"); + } + } +} diff --git a/PluginManager/Online/Helpers/OnlineFunctions.cs b/PluginManager/Online/Helpers/OnlineFunctions.cs index dcb7868..52c887d 100644 --- a/PluginManager/Online/Helpers/OnlineFunctions.cs +++ b/PluginManager/Online/Helpers/OnlineFunctions.cs @@ -3,6 +3,7 @@ using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; + using PluginManager.Others; namespace PluginManager.Online.Helpers; @@ -18,10 +19,10 @@ internal static class OnlineFunctions /// The that is used to track the download progress /// 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) + internal static async Task DownloadFileAsync(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)) { @@ -40,14 +41,14 @@ internal static class OnlineFunctions // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%) var relativeProgress = new Progress(totalBytes => { - progress.Report((float)totalBytes / contentLength.Value * 100); + progress?.Report((float)totalBytes / contentLength.Value * 100); downloadedBytes?.Report(totalBytes); } ); // Use extension method to report progress while downloading await download.CopyToOtherStreamAsync(destination, bufferSize, relativeProgress, cancellation); - progress.Report(1); + progress.Report(100); } } } diff --git a/PluginManager/Online/PluginsManager.cs b/PluginManager/Online/PluginsManager.cs index 5e71644..f509516 100644 --- a/PluginManager/Online/PluginsManager.cs +++ b/PluginManager/Online/PluginsManager.cs @@ -84,7 +84,7 @@ public class PluginsManager } catch (Exception exception) { - Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); + Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Functions.WriteErrFile(exception.ToString()); } } @@ -116,7 +116,7 @@ public class PluginsManager } catch (Exception exception) { - Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); + Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Functions.WriteErrFile(exception.ToString()); } diff --git a/PluginManager/Online/Updates/PluginUpdater.cs b/PluginManager/Online/Updates/PluginUpdater.cs index cd0d790..1b2bd48 100644 --- a/PluginManager/Online/Updates/PluginUpdater.cs +++ b/PluginManager/Online/Updates/PluginUpdater.cs @@ -23,7 +23,7 @@ public class PluginUpdater } catch (Exception ex) { - Console.WriteLine(ex.Message); + Logger.LogError(ex); } diff --git a/PluginManager/Others/Console Utilities.cs b/PluginManager/Others/Console Utilities.cs index e0149c0..61d8290 100644 --- a/PluginManager/Others/Console Utilities.cs +++ b/PluginManager/Others/Console Utilities.cs @@ -46,38 +46,38 @@ public static class Utilities foreach (var row in data) { if (row[0][0] == tableLine) - Settings.Variables.outputStream.Write(tableCross); + Logger.Write(tableCross); else - Settings.Variables.outputStream.Write(tableWall); + Logger.Write(tableWall); for (var l = 0; l < row.Length; l++) { if (row[l][0] == tableLine) { for (var i = 0; i < len[l] + 4; ++i) - Settings.Variables.outputStream.Write(tableLine); + Logger.Write(tableLine); } else if (row[l].Length == len[l]) { - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write(row[l]); - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); + Logger.Write(row[l]); + Logger.Write(" "); } else { var lenHalf = row[l].Length / 2; for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write(row[l]); + Logger.Write(" "); + Logger.Write(row[l]); for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); if (row[l].Length % 2 == 0) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); } - Settings.Variables.outputStream.Write(row[l][0] == tableLine ? tableCross : tableWall); + Logger.Write(row[l][0] == tableLine ? tableCross : tableWall); } - Settings.Variables.outputStream.WriteLine(); //end line + Logger.WriteLine(); //end line } return; @@ -95,44 +95,44 @@ public static class Utilities foreach (var row in data) { - Settings.Variables.outputStream.Write("\t"); + Logger.Write("\t"); if (row[0] == "-") - Settings.Variables.outputStream.Write("+"); + Logger.Write("+"); else - Settings.Variables.outputStream.Write("|"); + Logger.Write("|"); foreach (var s in row) { if (s == "-") { for (var i = 0; i < maxLen + 4; ++i) - Settings.Variables.outputStream.Write("-"); + Logger.Write("-"); } else if (s.Length == maxLen) { - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write(s); - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); + Logger.Write(s); + Logger.Write(" "); } else { var lenHalf = s.Length / 2; for (var i = 0; i < div - lenHalf; ++i) - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write(s); + Logger.Write(" "); + Logger.Write(s); for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); if (s.Length % 2 == 0) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); } if (s == "-") - Settings.Variables.outputStream.Write("+"); + Logger.Write("+"); else - Settings.Variables.outputStream.Write("|"); + Logger.Write("|"); } - Settings.Variables.outputStream.WriteLine(); //end line + Logger.WriteLine(); //end line } return; @@ -153,12 +153,12 @@ public static class Utilities { if (data[i][j] == "-") data[i][j] = " "; - Settings.Variables.outputStream.Write(data[i][j]); + Logger.Write(data[i][j]); for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); } - Settings.Variables.outputStream.WriteLine(); + Logger.WriteLine(); } return; @@ -169,12 +169,15 @@ public static class Utilities public static void WriteColorText(string text, bool appendNewLineAtEnd = true) { - if (Console.Out != Settings.Variables.outputStream) + if (!Logger.isConsole) { - Settings.Variables.outputStream.Write(text); + foreach (var item in Colors) + text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", ""); + Logger.Write(text); if (appendNewLineAtEnd) - Settings.Variables.outputStream.WriteLine(); + Logger.WriteLine(); return; + } var initialForeGround = Console.ForegroundColor; var input = text.ToCharArray(); @@ -197,12 +200,12 @@ public static class Utilities } else { - Settings.Variables.outputStream.Write(input[i]); + Logger.Write(input[i]); } Console.ForegroundColor = initialForeGround; if (appendNewLineAtEnd) - Settings.Variables.outputStream.WriteLine(); + Logger.WriteLine(); } @@ -219,7 +222,7 @@ public static class Utilities public ProgressBar(ProgressBarType type) { - if (Settings.Variables.outputStream != Console.Out) + if (!Logger.isConsole) throw new Exception("This class (or function) can be used with console only. For UI please use another approach."); this.type = type; } @@ -281,9 +284,9 @@ public static class Utilities { Console.CursorLeft = 0; for (var i = 0; i < BarLength + message.Length + 1; i++) - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); Console.CursorLeft = 0; - Settings.Variables.outputStream.WriteLine(message); + Logger.WriteLine(message); } } @@ -298,14 +301,14 @@ public static class Utilities private void UpdateNoEnd(string message) { Console.CursorLeft = 0; - Settings.Variables.outputStream.Write("["); + Logger.Write("["); for (var i = 1; i <= position; i++) - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write("<==()==>"); + Logger.Write(" "); + Logger.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write("] " + message); + Logger.Write(" "); + Logger.Write("] " + message); if (position == BarLength - 1 || position == 1) @@ -315,14 +318,14 @@ public static class Utilities private void UpdateNoEnd() { Console.CursorLeft = 0; - Settings.Variables.outputStream.Write("["); + Logger.Write("["); for (var i = 1; i <= position; i++) - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write("<==()==>"); + Logger.Write(" "); + Logger.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - Settings.Variables.outputStream.Write(" "); - Settings.Variables.outputStream.Write("]"); + Logger.Write(" "); + Logger.Write("]"); if (position == BarLength - 1 || position == 1) @@ -332,9 +335,9 @@ public static class Utilities private void UpdateNormal(float progress) { Console.CursorLeft = 0; - Settings.Variables.outputStream.Write("["); + Logger.Write("["); Console.CursorLeft = BarLength; - Settings.Variables.outputStream.Write("]"); + Logger.Write("]"); Console.CursorLeft = 1; var onechunk = 30.0f / Max; @@ -344,22 +347,22 @@ public static class Utilities { Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.CursorLeft = position++; - Settings.Variables.outputStream.Write("#"); + Logger.Write("#"); } for (var i = position; i < BarLength; i++) { Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.CursorLeft = position++; - Settings.Variables.outputStream.Write(" "); + Logger.Write(" "); } Console.CursorLeft = BarLength + 4; Console.BackgroundColor = ConsoleColor.Black; if (progress.CanAproximateTo(Max)) - Settings.Variables.outputStream.Write(progress + " % ✓"); + Logger.Write(progress + " % ✓"); else - Settings.Variables.outputStream.Write(MathF.Round(progress, 2) + " % "); + Logger.Write(MathF.Round(progress, 2) + " % "); } } } \ No newline at end of file diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index eb29510..cac962e 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -192,7 +192,7 @@ public static class Functions } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); } currentZIPFile++; @@ -224,7 +224,7 @@ public static class Functions } catch (Exception ex) { - Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); } await Task.Delay(10); diff --git a/PluginManager/Variables.cs b/PluginManager/Variables.cs index d830db0..2c4dfab 100644 --- a/PluginManager/Variables.cs +++ b/PluginManager/Variables.cs @@ -1,6 +1,4 @@ -using System.IO; - -using PluginManager.Database; +using PluginManager.Database; namespace PluginManager { @@ -11,8 +9,6 @@ namespace PluginManager { public static string WebsiteURL = "https://wizzy69.github.io/SethDiscordBot"; public static string UpdaterURL = "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip"; - - public static TextWriter outputStream; } public static SqlDatabase sqlDatabase; diff --git a/SethDiscordBot.sln b/SethDiscordBot.sln index bcf2c27..fa4e22c 100644 --- a/SethDiscordBot.sln +++ b/SethDiscordBot.sln @@ -13,6 +13,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\Discord EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotUI", "..\DiscordBotItems\DiscordBotUI\DiscordBotUI.csproj", "{3202CE21-BB39-452E-9B0C-740528CAFE43}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -39,6 +41,10 @@ Global {0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Release|Any CPU.Build.0 = Release|Any CPU + {3202CE21-BB39-452E-9B0C-740528CAFE43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3202CE21-BB39-452E-9B0C-740528CAFE43}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3202CE21-BB39-452E-9B0C-740528CAFE43}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3202CE21-BB39-452E-9B0C-740528CAFE43}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE