diff --git a/DiscordBot/Bot/Actions/Clear.cs b/DiscordBot/Bot/Actions/Clear.cs index 3be31da..1569452 100644 --- a/DiscordBot/Bot/Actions/Clear.cs +++ b/DiscordBot/Bot/Actions/Clear.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using PluginManager.Interfaces; -using PluginManager.Others; -using PluginManager.Others.Actions; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; namespace DiscordBot.Bot.Actions; diff --git a/DiscordBot/Bot/Actions/Exit.cs b/DiscordBot/Bot/Actions/Exit.cs index 612ec7f..4451e75 100644 --- a/DiscordBot/Bot/Actions/Exit.cs +++ b/DiscordBot/Bot/Actions/Exit.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using PluginManager; -using PluginManager.Interfaces; -using PluginManager.Others; -using PluginManager.Others.Actions; +using DiscordBotCore; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; namespace DiscordBot.Bot.Actions; @@ -24,8 +24,8 @@ public class Exit: ICommandAction { if (args is null || args.Length == 0) { - Config.Logger.Log("Exiting...", typeof(ICommandAction), LogType.WARNING); - await Config.AppSettings.SaveToFile(); + Application.CurrentApplication.Logger.Log("Exiting...", typeof(ICommandAction), LogType.WARNING); + await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile(); Environment.Exit(0); } else @@ -40,7 +40,7 @@ public class Exit: ICommandAction case "-f": case "force": - Config.Logger.Log("Exiting (FORCE)...", typeof(ICommandAction), LogType.WARNING); + Application.CurrentApplication.Logger.Log("Exiting (FORCE)...", typeof(ICommandAction), LogType.WARNING); Environment.Exit(0); break; diff --git a/DiscordBot/Bot/Actions/Extra/PluginMethods.cs b/DiscordBot/Bot/Actions/Extra/PluginMethods.cs index 1e71bf2..1dbb084 100644 --- a/DiscordBot/Bot/Actions/Extra/PluginMethods.cs +++ b/DiscordBot/Bot/Actions/Extra/PluginMethods.cs @@ -6,11 +6,12 @@ using System.Threading.Tasks; using DiscordBot.Utilities; -using PluginManager; -using PluginManager.Interfaces; -using PluginManager.Loaders; -using PluginManager.Online; -using PluginManager.Others; +using DiscordBotCore; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Loaders; +using DiscordBotCore.Online; +using DiscordBotCore.Others; +using DiscordBotCore.Plugin; using Spectre.Console; @@ -18,7 +19,7 @@ namespace DiscordBot.Bot.Actions.Extra; internal static class PluginMethods { - internal static async Task List(PluginsManager manager) + internal static async Task List(PluginManager manager) { var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetPluginsList(), "Reading remote database"); @@ -38,11 +39,11 @@ internal static class PluginMethods internal static async Task RefreshPlugins(bool quiet) { - await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty); - await Program.internalActionManager.Refresh(); + await Application.CurrentApplication.InternalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty); + await Application.CurrentApplication.InternalActionManager.Refresh(); } - internal static async Task DownloadPlugin(PluginsManager manager, string pluginName) + internal static async Task DownloadPlugin(PluginManager manager, string pluginName) { var pluginData = await manager.GetPluginDataByName(pluginName); if (pluginData is null) @@ -66,7 +67,7 @@ internal static class PluginMethods IProgress progress = new Progress(p => { downloadTask.Value = p; }); - await ServerCom.DownloadFileAsync(pluginLink, $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll", progress); + await ServerCom.DownloadFileAsync(pluginLink, $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll", progress); downloadTask.Increment(100); @@ -76,7 +77,7 @@ internal static class PluginMethods if (!pluginData.HasDependencies) { - await manager.AppendPluginToDatabase(new PluginManager.Plugin.PluginInfo(pluginName, pluginData.Version, [])); + await manager.AppendPluginToDatabase(new PluginInfo(pluginName, pluginData.Version, [])); Console.WriteLine("Finished installing " + pluginName + " successfully"); await RefreshPlugins(false); return; @@ -108,8 +109,8 @@ internal static class PluginMethods int maxParallelDownloads = 5; - if (Config.AppSettings.ContainsKey("MaxParallelDownloads")) - maxParallelDownloads = int.Parse(Config.AppSettings["MaxParallelDownloads"]); + if (Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("MaxParallelDownloads")) + maxParallelDownloads = int.Parse(Application.CurrentApplication.ApplicationEnvironmentVariables["MaxParallelDownloads"]); var options = new ParallelOptions() { @@ -129,13 +130,13 @@ internal static class PluginMethods } ); - await manager.AppendPluginToDatabase(new PluginManager.Plugin.PluginInfo(pluginName, pluginData.Version, pluginData.Dependencies.Select(sep => sep.DownloadLocation).ToList())); + await manager.AppendPluginToDatabase(new PluginInfo(pluginName, pluginData.Version, pluginData.Dependencies.Select(sep => sep.DownloadLocation).ToList())); await RefreshPlugins(false); } internal static async Task LoadPlugins(string[] args) { - var loader = new PluginLoader(Config.DiscordBot.Client); + var loader = new PluginLoader(Application.CurrentApplication.DiscordBotClient.Client); if (args.Length == 2 && args[1] == "-q") { await loader.LoadPlugins(); @@ -147,14 +148,14 @@ internal static class PluginMethods { if (data.IsSuccess) { - Config.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction), + Application.CurrentApplication.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction), LogType.INFO ); } else { - Config.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage, + Application.CurrentApplication.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage, typeof(ICommandAction), LogType.ERROR ); } @@ -165,13 +166,13 @@ internal static class PluginMethods { if (data.IsSuccess) { - Config.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction), + Application.CurrentApplication.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction), LogType.INFO ); } else { - Config.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage, + Application.CurrentApplication.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage, typeof(ICommandAction), LogType.ERROR ); } @@ -183,13 +184,13 @@ internal static class PluginMethods { if (data.IsSuccess) { - Config.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction), + Application.CurrentApplication.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction), LogType.INFO ); } else { - Config.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage, + Application.CurrentApplication.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage, typeof(ICommandAction), LogType.ERROR ); } diff --git a/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs b/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs index 9d78f7b..3d34fe2 100644 --- a/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs +++ b/DiscordBot/Bot/Actions/Extra/SettingsConfigExtra.cs @@ -1,6 +1,5 @@ using System.Linq; -using PluginManager; -using PluginManager.Loaders; +using DiscordBotCore; namespace DiscordBot.Bot.Actions.Extra; @@ -13,21 +12,21 @@ internal static class SettingsConfigExtra if (value is null) return; - if (!Config.AppSettings.ContainsKey(key)) + if (!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey(key)) return; - Config.AppSettings[key] = string.Join(' ', value); - // Config.AppSettings.SaveToFile().Wait(); + Application.CurrentApplication.ApplicationEnvironmentVariables[key] = string.Join(' ', value); + // Config.Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile().Wait(); } internal static void RemoveSettings(string key) { if (key is null) return; - if (!Config.AppSettings.ContainsKey(key)) + if (!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey(key)) return; - Config.AppSettings.Remove(key); + Application.CurrentApplication.ApplicationEnvironmentVariables.Remove(key); } internal static void AddSettings(string key, params string[] value) @@ -36,10 +35,10 @@ internal static class SettingsConfigExtra if (value is null) return; - if (Config.AppSettings.ContainsKey(key)) + if (Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey(key)) return; - Config.AppSettings.Add(key, string.Join(' ', value)); - // Config.AppSettings.SaveToFile().Wait(); + Application.CurrentApplication.ApplicationEnvironmentVariables.Add(key, string.Join(' ', value)); + // Config.Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile().Wait(); } } diff --git a/DiscordBot/Bot/Actions/Help.cs b/DiscordBot/Bot/Actions/Help.cs index 1378b62..7af945f 100644 --- a/DiscordBot/Bot/Actions/Help.cs +++ b/DiscordBot/Bot/Actions/Help.cs @@ -3,9 +3,11 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DiscordBot.Utilities; -using PluginManager.Interfaces; -using PluginManager.Others; -using PluginManager.Others.Actions; + +using DiscordBotCore; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; using Spectre.Console; namespace DiscordBot.Bot.Actions; @@ -30,7 +32,7 @@ public class Help: ICommandAction tableData.Columns = ["Command", "Usage", "Description", "Options"]; - foreach (var a in Program.internalActionManager.Actions) + foreach (var a in Application.CurrentApplication.InternalActionManager.Actions) { Markup actionName = new Markup($"[bold]{a.Key}[/]"); Markup usage = new Markup($"[italic]{a.Value.Usage}[/]"); @@ -68,13 +70,13 @@ public class Help: ICommandAction return; } - if (!Program.internalActionManager.Actions.ContainsKey(args[0])) + if (!Application.CurrentApplication.InternalActionManager.Actions.ContainsKey(args[0])) { Console.WriteLine("Command not found"); return; } - var action = Program.internalActionManager.Actions[args[0]]; + var action = Application.CurrentApplication.InternalActionManager.Actions[args[0]]; tableData.Columns = ["Command", "Usage", "Description"]; tableData.AddRow([action.ActionName, action.Usage, action.Description]); diff --git a/DiscordBot/Bot/Actions/Plugin.cs b/DiscordBot/Bot/Actions/Plugin.cs index be753cf..85deb78 100644 --- a/DiscordBot/Bot/Actions/Plugin.cs +++ b/DiscordBot/Bot/Actions/Plugin.cs @@ -2,10 +2,10 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using DiscordBot.Bot.Actions.Extra; -using PluginManager; -using PluginManager.Interfaces; -using PluginManager.Others; -using PluginManager.Others.Actions; +using DiscordBotCore; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; namespace DiscordBot.Bot.Actions; @@ -50,24 +50,24 @@ public class Plugin: ICommandAction case "uninstall": string plugName = string.Join(' ', args, 1, args.Length-1); - bool result = await Config.PluginsManager.MarkPluginToUninstall(plugName); + bool result = await Application.CurrentApplication.PluginManager.MarkPluginToUninstall(plugName); if(result) Console.WriteLine($"Marked to uninstall plugin {plugName}. Please restart the bot"); break; case "list": - await PluginMethods.List(Config.PluginsManager); + await PluginMethods.List(Application.CurrentApplication.PluginManager); break; case "load": if (pluginsLoaded) { - Config.Logger.Log("Plugins already loaded", typeof(ICommandAction), LogType.WARNING); + Application.CurrentApplication.Logger.Log("Plugins already loaded", typeof(ICommandAction), LogType.WARNING); break; } - if (Config.DiscordBot is null) + if (Application.CurrentApplication.DiscordBotClient is null) { - Config.Logger.Log("DiscordBot is null", typeof(ICommandAction), LogType.WARNING); + Application.CurrentApplication.Logger.Log("DiscordBot is null", typeof(ICommandAction), LogType.WARNING); break; } @@ -88,7 +88,7 @@ public class Plugin: ICommandAction } } - await PluginMethods.DownloadPlugin(Config.PluginsManager, pluginName); + await PluginMethods.DownloadPlugin(Application.CurrentApplication.PluginManager, pluginName); break; } } diff --git a/DiscordBot/Bot/Actions/SettingsConfig.cs b/DiscordBot/Bot/Actions/SettingsConfig.cs index 54389de..d45ea73 100644 --- a/DiscordBot/Bot/Actions/SettingsConfig.cs +++ b/DiscordBot/Bot/Actions/SettingsConfig.cs @@ -2,10 +2,10 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using DiscordBot.Bot.Actions.Extra; -using PluginManager; -using PluginManager.Interfaces; -using PluginManager.Others; -using PluginManager.Others.Actions; +using DiscordBotCore; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; namespace DiscordBot.Bot.Actions; @@ -26,7 +26,7 @@ public class SettingsConfig: ICommandAction { if (args is null) { - foreach (var settings in Config.AppSettings) + foreach (var settings in Application.CurrentApplication.ApplicationEnvironmentVariables) Console.WriteLine(settings.Key + ": " + settings.Value); return Task.CompletedTask; diff --git a/DiscordBot/Bot/Commands/NormalCommands/Help.cs b/DiscordBot/Bot/Commands/NormalCommands/Help.cs index c45d2a0..02750d0 100644 --- a/DiscordBot/Bot/Commands/NormalCommands/Help.cs +++ b/DiscordBot/Bot/Commands/NormalCommands/Help.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using Discord; -using PluginManager; -using PluginManager.Interfaces; -using PluginManager.Loaders; -using PluginManager.Others; +using DiscordBotCore; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Loaders; +using DiscordBotCore.Others; namespace DiscordBot.Bot.Commands; @@ -79,7 +79,7 @@ internal class Help: DBCommand ); if (cmd == null) return null; - embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); + embedBuilder.AddField("Usage", Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"] + cmd.Usage); embedBuilder.AddField("Description", cmd.Description); if (cmd.Aliases is null) return embedBuilder; diff --git a/DiscordBot/Bot/Commands/SlashCommands/Help.cs b/DiscordBot/Bot/Commands/SlashCommands/Help.cs index b36a443..0d741a3 100644 --- a/DiscordBot/Bot/Commands/SlashCommands/Help.cs +++ b/DiscordBot/Bot/Commands/SlashCommands/Help.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using Discord; using Discord.WebSocket; -using PluginManager.Interfaces; -using PluginManager.Loaders; -using PluginManager.Others; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Loaders; +using DiscordBotCore.Others; namespace DiscordBot.Bot.Commands.SlashCommands; diff --git a/DiscordBot/DiscordBot.csproj b/DiscordBot/DiscordBot.csproj index 699f4f9..3dc9b30 100644 --- a/DiscordBot/DiscordBot.csproj +++ b/DiscordBot/DiscordBot.csproj @@ -7,15 +7,15 @@ False True - 1.0.2.0 + 1.0.4.0 False - 1.0.2.0 + 1.0.4.0 - none + full - none + full @@ -38,6 +38,6 @@ - + \ No newline at end of file diff --git a/DiscordBot/Installer.cs b/DiscordBot/Installer.cs index d38381e..a24bbc4 100644 --- a/DiscordBot/Installer.cs +++ b/DiscordBot/Installer.cs @@ -1,5 +1,5 @@ using System; -using PluginManager; +using DiscordBotCore; using System.Threading.Tasks; using Spectre.Console; @@ -18,22 +18,22 @@ public static class Installer Environment.Exit(-20); } - Config.AppSettings.Add(key, value); + Application.CurrentApplication.ApplicationEnvironmentVariables.Add(key, value); } public static async Task GenerateStartupConfig() { - if(!Config.AppSettings.ContainsKey("token")) + if(!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("token")) await AskForConfig("token", "Token:"); - if(!Config.AppSettings.ContainsKey("prefix")) + if(!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("prefix")) await AskForConfig("prefix", "Prefix:"); - if(!Config.AppSettings.ContainsKey("ServerID")) + if(!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("ServerID")) await AskForConfig("ServerID", "Server ID:"); - await Config.AppSettings.SaveToFile(); + await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile(); - Config.Logger.Log("Config Saved", typeof(Installer)); + Application.CurrentApplication.Logger.Log("Config Saved", typeof(Installer)); } } diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index 2a08d0c..c7924a6 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -3,19 +3,19 @@ using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; -using DiscordBot.Utilities; -using PluginManager.Bot; -using PluginManager.Others; -using PluginManager.Others.Actions; + +using DiscordBotCore; +using DiscordBotCore.Bot; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; +using DiscordBotCore.Updater.Application; + using Spectre.Console; -using static PluginManager.Config; namespace DiscordBot; public class Program { - public static InternalActionManager internalActionManager; - /// /// The main entry point for the application. /// @@ -23,9 +23,14 @@ public class Program { PreLoadComponents(args).Wait(); - if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix")) + if (!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("ServerID") || + !Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("token") || + !Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("prefix") + ) Installer.GenerateStartupConfig().Wait(); + + HandleInput().Wait(); } @@ -34,9 +39,7 @@ public class Program /// private static void NoGUI() { - internalActionManager.Initialize().Wait(); - internalActionManager.Execute("plugin", "load").Wait(); - internalActionManager.Refresh().Wait(); + Application.CurrentApplication.InternalActionManager.Execute("plugin", "load").Wait(); while (true) { @@ -47,7 +50,7 @@ public class Program if (args.Length == 0) args = null; - internalActionManager.Execute(command, args).Wait(); // Execute the command + Application.CurrentApplication.InternalActionManager.Execute(command, args).Wait(); } } @@ -58,7 +61,7 @@ public class Program private static async Task StartNoGui() { - AnsiConsole.MarkupLine($"[yellow]Running on version: {AppSettings["Version"]}[/]"); + AnsiConsole.MarkupLine($"[yellow]Running on version: {Application.CurrentApplication.ApplicationEnvironmentVariables["Version"]}[/]"); AnsiConsole.MarkupLine("[yellow]Git SethBot: https://github.com/andreitdr/SethDiscordBot [/]"); AnsiConsole.MarkupLine("[yellow]Git Plugins: https://github.com/andreitdr/SethPlugins [/]"); @@ -69,14 +72,14 @@ public class Program try { - var token = AppSettings["token"]; - var prefix = AppSettings["prefix"]; + var token = Application.CurrentApplication.ApplicationEnvironmentVariables["token"]; + var prefix = Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"]; var discordbooter = new Boot(token, prefix); await discordbooter.Awake(); } catch (Exception ex) { - Logger.Log(ex.ToString(), typeof(Program), LogType.CRITICAL); + Application.CurrentApplication.Logger.Log(ex.ToString(), typeof(Program), LogType.CRITICAL); } } @@ -88,14 +91,13 @@ public class Program await StartNoGui(); try { - internalActionManager = new InternalActionManager(AppSettings["PluginFolder"], "*.dll"); NoGUI(); } catch (IOException ex) { if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) { - Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" + + Application.CurrentApplication.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 !", typeof(Program), LogType.ERROR ); @@ -105,14 +107,14 @@ public class Program private static async Task PreLoadComponents(string[] args) { - await Initialize(); + await Application.CreateApplication(); - AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + Application.CurrentApplication.ApplicationEnvironmentVariables["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); - PluginManager.Updater.Application.AppUpdater updater = new(); + AppUpdater updater = new(); var update = await updater.CheckForUpdates(); - if (update != PluginManager.Updater.Application.Update.None) + if (update != Update.None) { Console.WriteLine($"New update available: {update.UpdateVersion}"); Console.WriteLine($"Download link: {update.UpdateUrl}"); @@ -122,15 +124,16 @@ public class Program await Task.Delay(5000); } - Logger.OnLog += (sender, logMessage) => + Application.CurrentApplication.Logger.OnFormattedLog += async (sender, logMessage) => { + await File.AppendAllTextAsync(Application.CurrentApplication.LogFile, logMessage.Message + "\n"); var messageColor = logMessage.Type switch { - LogType.INFO => "[green]", - LogType.WARNING => "[yellow]", - LogType.ERROR => "[red]", + LogType.INFO => "[green]", + LogType.WARNING => "[yellow]", + LogType.ERROR => "[red]", LogType.CRITICAL => "[red]", - _ => "[white]" + _ => "[white]" }; if (logMessage.Message.Contains('[')) @@ -139,7 +142,8 @@ public class Program return; } - AnsiConsole.MarkupLine($"{messageColor}{logMessage.ThrowTime} {logMessage.Message} [/]"); + string messageToPrint = $"{messageColor}{logMessage.Message}[/]"; + AnsiConsole.MarkupLine(messageToPrint); }; } } diff --git a/DiscordBot/Utilities/TableData.cs b/DiscordBot/Utilities/TableData.cs index 27b1e34..7006f72 100644 --- a/DiscordBot/Utilities/TableData.cs +++ b/DiscordBot/Utilities/TableData.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Text; using System.Threading.Tasks; -using PluginManager.Others; +using DiscordBotCore.Others; using Spectre.Console; using Spectre.Console.Rendering; diff --git a/DiscordBotCore/Application.cs b/DiscordBotCore/Application.cs new file mode 100644 index 0000000..aece082 --- /dev/null +++ b/DiscordBotCore/Application.cs @@ -0,0 +1,99 @@ +using DiscordBotCore.Online; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; +using DiscordBotCore.Others.Logger; +using DiscordBotCore.Plugin; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; + + +namespace DiscordBotCore +{ + public class Application + { + public static Application CurrentApplication { get; private set; } = null; + + private static readonly string _DefaultLogMessageFormat = "{SenderName} {Message}"; + private static readonly string _ConfigFile = "./Data/Resources/config.json"; + private static readonly string _PluginsDatabaseFile = "./Data/Resources/plugins.json"; + + private static readonly string _ResourcesFolder = "./Data/Resources"; + private static readonly string _PluginsFolder = "./Data/Plugins"; + private static readonly string _ArchivesFolder = "./Data/Archives"; + private static readonly string _LogsFolder = "./Data/Logs"; + + private static readonly string _MaxParallelDownloads = "3"; + + public string ServerID => ApplicationEnvironmentVariables["ServerID"]; + public string PluginDatabase => ApplicationEnvironmentVariables["PluginDatabase"]; + public string LogFile => $"{ApplicationEnvironmentVariables["LogFolder"]}/{DateTime.Now.ToLongDateString().Replace(" / ", "")}.log"; + + + public SettingsDictionary ApplicationEnvironmentVariables { get; private set; } + public InternalActionManager InternalActionManager { get; private set; } + public PluginManager PluginManager { get; private set; } + public Logger Logger { get; private set; } + public Bot.Boot DiscordBotClient { get; internal set; } + + public static async Task CreateApplication() + { + if (CurrentApplication is not null) + return; + + CurrentApplication = new Application(); + + Directory.CreateDirectory(_ResourcesFolder); + Directory.CreateDirectory(_PluginsFolder); + Directory.CreateDirectory(_ArchivesFolder); + Directory.CreateDirectory(_LogsFolder); + + CurrentApplication.ApplicationEnvironmentVariables = new SettingsDictionary(_ConfigFile); + bool result = await CurrentApplication.ApplicationEnvironmentVariables.LoadFromFile(); + if(!result) + { + PopulateEnvWithDefault(); + File.Delete(_ConfigFile); + await CurrentApplication.ApplicationEnvironmentVariables.SaveToFile(); + } + + CurrentApplication.Logger = CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("LogMessageFormat") ? + new Logger(CurrentApplication.ApplicationEnvironmentVariables["LogMessageFormat"]) : + new Logger(_DefaultLogMessageFormat); + + if (!File.Exists(_PluginsDatabaseFile)) + { + List plugins = new(); + await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins); + } + + CurrentApplication.PluginManager = new PluginManager(); + await CurrentApplication.PluginManager.UninstallMarkedPlugins(); + await CurrentApplication.PluginManager.CheckForUpdates(); + + CurrentApplication.InternalActionManager = new InternalActionManager(CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"], "*.dll"); + await CurrentApplication.InternalActionManager.Initialize(); + } + + + private static void PopulateEnvWithDefault() + { + if (CurrentApplication is null) + return; + + if (CurrentApplication.ApplicationEnvironmentVariables is null) + return; + + + CurrentApplication.ApplicationEnvironmentVariables["LogFolder"] = _LogsFolder; + CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"] = _PluginsFolder; + CurrentApplication.ApplicationEnvironmentVariables["ArchiveFolder"] = _ArchivesFolder; + CurrentApplication.ApplicationEnvironmentVariables["PluginDatabase"] = _PluginsDatabaseFile; + CurrentApplication.ApplicationEnvironmentVariables["LogMessageFormat"] = _DefaultLogMessageFormat; + CurrentApplication.ApplicationEnvironmentVariables["MaxParallelDownloads"] = _MaxParallelDownloads; + } + + } +} diff --git a/PluginManager/Bot/Boot.cs b/DiscordBotCore/Bot/Boot.cs similarity index 80% rename from PluginManager/Bot/Boot.cs rename to DiscordBotCore/Bot/Boot.cs index 6e749c9..db1d074 100644 --- a/PluginManager/Bot/Boot.cs +++ b/DiscordBotCore/Bot/Boot.cs @@ -3,10 +3,10 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using PluginManager.Others; +using DiscordBotCore.Others; -namespace PluginManager.Bot; +namespace DiscordBotCore.Bot; public class Boot { @@ -86,7 +86,7 @@ public class Boot await _commandServiceHandler.InstallCommandsAsync(); - Config.DiscordBotClient = this; + Application.CurrentApplication.DiscordBotClient = this; while (!IsReady) ; } @@ -106,16 +106,16 @@ public class Boot { if (arg.Message.Contains("401")) { - Config.AppSettings.Remove("token"); - Config.Logger.Log("The token is invalid. Please restart the bot and follow the instructions", typeof(Boot), LogType.CRITICAL); - await Config.AppSettings.SaveToFile(); + Application.CurrentApplication.ApplicationEnvironmentVariables.Remove("token"); + Application.CurrentApplication.Logger.Log("The token is invalid. Please restart the bot and follow the instructions", typeof(Boot), LogType.CRITICAL); + await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile(); Environment.Exit(0); } } private async Task Client_LoggedOut() { - Config.Logger.Log("Successfully Logged Out", typeof(Boot)); + Application.CurrentApplication.Logger.Log("Successfully Logged Out", typeof(Boot)); await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); } @@ -127,7 +127,7 @@ public class Boot private Task LoggedIn() { - Config.Logger.Log("Successfully Logged In", typeof(Boot)); + Application.CurrentApplication.Logger.Log("Successfully Logged In", typeof(Boot)); return Task.CompletedTask; } @@ -137,12 +137,12 @@ public class Boot { case LogSeverity.Error: case LogSeverity.Critical: - Config.Logger.Log(message.Message, typeof(Boot), LogType.ERROR); + Application.CurrentApplication.Logger.Log(message.Message, typeof(Boot), LogType.ERROR); break; case LogSeverity.Info: case LogSeverity.Debug: - Config.Logger.Log(message.Message, typeof(Boot), LogType.INFO); + Application.CurrentApplication.Logger.Log(message.Message, typeof(Boot), LogType.INFO); break; diff --git a/PluginManager/Bot/CommandHandler.cs b/DiscordBotCore/Bot/CommandHandler.cs similarity index 93% rename from PluginManager/Bot/CommandHandler.cs rename to DiscordBotCore/Bot/CommandHandler.cs index 1789a80..6b95827 100644 --- a/PluginManager/Bot/CommandHandler.cs +++ b/DiscordBotCore/Bot/CommandHandler.cs @@ -4,13 +4,12 @@ using System.Reflection; using System.Threading.Tasks; using Discord.Commands; using Discord.WebSocket; -using PluginManager.Interfaces; -using PluginManager.Loaders; -using PluginManager.Online; -using PluginManager.Others; -using PluginManager.Others.Permissions; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Loaders; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Permissions; -namespace PluginManager.Bot; +namespace DiscordBotCore.Bot; internal class CommandHandler { @@ -57,7 +56,7 @@ internal class CommandHandler } catch (Exception ex) { - Config.Logger.Log(ex.Message, type: LogType.ERROR, source: typeof(CommandHandler)); + Application.CurrentApplication.Logger.LogException(ex, this); } return Task.CompletedTask; @@ -141,7 +140,7 @@ internal class CommandHandler DbCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean); - Config.Logger.Log( + Application.CurrentApplication.Logger.Log( $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"", typeof(CommandHandler), LogType.INFO @@ -153,7 +152,7 @@ internal class CommandHandler } catch (Exception ex) { - Config.Logger.Log(ex.Message, type: LogType.ERROR, source: typeof(CommandHandler)); + Application.CurrentApplication.Logger.LogException(ex, this); } } } diff --git a/PluginManager/Database/SqlDatabase.cs b/DiscordBotCore/Database/SqlDatabase.cs similarity index 99% rename from PluginManager/Database/SqlDatabase.cs rename to DiscordBotCore/Database/SqlDatabase.cs index 943e04f..9fe8865 100644 --- a/PluginManager/Database/SqlDatabase.cs +++ b/DiscordBotCore/Database/SqlDatabase.cs @@ -5,7 +5,7 @@ using System.Data.SQLite; using System.IO; using System.Threading.Tasks; -namespace PluginManager.Database; +namespace DiscordBotCore.Database; public class SqlDatabase { diff --git a/PluginManager/PluginManager.csproj b/DiscordBotCore/DiscordBotCore.csproj similarity index 86% rename from PluginManager/PluginManager.csproj rename to DiscordBotCore/DiscordBotCore.csproj index 1f64b4c..a2ed1c3 100644 --- a/PluginManager/PluginManager.csproj +++ b/DiscordBotCore/DiscordBotCore.csproj @@ -5,9 +5,12 @@ 512 - none + portable false + + + diff --git a/PluginManager/Interfaces/DBCommand.cs b/DiscordBotCore/Interfaces/DBCommand.cs similarity index 95% rename from PluginManager/Interfaces/DBCommand.cs rename to DiscordBotCore/Interfaces/DBCommand.cs index e25fe15..1c5f1e5 100644 --- a/PluginManager/Interfaces/DBCommand.cs +++ b/DiscordBotCore/Interfaces/DBCommand.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; -using PluginManager.Others; +using DiscordBotCore.Others; -namespace PluginManager.Interfaces; +namespace DiscordBotCore.Interfaces; public interface DBCommand { diff --git a/PluginManager/Interfaces/DBEvent.cs b/DiscordBotCore/Interfaces/DBEvent.cs similarity index 92% rename from PluginManager/Interfaces/DBEvent.cs rename to DiscordBotCore/Interfaces/DBEvent.cs index 4c7e06a..80bb93e 100644 --- a/PluginManager/Interfaces/DBEvent.cs +++ b/DiscordBotCore/Interfaces/DBEvent.cs @@ -1,6 +1,6 @@ using Discord.WebSocket; -namespace PluginManager.Interfaces; +namespace DiscordBotCore.Interfaces; public interface DBEvent { diff --git a/PluginManager/Interfaces/DBSlashCommand.cs b/DiscordBotCore/Interfaces/DBSlashCommand.cs similarity index 93% rename from PluginManager/Interfaces/DBSlashCommand.cs rename to DiscordBotCore/Interfaces/DBSlashCommand.cs index 35b06ad..e8e0d3f 100644 --- a/PluginManager/Interfaces/DBSlashCommand.cs +++ b/DiscordBotCore/Interfaces/DBSlashCommand.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using Discord; using Discord.WebSocket; -namespace PluginManager.Interfaces; +namespace DiscordBotCore.Interfaces; public interface DBSlashCommand { diff --git a/PluginManager/Interfaces/ICommandAction.cs b/DiscordBotCore/Interfaces/ICommandAction.cs similarity index 79% rename from PluginManager/Interfaces/ICommandAction.cs rename to DiscordBotCore/Interfaces/ICommandAction.cs index 13cbf54..4709bfb 100644 --- a/PluginManager/Interfaces/ICommandAction.cs +++ b/DiscordBotCore/Interfaces/ICommandAction.cs @@ -1,10 +1,10 @@ using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; -using PluginManager.Others; -using PluginManager.Others.Actions; +using DiscordBotCore.Others; +using DiscordBotCore.Others.Actions; -namespace PluginManager.Interfaces; +namespace DiscordBotCore.Interfaces; public interface ICommandAction { diff --git a/DiscordBotCore/Interfaces/Logger/ILogMessage.cs b/DiscordBotCore/Interfaces/Logger/ILogMessage.cs new file mode 100644 index 0000000..1408939 --- /dev/null +++ b/DiscordBotCore/Interfaces/Logger/ILogMessage.cs @@ -0,0 +1,15 @@ +using DiscordBotCore.Others; + +using System; + +namespace DiscordBotCore.Interfaces.Logger +{ + public interface ILogMessage + { + public string Message { get; protected set; } + public DateTime ThrowTime { get; protected set; } + public string SenderName { get; protected set; } + public LogType LogMessageType { get; protected set; } + + } +} diff --git a/DiscordBotCore/Interfaces/Logger/ILogger.cs b/DiscordBotCore/Interfaces/Logger/ILogger.cs new file mode 100644 index 0000000..4df4e41 --- /dev/null +++ b/DiscordBotCore/Interfaces/Logger/ILogger.cs @@ -0,0 +1,19 @@ +using DiscordBotCore.Others; + +using System; +using System.Collections.Generic; + +namespace DiscordBotCore.Interfaces.Logger +{ + public interface ILogger + { + public struct FormattedMessage { public string Message; public LogType Type; } + public string LogMessageFormat { get; set; } + + public void Log(ILogMessage message); + public void LogException(Exception exception, object Sender); + + public event EventHandler OnFormattedLog; + public event EventHandler OnRawLog; + } +} diff --git a/PluginManager/Interfaces/Updater/AppVersion.cs b/DiscordBotCore/Interfaces/Updater/AppVersion.cs similarity index 92% rename from PluginManager/Interfaces/Updater/AppVersion.cs rename to DiscordBotCore/Interfaces/Updater/AppVersion.cs index e522071..68bd2f0 100644 --- a/PluginManager/Interfaces/Updater/AppVersion.cs +++ b/DiscordBotCore/Interfaces/Updater/AppVersion.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace PluginManager.Interfaces.Updater +namespace DiscordBotCore.Interfaces.Updater { public class AppVersion : IVersion { @@ -16,7 +12,7 @@ namespace PluginManager.Interfaces.Updater public int PatchVersion { get; set; } - public static readonly AppVersion CurrentAppVersion = new AppVersion(Config.AppSettings["Version"]); + public static readonly AppVersion CurrentAppVersion = new AppVersion(Application.CurrentApplication.ApplicationEnvironmentVariables["Version"]); private readonly char _Separator = '.'; diff --git a/PluginManager/Interfaces/Updater/IVersion.cs b/DiscordBotCore/Interfaces/Updater/IVersion.cs similarity index 88% rename from PluginManager/Interfaces/Updater/IVersion.cs rename to DiscordBotCore/Interfaces/Updater/IVersion.cs index 911ab98..275482c 100644 --- a/PluginManager/Interfaces/Updater/IVersion.cs +++ b/DiscordBotCore/Interfaces/Updater/IVersion.cs @@ -1,4 +1,4 @@ -namespace PluginManager.Interfaces.Updater; +namespace DiscordBotCore.Interfaces.Updater; public interface IVersion { diff --git a/PluginManager/Interfaces/Updater/Version.cs b/DiscordBotCore/Interfaces/Updater/Version.cs similarity index 97% rename from PluginManager/Interfaces/Updater/Version.cs rename to DiscordBotCore/Interfaces/Updater/Version.cs index 36bda8d..67c3f76 100644 --- a/PluginManager/Interfaces/Updater/Version.cs +++ b/DiscordBotCore/Interfaces/Updater/Version.cs @@ -1,6 +1,6 @@ using System; -namespace PluginManager.Interfaces.Updater; +namespace DiscordBotCore.Interfaces.Updater; public abstract class Version: IVersion { diff --git a/PluginManager/Loaders/ActionsLoader.cs b/DiscordBotCore/Loaders/ActionsLoader.cs similarity index 95% rename from PluginManager/Loaders/ActionsLoader.cs rename to DiscordBotCore/Loaders/ActionsLoader.cs index f6c4396..ffbf53c 100644 --- a/PluginManager/Loaders/ActionsLoader.cs +++ b/DiscordBotCore/Loaders/ActionsLoader.cs @@ -4,10 +4,10 @@ using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; -using PluginManager.Interfaces; -using PluginManager.Others; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; -namespace PluginManager.Loaders; +namespace DiscordBotCore.Loaders; public class ActionsLoader { diff --git a/PluginManager/Loaders/FileLoaderResult.cs b/DiscordBotCore/Loaders/FileLoaderResult.cs similarity index 92% rename from PluginManager/Loaders/FileLoaderResult.cs rename to DiscordBotCore/Loaders/FileLoaderResult.cs index 3036dba..0ad72fa 100644 --- a/PluginManager/Loaders/FileLoaderResult.cs +++ b/DiscordBotCore/Loaders/FileLoaderResult.cs @@ -1,4 +1,4 @@ -namespace PluginManager.Loaders; +namespace DiscordBotCore.Loaders; public class FileLoaderResult { diff --git a/PluginManager/Loaders/Loader.cs b/DiscordBotCore/Loaders/Loader.cs similarity index 96% rename from PluginManager/Loaders/Loader.cs rename to DiscordBotCore/Loaders/Loader.cs index 51e3f84..967e81c 100644 --- a/PluginManager/Loaders/Loader.cs +++ b/DiscordBotCore/Loaders/Loader.cs @@ -3,10 +3,10 @@ using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; -using PluginManager.Interfaces; -using PluginManager.Others; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; -namespace PluginManager.Loaders; +namespace DiscordBotCore.Loaders; internal class Loader { diff --git a/PluginManager/Loaders/PluginLoadResultData.cs b/DiscordBotCore/Loaders/PluginLoadResultData.cs similarity index 90% rename from PluginManager/Loaders/PluginLoadResultData.cs rename to DiscordBotCore/Loaders/PluginLoadResultData.cs index f9ac853..ba02086 100644 --- a/PluginManager/Loaders/PluginLoadResultData.cs +++ b/DiscordBotCore/Loaders/PluginLoadResultData.cs @@ -1,6 +1,6 @@ -using PluginManager.Others; +using DiscordBotCore.Others; -namespace PluginManager.Loaders; +namespace DiscordBotCore.Loaders; public class PluginLoadResultData { diff --git a/PluginManager/Loaders/PluginLoader.cs b/DiscordBotCore/Loaders/PluginLoader.cs similarity index 77% rename from PluginManager/Loaders/PluginLoader.cs rename to DiscordBotCore/Loaders/PluginLoader.cs index 692a820..a2dca4a 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/DiscordBotCore/Loaders/PluginLoader.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Threading.Tasks; using Discord.WebSocket; -using PluginManager.Interfaces; -using PluginManager.Others; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; -namespace PluginManager.Loaders; +namespace DiscordBotCore.Loaders; public class PluginLoader { @@ -32,9 +32,9 @@ public class PluginLoader public async Task LoadPlugins() { - Config.Logger.Log("Loading plugins...", typeof(PluginLoader)); + Application.CurrentApplication.Logger.Log("Loading plugins...", typeof(PluginLoader)); - var loader = new Loader(Config.AppSettings["PluginFolder"], "dll"); + var loader = new Loader(Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"], "dll"); //await this.ResetSlashCommands(); @@ -46,7 +46,7 @@ public class PluginLoader private void FileLoadedException(FileLoaderResult result) { - Config.Logger.Log(result.ErrorMessage, typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log(result.ErrorMessage, typeof(PluginLoader), LogType.ERROR); } private async void OnPluginLoaded(PluginLoadResultData result) @@ -74,11 +74,11 @@ public class PluginLoader OnSlashCommandLoaded?.Invoke(result); } else - Config.Logger.Log($"Failed to start slash command {result.PluginName}", typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log($"Failed to start slash command {result.PluginName}", typeof(PluginLoader), LogType.ERROR); break; case PluginType.UNKNOWN: default: - Config.Logger.Log("Unknown plugin type", typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log("Unknown plugin type", typeof(PluginLoader), LogType.ERROR); break; } } diff --git a/PluginManager/Loaders/PluginLoaderExtensions.cs b/DiscordBotCore/Loaders/PluginLoaderExtensions.cs similarity index 63% rename from PluginManager/Loaders/PluginLoaderExtensions.cs rename to DiscordBotCore/Loaders/PluginLoaderExtensions.cs index 2045040..55b5f93 100644 --- a/PluginManager/Loaders/PluginLoaderExtensions.cs +++ b/DiscordBotCore/Loaders/PluginLoaderExtensions.cs @@ -5,10 +5,10 @@ using System.Threading.Tasks; using Discord; using Discord.WebSocket; -using PluginManager.Interfaces; -using PluginManager.Others; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Others; -namespace PluginManager.Loaders; +namespace DiscordBotCore.Loaders; internal static class PluginLoaderExtensions { @@ -27,7 +27,7 @@ internal static class PluginLoaderExtensions } catch (Exception e) { - Config.Logger.Log($"Error starting event {dbEvent.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log($"Error starting event {dbEvent.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR); return false; } } @@ -37,22 +37,22 @@ internal static class PluginLoaderExtensions await pluginLoader._Client.Rest.DeleteAllGlobalCommandsAsync(); if(pluginLoader._Client.Guilds.Count == 0) return; - if (!ulong.TryParse(Config.ServerID, out _)) + if (!ulong.TryParse(Application.CurrentApplication.ServerID, out _)) { - Config.Logger.Log("Invalid ServerID in config file. Can not reset specific guild commands", typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log("Invalid ServerID in config file. Can not reset specific guild commands", typeof(PluginLoader), LogType.ERROR); return; } - SocketGuild? guild = pluginLoader._Client.GetGuild(ulong.Parse(Config.ServerID)); + SocketGuild? guild = pluginLoader._Client.GetGuild(ulong.Parse(Application.CurrentApplication.ServerID)); if(guild is null) { - Config.Logger.Log("Failed to get guild with ID " + Config.ServerID, typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log("Failed to get guild with ID " + Application.CurrentApplication.ServerID, typeof(PluginLoader), LogType.ERROR); return; } await guild.DeleteApplicationCommandsAsync(); - Config.Logger.Log($"Cleared all slash commands from guild {guild.Id}", typeof(PluginLoader)); + Application.CurrentApplication.Logger.Log($"Cleared all slash commands from guild {guild.Id}", typeof(PluginLoader)); } internal static async Task TryStartSlashCommand(this PluginLoader pluginLoader, DBSlashCommand? dbSlashCommand) @@ -74,12 +74,12 @@ internal static class PluginLoaderExtensions builder.WithDMPermission(dbSlashCommand.canUseDM); builder.Options = dbSlashCommand.Options; - if (uint.TryParse(Config.ServerID, out uint result)) + if (uint.TryParse(Application.CurrentApplication.ServerID, out uint result)) { SocketGuild? guild = pluginLoader._Client.GetGuild(result); if (guild is null) { - Config.Logger.Log("Failed to get guild with ID " + Config.ServerID, typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log("Failed to get guild with ID " + Application.CurrentApplication.ServerID, typeof(PluginLoader), LogType.ERROR); return false; } @@ -90,7 +90,7 @@ internal static class PluginLoaderExtensions } catch (Exception e) { - Config.Logger.Log($"Error starting slash command {dbSlashCommand.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR); + Application.CurrentApplication.Logger.Log($"Error starting slash command {dbSlashCommand.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR); return false; } } diff --git a/PluginManager/Online/Helpers/OnlineFunctions.cs b/DiscordBotCore/Online/Helpers/OnlineFunctions.cs similarity index 97% rename from PluginManager/Online/Helpers/OnlineFunctions.cs rename to DiscordBotCore/Online/Helpers/OnlineFunctions.cs index 0762d14..e13e134 100644 --- a/PluginManager/Online/Helpers/OnlineFunctions.cs +++ b/DiscordBotCore/Online/Helpers/OnlineFunctions.cs @@ -3,9 +3,9 @@ using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using PluginManager.Others; +using DiscordBotCore.Others; -namespace PluginManager.Online.Helpers; +namespace DiscordBotCore.Online.Helpers; internal static class OnlineFunctions { diff --git a/PluginManager/Online/Helpers/PluginVersion.cs b/DiscordBotCore/Online/Helpers/PluginVersion.cs similarity index 81% rename from PluginManager/Online/Helpers/PluginVersion.cs rename to DiscordBotCore/Online/Helpers/PluginVersion.cs index 10751cb..409bdf2 100644 --- a/PluginManager/Online/Helpers/PluginVersion.cs +++ b/DiscordBotCore/Online/Helpers/PluginVersion.cs @@ -1,7 +1,7 @@ using System.Text.Json.Serialization; -using PluginManager.Interfaces.Updater; +using DiscordBotCore.Interfaces.Updater; -namespace PluginManager.Online.Helpers; +namespace DiscordBotCore.Online.Helpers; public class PluginVersion: Version { diff --git a/PluginManager/Online/PluginsManager.cs b/DiscordBotCore/Online/PluginManager.cs similarity index 80% rename from PluginManager/Online/PluginsManager.cs rename to DiscordBotCore/Online/PluginManager.cs index faaacc7..1aa31c0 100644 --- a/PluginManager/Online/PluginsManager.cs +++ b/DiscordBotCore/Online/PluginManager.cs @@ -3,13 +3,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; -using PluginManager.Others; -using PluginManager.Plugin; -using PluginManager.Updater.Plugins; +using DiscordBotCore.Others; +using DiscordBotCore.Plugin; +using DiscordBotCore.Updater.Plugins; -namespace PluginManager.Online; +namespace DiscordBotCore.Online; -public class PluginsManager +public class PluginManager { private static readonly string _DefaultBranch = "releases"; private static readonly string _DefaultBaseUrl = "https://raw.githubusercontent.com/andreitdr/SethPlugins"; @@ -23,19 +23,19 @@ public class PluginsManager private string PluginsLink => $"{BaseUrl}/{Branch}/{_DefaultPluginsLink}"; - public PluginsManager(Uri baseUrl, string branch) + public PluginManager(Uri baseUrl, string branch) { BaseUrl = baseUrl.ToString(); Branch = branch; } - public PluginsManager(string branch) + public PluginManager(string branch) { BaseUrl = _DefaultBaseUrl; Branch = branch; } - public PluginsManager() + public PluginManager() { BaseUrl = _DefaultBaseUrl; Branch = _DefaultBranch; @@ -65,28 +65,28 @@ public class PluginsManager public async Task RemovePluginFromDatabase(string pluginName) { - List installedPlugins = await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Config.PluginDatabase)); + List installedPlugins = await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase)); installedPlugins.RemoveAll(p => p.PluginName == pluginName); - await JsonManager.SaveToJsonFile( Config.PluginDatabase,installedPlugins); + await JsonManager.SaveToJsonFile(Application.CurrentApplication.PluginDatabase,installedPlugins); } public async Task AppendPluginToDatabase(PluginInfo pluginData) { - List installedPlugins = await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Config.PluginDatabase)); + List installedPlugins = await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase)); installedPlugins.Add(pluginData); - await JsonManager.SaveToJsonFile( Config.PluginDatabase, installedPlugins); + await JsonManager.SaveToJsonFile(Application.CurrentApplication.PluginDatabase, installedPlugins); } public async Task> GetInstalledPlugins() { - return await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Config.PluginDatabase)); + return await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase)); } public async Task IsPluginInstalled(string pluginName) { - List installedPlugins = await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Config.PluginDatabase)); + List installedPlugins = await JsonManager.ConvertFromJson>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase)); return installedPlugins.Any(plugin => plugin.PluginName == pluginName); } @@ -101,7 +101,7 @@ public class PluginsManager { if (await pluginUpdater.HasUpdate(plugin.PluginName)) { - Config.Logger.Log("Updating plugin: " + plugin.PluginName, typeof(PluginsManager), LogType.INFO); + Application.CurrentApplication.Logger.Log("Updating plugin: " + plugin.PluginName, typeof(PluginManager), LogType.INFO); await pluginUpdater.UpdatePlugin(plugin.PluginName); } } @@ -158,7 +158,7 @@ public class PluginsManager installProgress?.Report(currentProgress + stepProgress * p); }); - await ServerCom.DownloadFileAsync(pluginData.DownLoadLink, $"{Config.AppSettings["PluginFolder"]}/{pluginData.Name}.dll", progress); + await ServerCom.DownloadFileAsync(pluginData.DownLoadLink, $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginData.Name}.dll", progress); foreach (var dependency in pluginData.Dependencies) { diff --git a/PluginManager/Online/ServerCom.cs b/DiscordBotCore/Online/ServerCom.cs similarity index 97% rename from PluginManager/Online/ServerCom.cs rename to DiscordBotCore/Online/ServerCom.cs index 98fe43e..eef3f81 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/DiscordBotCore/Online/ServerCom.cs @@ -4,9 +4,9 @@ using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; -using PluginManager.Online.Helpers; +using DiscordBotCore.Online.Helpers; -namespace PluginManager.Online; +namespace DiscordBotCore.Online; public static class ServerCom { diff --git a/PluginManager/Others/Actions/InternalActionOption.cs b/DiscordBotCore/Others/Actions/InternalActionOption.cs similarity index 68% rename from PluginManager/Others/Actions/InternalActionOption.cs rename to DiscordBotCore/Others/Actions/InternalActionOption.cs index fdc89b8..88c451b 100644 --- a/PluginManager/Others/Actions/InternalActionOption.cs +++ b/DiscordBotCore/Others/Actions/InternalActionOption.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace PluginManager.Others.Actions +namespace DiscordBotCore.Others.Actions { public class InternalActionOption { diff --git a/PluginManager/Others/Actions/InternalActionsManager.cs b/DiscordBotCore/Others/Actions/InternalActionsManager.cs similarity index 76% rename from PluginManager/Others/Actions/InternalActionsManager.cs rename to DiscordBotCore/Others/Actions/InternalActionsManager.cs index 19c3560..a599969 100644 --- a/PluginManager/Others/Actions/InternalActionsManager.cs +++ b/DiscordBotCore/Others/Actions/InternalActionsManager.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using PluginManager.Interfaces; -using PluginManager.Loaders; +using DiscordBotCore.Interfaces; +using DiscordBotCore.Loaders; -namespace PluginManager.Others.Actions; +namespace DiscordBotCore.Others.Actions; public class InternalActionManager { @@ -36,7 +36,7 @@ public class InternalActionManager { if (!Actions.ContainsKey(actionName)) { - Config.Logger.Log($"Action {actionName} not found", type: LogType.ERROR, source: typeof(InternalActionManager)); + Application.CurrentApplication.Logger.Log($"Action {actionName} not found", this, LogType.ERROR); return false; } @@ -47,7 +47,7 @@ public class InternalActionManager } catch (Exception e) { - Config.Logger.Log(e.Message, type: LogType.ERROR, source: typeof(InternalActionManager)); + Application.CurrentApplication.Logger.Log(e.Message, type: LogType.ERROR, Sender: this); return false; } } diff --git a/PluginManager/Others/ArchiveManager.cs b/DiscordBotCore/Others/ArchiveManager.cs similarity index 90% rename from PluginManager/Others/ArchiveManager.cs rename to DiscordBotCore/Others/ArchiveManager.cs index a74411c..24db751 100644 --- a/PluginManager/Others/ArchiveManager.cs +++ b/DiscordBotCore/Others/ArchiveManager.cs @@ -4,7 +4,7 @@ using System.IO.Compression; using System.Linq; using System.Threading.Tasks; -namespace PluginManager.Others; +namespace DiscordBotCore.Others; public static class ArchiveManager { @@ -33,7 +33,7 @@ public static class ArchiveManager public static async Task ReadStreamFromPakAsync(string fileName, string archName) { - archName = Config.AppSettings["ArchiveFolder"] + archName; + archName = Application.CurrentApplication.ApplicationEnvironmentVariables["ArchiveFolder"] + archName; if (!File.Exists(archName)) throw new Exception("Failed to load file !"); @@ -61,7 +61,7 @@ public static class ArchiveManager /// A string that represents the content of the file or null if the file does not exists or it has no content public static async Task ReadFromPakAsync(string fileName, string archFile) { - archFile = Config.AppSettings["ArchiveFolder"] + archFile; + archFile = Application.CurrentApplication.ApplicationEnvironmentVariables["ArchiveFolder"] + archFile; if (!File.Exists(archFile)) throw new Exception("Failed to load file !"); @@ -87,7 +87,7 @@ public static class ArchiveManager } catch (Exception ex) { - Config.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); // Write the error to a file + Application.CurrentApplication.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); // Write the error to a file await Task.Delay(100); return await ReadFromPakAsync(fileName, archFile); } @@ -123,7 +123,7 @@ public static class ArchiveManager } catch (Exception ex) { - Config.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); + Application.CurrentApplication.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); } currentZipFile++; @@ -155,7 +155,7 @@ public static class ArchiveManager } catch (Exception ex) { - Config.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); + Application.CurrentApplication.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); } await Task.Delay(10); diff --git a/PluginManager/Others/DBCommandExecutingArguments.cs b/DiscordBotCore/Others/DBCommandExecutingArguments.cs similarity index 90% rename from PluginManager/Others/DBCommandExecutingArguments.cs rename to DiscordBotCore/Others/DBCommandExecutingArguments.cs index 00914b7..4faf8e9 100644 --- a/PluginManager/Others/DBCommandExecutingArguments.cs +++ b/DiscordBotCore/Others/DBCommandExecutingArguments.cs @@ -2,7 +2,7 @@ using Discord.WebSocket; -namespace PluginManager.Others; +namespace DiscordBotCore.Others; public class DbCommandExecutingArguments { @@ -33,7 +33,7 @@ public class DbCommandExecutingArguments } else { - cleanContent = message.Content.Substring(Config.DiscordBot.BotPrefix.Length); + cleanContent = message.Content.Substring(Application.CurrentApplication.DiscordBotClient.BotPrefix.Length); } var split = cleanContent.Split(' '); diff --git a/PluginManager/Others/Enums.cs b/DiscordBotCore/Others/Enums.cs similarity index 94% rename from PluginManager/Others/Enums.cs rename to DiscordBotCore/Others/Enums.cs index 0ecc457..36b9d16 100644 --- a/PluginManager/Others/Enums.cs +++ b/DiscordBotCore/Others/Enums.cs @@ -1,6 +1,6 @@ using System; -namespace PluginManager.Others; +namespace DiscordBotCore.Others; /// /// The output log type diff --git a/PluginManager/Others/Functions.cs b/DiscordBotCore/Others/Functions.cs similarity index 96% rename from PluginManager/Others/Functions.cs rename to DiscordBotCore/Others/Functions.cs index 6ea23ae..4cc8172 100644 --- a/PluginManager/Others/Functions.cs +++ b/DiscordBotCore/Others/Functions.cs @@ -1,13 +1,10 @@ using System; using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Discord; -namespace PluginManager.Others; +namespace DiscordBotCore.Others; /// /// A special class with functions diff --git a/PluginManager/Others/JsonManager.cs b/DiscordBotCore/Others/JsonManager.cs similarity index 97% rename from PluginManager/Others/JsonManager.cs rename to DiscordBotCore/Others/JsonManager.cs index 20b8007..079914f 100644 --- a/PluginManager/Others/JsonManager.cs +++ b/DiscordBotCore/Others/JsonManager.cs @@ -4,7 +4,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -namespace PluginManager; +namespace DiscordBotCore.Others; public class JsonManager { diff --git a/DiscordBotCore/Others/Logger/LogMessage.cs b/DiscordBotCore/Others/Logger/LogMessage.cs new file mode 100644 index 0000000..92b069a --- /dev/null +++ b/DiscordBotCore/Others/Logger/LogMessage.cs @@ -0,0 +1,71 @@ +using DiscordBotCore.Interfaces.Logger; + +using System; + +namespace DiscordBotCore.Others.Logger +{ + internal sealed class LogMessage : ILogMessage + { + public string Message { get; set; } + public DateTime ThrowTime { get; set; } + public string SenderName { get; set; } + public LogType LogMessageType { get; set; } + + public LogMessage(string message, object sender) + { + Message = message; + SenderName = sender.GetType().FullName ?? sender.GetType().Name; + ThrowTime = DateTime.Now; + LogMessageType = LogType.INFO; + } + + public LogMessage(string message, object sender, DateTime throwTime) + { + Message = message; + SenderName = sender.GetType().FullName ?? sender.GetType().Name; + ThrowTime = throwTime; + LogMessageType = LogType.INFO; + } + + public LogMessage(string message, object sender, LogType logMessageType) + { + Message = message; + SenderName = sender.GetType().FullName ?? sender.GetType().Name; + ThrowTime = DateTime.Now; + LogMessageType = logMessageType; + + } + + public LogMessage(string message, DateTime throwTime, object sender, LogType logMessageType) + { + Message = message; + ThrowTime = throwTime; + SenderName = sender.GetType().FullName ?? sender.GetType().Name; + LogMessageType = logMessageType; + } + + public LogMessage WithMessage(string message) + { + this.Message = message; + return this; + } + + public LogMessage WithCurrentThrowTime() + { + this.ThrowTime = DateTime.Now; + return this; + } + + public LogMessage WithMessageType(LogType logType) + { + this.LogMessageType = logType; + return this; + } + + public static LogMessage CreateFromException(Exception exception, object Sender) + { + LogMessage message = new LogMessage(exception.Message, Sender, LogType.ERROR); + return message; + } + } +} diff --git a/DiscordBotCore/Others/Logger/Logger.cs b/DiscordBotCore/Others/Logger/Logger.cs new file mode 100644 index 0000000..7e0154e --- /dev/null +++ b/DiscordBotCore/Others/Logger/Logger.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +using DiscordBotCore.Interfaces.Logger; + +namespace DiscordBotCore.Others.Logger; + +public sealed class Logger : ILogger +{ + + public List LogMessageProperties = typeof(ILogMessage).GetProperties().Select(p => p.Name).ToList(); + public string LogMessageFormat { get ; set; } + + public event EventHandler OnFormattedLog; + public event EventHandler OnRawLog; + + public Logger(string logMessageFormat) + { + this.LogMessageFormat = logMessageFormat; + } + + /// + /// Generate a formatted string based on the default parameters of the ILogMessage and a string defined as model + /// + /// The message + /// A formatted string with the message values + private string GenerateLogMessage(ILogMessage message) + { + string messageAsString = new string(LogMessageFormat); + foreach (var prop in LogMessageProperties) + { + Type messageType = typeof(ILogMessage); + messageAsString = messageAsString.Replace("{" + prop + "}", messageType?.GetProperty(prop)?.GetValue(message)?.ToString()); + } + + return messageAsString; + } + + public void Log(ILogMessage message) + { + OnRawLog?.Invoke(this, message); + string messageAsString = GenerateLogMessage(message); + OnFormattedLog?.Invoke(this, new ILogger.FormattedMessage() { Message = messageAsString, Type = message.LogMessageType }) ; + } + + public void Log(string message, object Sender) => Log(new LogMessage(message, Sender)); + public void Log(string message, object Sender, LogType type) => Log(new LogMessage(message, Sender, type)); + public void LogException(Exception exception, object Sender) => Log(LogMessage.CreateFromException(exception, Sender)); + +} diff --git a/PluginManager/Others/OneOf.cs b/DiscordBotCore/Others/OneOf.cs similarity index 96% rename from PluginManager/Others/OneOf.cs rename to DiscordBotCore/Others/OneOf.cs index 44647c7..ef5abe5 100644 --- a/PluginManager/Others/OneOf.cs +++ b/DiscordBotCore/Others/OneOf.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace PluginManager.Others +namespace DiscordBotCore.Others { public class OneOf { diff --git a/PluginManager/Others/Permissions/DiscordPermissions.cs b/DiscordBotCore/Others/Permissions/DiscordPermissions.cs similarity index 97% rename from PluginManager/Others/Permissions/DiscordPermissions.cs rename to DiscordBotCore/Others/Permissions/DiscordPermissions.cs index 24b600c..f617b87 100644 --- a/PluginManager/Others/Permissions/DiscordPermissions.cs +++ b/DiscordBotCore/Others/Permissions/DiscordPermissions.cs @@ -2,7 +2,7 @@ using Discord; using Discord.WebSocket; -namespace PluginManager.Others.Permissions; +namespace DiscordBotCore.Others.Permissions; /// /// A class whith all discord permissions diff --git a/PluginManager/Others/SettingsDictionary.cs b/DiscordBotCore/Others/SettingsDictionary.cs similarity index 91% rename from PluginManager/Others/SettingsDictionary.cs rename to DiscordBotCore/Others/SettingsDictionary.cs index f0ae113..2bdd3ce 100644 --- a/PluginManager/Others/SettingsDictionary.cs +++ b/DiscordBotCore/Others/SettingsDictionary.cs @@ -1,10 +1,9 @@ -using System.Collections; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; -namespace PluginManager.Others; +namespace DiscordBotCore.Others; public class SettingsDictionary { @@ -36,14 +35,14 @@ public class SettingsDictionary if(!File.Exists(_File)) { _Dictionary = new Dictionary(); - return true; + return false; } string fileAsText = await File.ReadAllTextAsync(_File); if(string.IsNullOrEmpty(fileAsText) || string.IsNullOrWhiteSpace(fileAsText)) { _Dictionary = new Dictionary(); - return true; + return false; } _Dictionary = await JsonManager.ConvertFromJson>(fileAsText); @@ -76,7 +75,7 @@ public class SettingsDictionary get { if(!_Dictionary.ContainsKey(key)) - throw new System.Exception($"The key {key} ({typeof(TKey)}) was not present in the dictionary"); + throw new System.Exception($"The key {key} ({typeof(TKey)}) (file: {this._File}) was not present in the dictionary"); if(_Dictionary[key] is not TValue) throw new System.Exception("The dictionary is corrupted. This error is critical !"); diff --git a/PluginManager/Plugin/OnlineDependencyInfo.cs b/DiscordBotCore/Plugin/OnlineDependencyInfo.cs similarity index 90% rename from PluginManager/Plugin/OnlineDependencyInfo.cs rename to DiscordBotCore/Plugin/OnlineDependencyInfo.cs index 6ac49e5..345ba4e 100644 --- a/PluginManager/Plugin/OnlineDependencyInfo.cs +++ b/DiscordBotCore/Plugin/OnlineDependencyInfo.cs @@ -1,4 +1,4 @@ -namespace PluginManager.Plugin; +namespace DiscordBotCore.Plugin; public class OnlineDependencyInfo { diff --git a/PluginManager/Plugin/PluginInfo.cs b/DiscordBotCore/Plugin/PluginInfo.cs similarity index 79% rename from PluginManager/Plugin/PluginInfo.cs rename to DiscordBotCore/Plugin/PluginInfo.cs index 9023dfd..d0d3954 100644 --- a/PluginManager/Plugin/PluginInfo.cs +++ b/DiscordBotCore/Plugin/PluginInfo.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; -using PluginManager.Online.Helpers; +using DiscordBotCore.Online.Helpers; -namespace PluginManager.Plugin; +namespace DiscordBotCore.Plugin; public class PluginInfo { @@ -20,7 +20,7 @@ public class PluginInfo PluginVersion = pluginVersion; ListOfDependancies = listOfDependancies; IsMarkedToUninstall = isMarkedToUninstall; - FilePath = $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll"; + FilePath = $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll"; } public PluginInfo(string pluginName, PluginVersion pluginVersion, List listOfDependancies) @@ -29,7 +29,7 @@ public class PluginInfo PluginVersion = pluginVersion; ListOfDependancies = listOfDependancies; IsMarkedToUninstall = false; - FilePath = $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll"; + FilePath = $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll"; } public static PluginInfo FromOnlineInfo(PluginOnlineInfo onlineInfo) diff --git a/PluginManager/Plugin/PluginOnlineInfo.cs b/DiscordBotCore/Plugin/PluginOnlineInfo.cs similarity index 94% rename from PluginManager/Plugin/PluginOnlineInfo.cs rename to DiscordBotCore/Plugin/PluginOnlineInfo.cs index 317beb3..fd23e77 100644 --- a/PluginManager/Plugin/PluginOnlineInfo.cs +++ b/DiscordBotCore/Plugin/PluginOnlineInfo.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Text.Json.Serialization; using System.Threading.Tasks; -using PluginManager.Online.Helpers; -using PluginManager.Others; +using DiscordBotCore.Online.Helpers; +using DiscordBotCore.Others; -namespace PluginManager.Plugin; +namespace DiscordBotCore.Plugin; public class PluginOnlineInfo { diff --git a/PluginManager/Updater/Application/AppUpdater.cs b/DiscordBotCore/Updater/Application/AppUpdater.cs similarity index 97% rename from PluginManager/Updater/Application/AppUpdater.cs rename to DiscordBotCore/Updater/Application/AppUpdater.cs index ceefa7d..c369cf2 100644 --- a/PluginManager/Updater/Application/AppUpdater.cs +++ b/DiscordBotCore/Updater/Application/AppUpdater.cs @@ -6,9 +6,9 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; -using PluginManager.Interfaces.Updater; +using DiscordBotCore.Interfaces.Updater; -namespace PluginManager.Updater.Application +namespace DiscordBotCore.Updater.Application { public class AppUpdater { diff --git a/PluginManager/Updater/Application/Update.cs b/DiscordBotCore/Updater/Application/Update.cs similarity index 75% rename from PluginManager/Updater/Application/Update.cs rename to DiscordBotCore/Updater/Application/Update.cs index a1770f6..e7e905d 100644 --- a/PluginManager/Updater/Application/Update.cs +++ b/DiscordBotCore/Updater/Application/Update.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + +using DiscordBotCore.Interfaces.Updater; -using Discord.Commands; - -using PluginManager.Interfaces.Updater; - -namespace PluginManager.Updater.Application +namespace DiscordBotCore.Updater.Application { public class Update { diff --git a/PluginManager/Updater/Plugins/PluginUpdater.cs b/DiscordBotCore/Updater/Plugins/PluginUpdater.cs similarity index 76% rename from PluginManager/Updater/Plugins/PluginUpdater.cs rename to DiscordBotCore/Updater/Plugins/PluginUpdater.cs index 0be21e0..28382ec 100644 --- a/PluginManager/Updater/Plugins/PluginUpdater.cs +++ b/DiscordBotCore/Updater/Plugins/PluginUpdater.cs @@ -2,16 +2,17 @@ using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; -using PluginManager.Online; -using PluginManager.Plugin; +using DiscordBotCore.Online; +using DiscordBotCore.Others; +using DiscordBotCore.Plugin; -namespace PluginManager.Updater.Plugins; +namespace DiscordBotCore.Updater.Plugins; public class PluginUpdater { - private readonly PluginsManager _PluginsManager; + private readonly PluginManager _PluginsManager; - public PluginUpdater(PluginsManager pluginManager) + public PluginUpdater(PluginManager pluginManager) { _PluginsManager = pluginManager; } @@ -24,7 +25,7 @@ public class PluginUpdater public async Task GetLocalPluginInfo(string pluginName) { - string pluginsDatabase = File.ReadAllText(Config.AppSettings["PluginDatabase"]); + string pluginsDatabase = File.ReadAllText(DiscordBotCore.Application.CurrentApplication.PluginDatabase); List installedPlugins = await JsonManager.ConvertFromJson>(pluginsDatabase); var result = installedPlugins.Find(p => p.PluginName == pluginName); @@ -35,7 +36,7 @@ public class PluginUpdater public async Task UpdatePlugin(string pluginName, IProgress? progressMeter = null) { PluginOnlineInfo pluginInfo = await GetPluginInfo(pluginName); - await ServerCom.DownloadFileAsync(pluginInfo.DownLoadLink, $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll", progressMeter); + await ServerCom.DownloadFileAsync(pluginInfo.DownLoadLink, $"{DiscordBotCore.Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll", progressMeter); foreach(OnlineDependencyInfo dependency in pluginInfo.Dependencies) await ServerCom.DownloadFileAsync(dependency.DownloadLocation, dependency.DownloadLocation, progressMeter); diff --git a/DiscordBotUI/DiscordBotUI/Bot/Commands/Help.cs b/DiscordBotUI/DiscordBotUI/Bot/Commands/Help.cs index 8f9ec34..9606a84 100644 --- a/DiscordBotUI/DiscordBotUI/Bot/Commands/Help.cs +++ b/DiscordBotUI/DiscordBotUI/Bot/Commands/Help.cs @@ -79,7 +79,7 @@ internal class Help: DBCommand ); if (cmd == null) return null; - embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); + embedBuilder.AddField("Usage", Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"] + cmd.Usage); embedBuilder.AddField("Description", cmd.Description); if (cmd.Aliases is null) return embedBuilder; diff --git a/DiscordBotUI/DiscordBotUI/Bot/DiscordBot.cs b/DiscordBotUI/DiscordBotUI/Bot/DiscordBot.cs index 1e7ed32..e3cfe37 100644 --- a/DiscordBotUI/DiscordBotUI/Bot/DiscordBot.cs +++ b/DiscordBotUI/DiscordBotUI/Bot/DiscordBot.cs @@ -18,8 +18,8 @@ namespace DiscordBotUI.Bot public async Task InitializeBot() { - string token = Config.AppSettings["token"]; - string prefix = Config.AppSettings["prefix"]; + string token = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["token"]; + string prefix = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"]; PluginManager.Bot.Boot discordBooter = new PluginManager.Bot.Boot(token, prefix); await discordBooter.Awake(); } @@ -32,14 +32,14 @@ namespace DiscordBotUI.Bot { if (data.IsSuccess) { - Config.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction), + Application.CurrentApplication.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction), LogType.INFO ); } else { - Config.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage, + Application.CurrentApplication.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage, typeof(ICommandAction), LogType.ERROR ); } @@ -48,13 +48,13 @@ namespace DiscordBotUI.Bot { if (data.IsSuccess) { - Config.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction), + Application.CurrentApplication.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction), LogType.INFO ); } else { - Config.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage, + Application.CurrentApplication.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage, typeof(ICommandAction), LogType.ERROR ); } @@ -64,13 +64,13 @@ namespace DiscordBotUI.Bot { if (data.IsSuccess) { - Config.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction), + Application.CurrentApplication.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction), LogType.INFO ); } else { - Config.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage, + Application.CurrentApplication.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage, typeof(ICommandAction), LogType.ERROR ); } diff --git a/DiscordBotUI/DiscordBotUI/DiscordBotUI.csproj b/DiscordBotUI/DiscordBotUI/DiscordBotUI.csproj index 9ceec94..0e31c41 100644 --- a/DiscordBotUI/DiscordBotUI/DiscordBotUI.csproj +++ b/DiscordBotUI/DiscordBotUI/DiscordBotUI.csproj @@ -20,6 +20,6 @@ - + diff --git a/DiscordBotUI/DiscordBotUI/Views/HomePage.axaml.cs b/DiscordBotUI/DiscordBotUI/Views/HomePage.axaml.cs index c9e220c..97e6b13 100644 --- a/DiscordBotUI/DiscordBotUI/Views/HomePage.axaml.cs +++ b/DiscordBotUI/DiscordBotUI/Views/HomePage.axaml.cs @@ -28,18 +28,18 @@ public partial class HomePage : Window { await Config.Initialize(); - if(!Config.AppSettings.ContainsAllKeys("token", "prefix")) + if(!Config.Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsAllKeys("token", "prefix")) { await new SettingsPage().ShowDialog(this); - if (string.IsNullOrWhiteSpace(Config.AppSettings["token"]) || string.IsNullOrWhiteSpace(Config.AppSettings["prefix"])) + if (string.IsNullOrWhiteSpace(Config.Application.CurrentApplication.ApplicationEnvironmentVariables["token"]) || string.IsNullOrWhiteSpace(Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"])) Environment.Exit(-1); } - textBoxToken.Text = Config.AppSettings["token"]; - textBoxPrefix.Text = Config.AppSettings["prefix"]; - textBoxServerId.Text = Config.AppSettings["ServerID"]; + textBoxToken.Text = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["token"]; + textBoxPrefix.Text = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"]; + textBoxServerId.Text = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["ServerID"]; } private void SetTextToTB(Log logMessage) @@ -50,7 +50,7 @@ public partial class HomePage : Window private async void ButtonStartBotClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { - Config.Logger.OnLog += async (sender, logMessage) => + Application.CurrentApplication.Logger.OnLog += async (sender, logMessage) => { await Dispatcher.UIThread.InvokeAsync(() => SetTextToTB(logMessage), DispatcherPriority.Background); }; diff --git a/DiscordBotUI/DiscordBotUI/Views/SettingsPage.axaml.cs b/DiscordBotUI/DiscordBotUI/Views/SettingsPage.axaml.cs index 7b94dae..9abe229 100644 --- a/DiscordBotUI/DiscordBotUI/Views/SettingsPage.axaml.cs +++ b/DiscordBotUI/DiscordBotUI/Views/SettingsPage.axaml.cs @@ -30,13 +30,13 @@ public partial class SettingsPage : Window return; } - Config.AppSettings.Add("token", token); - Config.AppSettings.Add("prefix", botPrefix); - Config.AppSettings.Add("ServerID", serverId); + Config.Application.CurrentApplication.ApplicationEnvironmentVariables.Add("token", token); + Config.Application.CurrentApplication.ApplicationEnvironmentVariables.Add("prefix", botPrefix); + Config.Application.CurrentApplication.ApplicationEnvironmentVariables.Add("ServerID", serverId); - await Config.AppSettings.SaveToFile(); + await Config.Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile(); - Config.Logger.Log("Config Saved"); + Application.CurrentApplication.Logger.Log("Config Saved"); Close(); diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs deleted file mode 100644 index 3a5eec8..0000000 --- a/PluginManager/Config.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; -using PluginManager.Bot; -using PluginManager.Interfaces.Updater; -using PluginManager.Online; -using PluginManager.Others; -using PluginManager.Others.Actions; -using PluginManager.Others.Logger; -using PluginManager.Plugin; -using PluginManager.Updater.Application; - -namespace PluginManager; - -public class Config -{ - - private static readonly string _DefaultBranchForPlugins = "releases"; - - private static readonly string _ConfigFile = "./Data/Resources/config.json"; - private static readonly string _PluginsDatabaseFile = "./Data/Resources/plugins.json"; - private static readonly string _ResourcesFolder = "./Data/Resources"; - private static readonly string _PluginsFolder = "./Data/Plugins"; - private static readonly string _ArchivesFolder = "./Data/Archives"; - private static readonly string _LogsFolder = "./Data/Logs"; - - private static bool _isLoaded; - public static Logger Logger; - public static SettingsDictionary AppSettings; - - internal static string PluginDatabase => AppSettings["PluginDatabase"]; - internal static string ServerID => AppSettings["ServerID"]; - - public static InternalActionManager InternalActionManager; - - public static PluginsManager PluginsManager; - - internal static Boot? DiscordBotClient; - - public static Boot? DiscordBot => DiscordBotClient; - - public static async Task Initialize() - { - if (_isLoaded) return; - - Directory.CreateDirectory(_ResourcesFolder); - Directory.CreateDirectory(_PluginsFolder); - Directory.CreateDirectory(_ArchivesFolder); - Directory.CreateDirectory(_LogsFolder); - - AppSettings = new SettingsDictionary(_ConfigFile); - bool response = await AppSettings.LoadFromFile(); - - if (!response) - throw new Exception("Invalid config file"); - - AppSettings["LogFolder"] = _LogsFolder; - AppSettings["PluginFolder"] = _PluginsFolder; - AppSettings["ArchiveFolder"] = _ArchivesFolder; - AppSettings["PluginDatabase"] = _PluginsDatabaseFile; - - if (!File.Exists(_PluginsDatabaseFile)) - { - List plugins = new(); - await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins); - } - - Logger = new Logger(false, true, _LogsFolder + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log"); - - PluginsManager = new PluginsManager(_DefaultBranchForPlugins); - - await PluginsManager.UninstallMarkedPlugins(); - - await PluginsManager.CheckForUpdates(); - - _isLoaded = true; - - Logger.Log("Config initialized", typeof(Config)); - - } - -} diff --git a/PluginManager/Interfaces/Logger/ILog.cs b/PluginManager/Interfaces/Logger/ILog.cs deleted file mode 100644 index 19c4b8a..0000000 --- a/PluginManager/Interfaces/Logger/ILog.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using PluginManager.Others; - -namespace PluginManager.Interfaces.Logger; - -internal interface ILog -{ - string Message { get; set; } - - Type? Source { get; set; } - - LogType Type { get; set; } - DateTime ThrowTime { get; set; } -} diff --git a/PluginManager/Interfaces/Logger/ILogger.cs b/PluginManager/Interfaces/Logger/ILogger.cs deleted file mode 100644 index d45e527..0000000 --- a/PluginManager/Interfaces/Logger/ILogger.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Threading.Tasks; -using PluginManager.Others; -using PluginManager.Others.Logger; - -namespace PluginManager.Interfaces.Logger; - -internal interface ILogger -{ - bool IsEnabled { get; init; } - bool OutputToFile { get; init; } - - string OutputFile { get; init; } - - event EventHandler OnLog; - void Log( - string message = "", Type? source = default, LogType type = LogType.INFO, - DateTime throwTime = default); -} diff --git a/PluginManager/Others/Logger/Log.cs b/PluginManager/Others/Logger/Log.cs deleted file mode 100644 index 164a4ab..0000000 --- a/PluginManager/Others/Logger/Log.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Linq; -using PluginManager.Interfaces.Logger; - -namespace PluginManager.Others.Logger; - -public class Log: ILog -{ - 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; - Source = source; - Type = type; - ThrowTime = throwTime; - } - - public Log(string message, Type? source, LogType type) - { - Message = message; - Source = source; - Type = type; - ThrowTime = DateTime.Now; - } - - public Log(string message, Type? source) - { - Message = message; - Source = source; - Type = LogType.INFO; - ThrowTime = DateTime.Now; - } - - public Log(string message) - { - Message = message; - Source = typeof(Log); - Type = LogType.INFO; - ThrowTime = DateTime.Now; - } - - public static implicit operator Log(string message) - { - return new Log(message); - } - - public static implicit operator string(Log log) - { - return $"[{log.ThrowTime}] {log.Message}"; - } - - public string AsLongString() - { - return $"[{ThrowTime}] [{Source}] [{Type}] {Message}"; - } - - public string AsShortString() - { - return this; - } - - public string FormatedLongString() - { - return $"[{ThrowTime}]\t[{Source}]\t\t\t[{Type}]\t{Message}"; - } -} diff --git a/PluginManager/Others/Logger/Logger.cs b/PluginManager/Others/Logger/Logger.cs deleted file mode 100644 index de9ab64..0000000 --- a/PluginManager/Others/Logger/Logger.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using PluginManager.Interfaces.Logger; - -namespace PluginManager.Others.Logger; - -public sealed class Logger: ILogger -{ - 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, 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( - OutputFile!, - (UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n" - ); - } - - 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 (throwTime == default) throwTime = DateTime.Now; - - if (source == default) source = typeof(Log); - - 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, source, logType, DateTime.Now)); - } -} diff --git a/SethDiscordBot.sln b/SethDiscordBot.sln index c6264aa..6686388 100644 --- a/SethDiscordBot.sln +++ b/SethDiscordBot.sln @@ -4,14 +4,14 @@ VisualStudioVersion = 17.1.32421.90 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\DiscordBot.csproj", "{087E64F4-1E1C-4899-8223-295356C9894A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SethPlugins", "SethPlugins", "{78B6D390-F61A-453F-B38D-E4C054321615}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI", "DiscordBotUI\DiscordBotUI\DiscordBotUI.csproj", "{71293BF7-79D0-4707-AB4B-FDD16800FA81}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI.Desktop", "DiscordBotUI\DiscordBotUI.Desktop\DiscordBotUI.Desktop.csproj", "{F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotCore", "DiscordBotCore\DiscordBotCore.csproj", "{5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -22,10 +22,6 @@ Global {087E64F4-1E1C-4899-8223-295356C9894A}.Debug|Any CPU.Build.0 = Debug|Any CPU {087E64F4-1E1C-4899-8223-295356C9894A}.Release|Any CPU.ActiveCfg = Release|Any CPU {087E64F4-1E1C-4899-8223-295356C9894A}.Release|Any CPU.Build.0 = Release|Any CPU - {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = Release|Any CPU {71293BF7-79D0-4707-AB4B-FDD16800FA81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {71293BF7-79D0-4707-AB4B-FDD16800FA81}.Debug|Any CPU.Build.0 = Debug|Any CPU {71293BF7-79D0-4707-AB4B-FDD16800FA81}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -34,6 +30,10 @@ Global {F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Release|Any CPU.Build.0 = Release|Any CPU + {5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE