diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index 020e194..dbe55d4 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -50,9 +50,7 @@ public class Program private static void NoGUI() { #if DEBUG - Logger.WriteLine(); - Logger.WriteLine("Debug mode enabled"); - Logger.WriteLine(); + Console.WriteLine("Debug mode enabled"); #endif if (loadPluginsOnStartup) @@ -67,7 +65,7 @@ public class Program #endif ) && cmd.Length > 0) - Logger.WriteLine("Failed to run command " + cmd); + Console.WriteLine("Failed to run command " + cmd); } } @@ -85,7 +83,7 @@ public class Program "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage"); foreach (var message in startupMessageList) - Logger.WriteLine(message); + Config.Logger.Log(message); Logger.WriteLine( $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); diff --git a/PluginManager/Bot/Boot.cs b/PluginManager/Bot/Boot.cs index b6b8039..506bcf0 100644 --- a/PluginManager/Bot/Boot.cs +++ b/PluginManager/Bot/Boot.cs @@ -106,30 +106,27 @@ public class Boot if (arg.Message.Contains("401")) { Config.Data.Remove("token"); - Logger.LogError("The token is invalid. Please restart the bot and enter a valid token."); + Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", this, Others.TextType.ERROR); await Task.Delay(4000); Environment.Exit(0); } - - Logger.WriteErrFile(arg); } private async Task Client_LoggedOut() { - Logger.WriteLine("Successfully Logged Out"); + Config.Logger.Log("Successfully Logged Out", this); await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); } private Task Ready() { - Console.Title = "ONLINE"; isReady = true; return Task.CompletedTask; } private Task LoggedIn() { - Console.Title = "CONNECTED"; + Config.Logger.Log("Successfully Logged In", this); return Task.CompletedTask; } @@ -139,15 +136,13 @@ public class Boot { case LogSeverity.Error: case LogSeverity.Critical: - Logger.WriteErrFile(message.Message); - Logger.WriteColored(message.Message + "\n", ConsoleColor.Red); + Config.Logger.Log(message.Message, this, Others.TextType.ERROR); break; case LogSeverity.Info: case LogSeverity.Debug: - Logger.WriteLogFile(message.Message); - Logger.WriteColored(message.Message + "\n", ConsoleColor.White); + Config.Logger.Log(message.Message, this); break; diff --git a/PluginManager/Bot/CommandHandler.cs b/PluginManager/Bot/CommandHandler.cs index 7882325..d85923d 100644 --- a/PluginManager/Bot/CommandHandler.cs +++ b/PluginManager/Bot/CommandHandler.cs @@ -146,9 +146,7 @@ internal class CommandHandler } catch (Exception ex) { - ex.WriteErrFile(); - - Console.WriteLine(ex.ToString()); + Config.Logger.Log(ex.Message, this, TextType.ERROR); } } } \ No newline at end of file diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index 4a33300..49b3069 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using PluginManager.Others; using System.Collections; using PluginManager.Online.Helpers; +using PluginManager.Others.Logger; namespace PluginManager; @@ -13,6 +14,7 @@ public static class Config { private static bool IsLoaded = false; + public static DBLogger Logger; public static Json Data; public static Json Plugins; @@ -27,14 +29,19 @@ public static class Config Data = new Json("./Data/Resources/config.json"); Plugins = new Json("./Data/Resources/Plugins.json"); + + Logger = new DBLogger(); + + PluginManager.Logger.Initialize(isConsole); - Logger.Initialize(isConsole); ArchiveManager.Initialize(); IsLoaded = true; if (isConsole) - Logger.LogEvent += (message) => { Console.Write(message); }; + PluginManager.Logger.LogEvent += (message) => { Console.Write(message); }; + + Logger.Log("Config initialized", TextType.NORMAL); } public class Json : IDictionary diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 2bd57ef..9753ed6 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -48,11 +48,13 @@ public class ConsoleCommandsHandler if (args.Length <= 1) { Logger.WriteLine("Available commands:"); - var items = new List(); - items.Add(new[] { "-", "-", "-" }); - items.Add(new[] { "Command", "Description", "Usage" }); - items.Add(new[] { " ", " ", "Argument type: [required]" }); - items.Add(new[] { "-", "-", "-" }); + var items = new List + { + new[] { "-", "-", "-" }, + new[] { "Command", "Description", "Usage" }, + new[] { " ", " ", "Argument type: [required]" }, + new[] { "-", "-", "-" } + }; foreach (var command in commandList) { diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index 94cce23..e4b3b95 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -9,7 +9,6 @@ using Discord.WebSocket; using PluginManager.Interfaces; using PluginManager.Online; -using PluginManager.Online.Updates; namespace PluginManager.Loaders; @@ -82,34 +81,16 @@ public class PluginLoader /// public async void LoadPlugins() { - //Check for updates in commands - foreach (var file in Directory.GetFiles("./Data/Plugins/", $"*.{pluginExtension}", - SearchOption.AllDirectories)) - await Task.Run(async () => - { - var name = new FileInfo(file).Name.Split('.')[0]; - var version = await ServerCom.GetVersionOfPackageFromWeb(name); - if (version is null) - return; - if (Config.Plugins[name] is not null) - Config.Plugins[name] = version.ToShortString(); - - if (await PluginUpdater.CheckForUpdates(name)) - await PluginUpdater.Download(name); - }); - - //Load all plugins Commands = new List(); Events = new List(); SlashCommands = new List(); - Logger.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); - Logger.WriteLine("Loading plugins"); + Config.Logger.Log("Starting plugin loader ... Client: " + _client.CurrentUser.Username, this, Others.TextType.NORMAL); var loader = new Loader("./Data/Plugins", "dll"); - loader.FileLoaded += (args) => Logger.WriteLogFile($"{args.PluginName} file Loaded"); + loader.FileLoaded += (args) => Config.Logger.Log($"{args.PluginName} file Loaded", this , Others.TextType.SUCCESS); loader.PluginLoaded += Loader_PluginLoaded; var res = loader.Load(); Events = res.Item1; @@ -135,10 +116,7 @@ public class PluginLoader } catch (Exception ex) { - Logger.WriteLine(ex.ToString()); - Logger.WriteLine("Plugin: " + args.PluginName); - Logger.WriteLine("Type: " + args.TypeName); - Logger.WriteLine("IsLoaded: " + args.IsLoaded); + Config.Logger.Log(ex.Message, this, Others.TextType.ERROR); } break; case "DBSlashCommand": @@ -168,13 +146,13 @@ public class PluginLoader var instance = (DBEvent)Activator.CreateInstance(type); instance.Start(client); PluginLoader.Events.Add(instance); - Logger.WriteLine($"[EVENT] Loaded external {type.FullName}!"); + Config.Logger.Log($"[EVENT] Loaded external {type.FullName}!", Others.TextType.SUCCESS); } else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type)) { var instance = (DBCommand)Activator.CreateInstance(type); PluginLoader.Commands.Add(instance); - Logger.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); + Config.Logger.Log($"[CMD] Instance: {type.FullName} loaded !", Others.TextType.SUCCESS); } else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type)) { @@ -187,7 +165,7 @@ public class PluginLoader await client.CreateGlobalApplicationCommandAsync(builder.Build()); PluginLoader.SlashCommands.Add(instance); - Logger.WriteLine($"[SLASH] Instance: {type.FullName} loaded !"); + Config.Logger.Log($"[SLASH] Instance: {type.FullName} loaded !", Others.TextType.SUCCESS); } } diff --git a/PluginManager/Logger.cs b/PluginManager/Logger.cs index 68d79d9..3ee5d7e 100644 --- a/PluginManager/Logger.cs +++ b/PluginManager/Logger.cs @@ -7,9 +7,9 @@ using Discord; namespace PluginManager { + [Obsolete("Use Logger from PluginManager.Others.Logger namespace instead\nThis class will be removed soon")] public static class Logger { - public static bool isConsole { get; private set; } private static bool isInitialized; @@ -18,7 +18,6 @@ namespace PluginManager public static void Initialize(bool console) { - if (isInitialized) throw new Exception("Logger is already initialized"); diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs index beaf976..c1f3b90 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/PluginManager/Online/ServerCom.cs @@ -89,11 +89,6 @@ public static class ServerCom await DownloadFileAsync(URL, location, progress); } - public static VersionString? GetVersionOfPackage(string pakName) - { - return new VersionString(Config.Plugins[pakName]); - } - public static async Task GetVersionOfPackageFromWeb(string pakName) { var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions"; diff --git a/PluginManager/Online/Updates/PluginUpdater.cs b/PluginManager/Online/Updates/PluginUpdater.cs deleted file mode 100644 index b38a691..0000000 --- a/PluginManager/Online/Updates/PluginUpdater.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Threading.Tasks; -using System.Collections.Generic; - -using PluginManager.Items; -using PluginManager.Others; - -namespace PluginManager.Online.Updates; - -public class PluginUpdater -{ - public static async Task CheckForUpdates(string pakName) - { - try - { - var webV = await ServerCom.GetVersionOfPackageFromWeb(pakName); - var local = ServerCom.GetVersionOfPackage(pakName); - - if (local is null) return true; - if (webV is null) return false; - - if (webV == local) return false; - if (webV > local) return true; - } - catch (Exception ex) - { - Logger.LogError(ex); - } - - - return false; - } - - public static async Task> GetInfo(string pakName) - { - - Utilities.WriteColorText("An update was found for &g" + pakName + "&c. Version: &r" + - (await ServerCom.GetVersionOfPackageFromWeb(pakName))?.ToShortString() + - "&c. Current Version: &y" + - ServerCom.GetVersionOfPackage(pakName)?.ToShortString()); - - List fileInfo = await ServerCom.ReadTextFromURL(""); - return fileInfo; - } - - public static async Task Download(string pakName) - { - var pakUpdateInfo = await GetInfo(pakName); - Logger.Log(string.Join("\n", pakUpdateInfo)); - await ConsoleCommandsHandler.ExecuteCommad("dwplug " + pakName); - } -} \ No newline at end of file diff --git a/PluginManager/Others/ArchiveManager.cs b/PluginManager/Others/ArchiveManager.cs index b609ee6..4d97666 100644 --- a/PluginManager/Others/ArchiveManager.cs +++ b/PluginManager/Others/ArchiveManager.cs @@ -95,7 +95,7 @@ namespace PluginManager.Others } catch (Exception ex) { - Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}", "Archive Manager", TextType.ERROR); } currentZIPFile++; @@ -127,7 +127,7 @@ namespace PluginManager.Others } catch (Exception ex) { - Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}", "Archive Manager", TextType.ERROR); } await Task.Delay(10); diff --git a/PluginManager/Others/Console Utilities.cs b/PluginManager/Others/Console Utilities.cs index 61d8290..881dfce 100644 --- a/PluginManager/Others/Console Utilities.cs +++ b/PluginManager/Others/Console Utilities.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using System.Threading.Tasks; +using PluginManager; + namespace PluginManager.Others; public static class Utilities @@ -46,38 +48,38 @@ public static class Utilities foreach (var row in data) { if (row[0][0] == tableLine) - Logger.Write(tableCross); + PluginManager.Logger.Write(tableCross); else - Logger.Write(tableWall); + PluginManager.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) - Logger.Write(tableLine); + PluginManager.Logger.Write(tableLine); } else if (row[l].Length == len[l]) { - Logger.Write(" "); - Logger.Write(row[l]); - Logger.Write(" "); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write(row[l]); + PluginManager.Logger.Write(" "); } else { var lenHalf = row[l].Length / 2; for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) - Logger.Write(" "); - Logger.Write(row[l]); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write(row[l]); for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) - Logger.Write(" "); + PluginManager.Logger.Write(" "); if (row[l].Length % 2 == 0) - Logger.Write(" "); + PluginManager.Logger.Write(" "); } - Logger.Write(row[l][0] == tableLine ? tableCross : tableWall); + PluginManager.Logger.Write(row[l][0] == tableLine ? tableCross : tableWall); } - Logger.WriteLine(); //end line + PluginManager.Logger.WriteLine(); //end line } return; @@ -95,44 +97,44 @@ public static class Utilities foreach (var row in data) { - Logger.Write("\t"); + PluginManager.Logger.Write("\t"); if (row[0] == "-") - Logger.Write("+"); + PluginManager.Logger.Write("+"); else - Logger.Write("|"); + PluginManager.Logger.Write("|"); foreach (var s in row) { if (s == "-") { for (var i = 0; i < maxLen + 4; ++i) - Logger.Write("-"); + PluginManager.Logger.Write("-"); } else if (s.Length == maxLen) { - Logger.Write(" "); - Logger.Write(s); - Logger.Write(" "); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write(s); + PluginManager.Logger.Write(" "); } else { var lenHalf = s.Length / 2; for (var i = 0; i < div - lenHalf; ++i) - Logger.Write(" "); - Logger.Write(s); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write(s); for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) - Logger.Write(" "); + PluginManager.Logger.Write(" "); if (s.Length % 2 == 0) - Logger.Write(" "); + PluginManager.Logger.Write(" "); } if (s == "-") - Logger.Write("+"); + PluginManager.Logger.Write("+"); else - Logger.Write("|"); + PluginManager.Logger.Write("|"); } - Logger.WriteLine(); //end line + PluginManager.Logger.WriteLine(); //end line } return; @@ -153,12 +155,12 @@ public static class Utilities { if (data[i][j] == "-") data[i][j] = " "; - Logger.Write(data[i][j]); + PluginManager.Logger.Write(data[i][j]); for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) - Logger.Write(" "); + PluginManager.Logger.Write(" "); } - Logger.WriteLine(); + PluginManager.Logger.WriteLine(); } return; @@ -169,13 +171,13 @@ public static class Utilities public static void WriteColorText(string text, bool appendNewLineAtEnd = true) { - if (!Logger.isConsole) + if (!PluginManager.Logger.isConsole) { foreach (var item in Colors) text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", ""); - Logger.Write(text); + PluginManager.Logger.Write(text); if (appendNewLineAtEnd) - Logger.WriteLine(); + PluginManager.Logger.WriteLine(); return; } @@ -200,12 +202,12 @@ public static class Utilities } else { - Logger.Write(input[i]); + PluginManager.Logger.Write(input[i]); } Console.ForegroundColor = initialForeGround; if (appendNewLineAtEnd) - Logger.WriteLine(); + PluginManager.Logger.WriteLine(); } @@ -222,7 +224,7 @@ public static class Utilities public ProgressBar(ProgressBarType type) { - if (!Logger.isConsole) + 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; } @@ -284,9 +286,9 @@ public static class Utilities { Console.CursorLeft = 0; for (var i = 0; i < BarLength + message.Length + 1; i++) - Logger.Write(" "); + PluginManager.Logger.Write(" "); Console.CursorLeft = 0; - Logger.WriteLine(message); + PluginManager.Logger.WriteLine(message); } } @@ -301,14 +303,14 @@ public static class Utilities private void UpdateNoEnd(string message) { Console.CursorLeft = 0; - Logger.Write("["); + PluginManager.Logger.Write("["); for (var i = 1; i <= position; i++) - Logger.Write(" "); - Logger.Write("<==()==>"); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - Logger.Write(" "); - Logger.Write("] " + message); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write("] " + message); if (position == BarLength - 1 || position == 1) @@ -318,14 +320,14 @@ public static class Utilities private void UpdateNoEnd() { Console.CursorLeft = 0; - Logger.Write("["); + PluginManager.Logger.Write("["); for (var i = 1; i <= position; i++) - Logger.Write(" "); - Logger.Write("<==()==>"); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - Logger.Write(" "); - Logger.Write("]"); + PluginManager.Logger.Write(" "); + PluginManager.Logger.Write("]"); if (position == BarLength - 1 || position == 1) @@ -335,9 +337,9 @@ public static class Utilities private void UpdateNormal(float progress) { Console.CursorLeft = 0; - Logger.Write("["); + PluginManager.Logger.Write("["); Console.CursorLeft = BarLength; - Logger.Write("]"); + PluginManager.Logger.Write("]"); Console.CursorLeft = 1; var onechunk = 30.0f / Max; @@ -347,22 +349,22 @@ public static class Utilities { Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.CursorLeft = position++; - Logger.Write("#"); + PluginManager.Logger.Write("#"); } for (var i = position; i < BarLength; i++) { Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.CursorLeft = position++; - Logger.Write(" "); + PluginManager.Logger.Write(" "); } Console.CursorLeft = BarLength + 4; Console.BackgroundColor = ConsoleColor.Black; if (progress.CanAproximateTo(Max)) - Logger.Write(progress + " % ✓"); + PluginManager.Logger.Write(progress + " % ✓"); else - Logger.Write(MathF.Round(progress, 2) + " % "); + PluginManager.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 33d538c..d3401dc 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; @@ -7,11 +6,6 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Discord.WebSocket; - -using PluginManager.Items; - - namespace PluginManager.Others; /// diff --git a/PluginManager/Others/Logger/DBLogger.cs b/PluginManager/Others/Logger/DBLogger.cs new file mode 100644 index 0000000..10ca6f6 --- /dev/null +++ b/PluginManager/Others/Logger/DBLogger.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PluginManager.Others.Logger +{ + public class DBLogger + { + + private List LogHistory = new List(); + private List ErrorHistory = new List(); + + public IReadOnlyList Logs => LogHistory; + public IReadOnlyList Errors => ErrorHistory; + + public delegate void LogHandler(string message, TextType logType); + public event LogHandler LogEvent; + + private string _logFolder; + private string _errFolder; + + public DBLogger() + { + _logFolder = Config.Data["LogFolder"]; + _errFolder = Config.Data["ErrorFolder"]; + } + + public void Log(string message, string sender = "unknown", TextType type = TextType.NORMAL) => Log(new LogMessage(message, type, sender)); + + public void Log(LogMessage message) + { + if(LogEvent is not null) + LogEvent?.Invoke(message.Message, message.Type); + + if (message.Type != TextType.ERROR) + LogHistory.Add(message); + else + ErrorHistory.Add(message); + } + + public void Log(string message, object sender, TextType type = TextType.NORMAL) => Log(message, sender.GetType().Name, type); + + public async void SaveToFile() + { + await Functions.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", LogHistory); + await Functions.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", ErrorHistory); + } + } +} diff --git a/PluginManager/Others/Logger/LogMessage.cs b/PluginManager/Others/Logger/LogMessage.cs new file mode 100644 index 0000000..6976506 --- /dev/null +++ b/PluginManager/Others/Logger/LogMessage.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PluginManager.Others.Logger +{ + public class LogMessage + { + public string Message { get; set; } + public TextType Type { get; set; } + public string Time { get; set; } + public string Sender { get; set; } + public LogMessage(string message, TextType type) + { + Message = message; + Type = type; + Time = DateTime.Now.ToString("HH:mm:ss"); + } + + public LogMessage(string message, TextType type, string sender) : this(message, type) + { + Sender = sender; + } + + public override string ToString() + { + return $"[{Time}] {Message}"; + } + + public static explicit operator LogMessage(string message) + { + return new LogMessage(message, TextType.NORMAL); + } + + public static explicit operator LogMessage((string message, TextType type) tuple) + { + return new LogMessage(tuple.message, tuple.type); + } + + public static explicit operator LogMessage((string message, TextType type, string sender) tuple) + { + return new LogMessage(tuple.message, tuple.type, tuple.sender); + } + } +} diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj index 42446cf..bfa82b3 100644 --- a/PluginManager/PluginManager.csproj +++ b/PluginManager/PluginManager.csproj @@ -15,4 +15,7 @@ + + + \ No newline at end of file