From 460a85944a926a36ef83ade0c8ec61f7113a58be Mon Sep 17 00:00:00 2001 From: Andrei Date: Fri, 24 Mar 2023 21:52:03 +0200 Subject: [PATCH] changed to .json file instead of database for settings --- .gitignore | 3 +- DiscordBot/Discord/Commands/Help.cs | 9 +- DiscordBot/Entry.cs | 2 +- DiscordBot/Program.cs | 145 +++++----- DiscordBot/StartupArguments.cs | 14 - PluginManager/Bot/Boot.cs | 18 +- PluginManager/Config.cs | 254 +++++++----------- PluginManager/Items/ConsoleCommandsHandler.cs | 15 +- PluginManager/Loaders/PluginLoader.cs | 4 +- PluginManager/Logger.cs | 20 +- PluginManager/Online/ServerCom.cs | 4 +- PluginManager/Others/ArchiveManager.cs | 7 +- PluginManager/Others/Functions.cs | 1 + PluginManager/Variables.cs | 17 -- SethDiscordBot.sln | 6 + 15 files changed, 207 insertions(+), 312 deletions(-) delete mode 100644 DiscordBot/StartupArguments.cs delete mode 100644 PluginManager/Variables.cs diff --git a/.gitignore b/.gitignore index 7cf8b6f..c82094e 100644 --- a/.gitignore +++ b/.gitignore @@ -372,4 +372,5 @@ FodyWeavers.xsd /DiscordBot/Data/ /DiscordBot/Updater/ .vscode/ -.idea/ \ No newline at end of file +.idea/ +/DiscordBotWeb/ \ No newline at end of file diff --git a/DiscordBot/Discord/Commands/Help.cs b/DiscordBot/Discord/Commands/Help.cs index 23fa7ca..52855c6 100644 --- a/DiscordBot/Discord/Commands/Help.cs +++ b/DiscordBot/Discord/Commands/Help.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using Discord; + using PluginManager; using PluginManager.Interfaces; using PluginManager.Loaders; @@ -48,7 +49,7 @@ internal class Help : DBCommand args.context.Channel.SendMessageAsync("Unknown Command " + args.arguments[0]); else args.context.Channel.SendMessageAsync(embed: e.Build()); - + return; } @@ -65,9 +66,9 @@ internal class Help : DBCommand normalCommands += cmd.Command + " "; - if(adminCommands.Length > 0) + if (adminCommands.Length > 0) embedBuilder.AddField("Admin Commands", adminCommands); - if(normalCommands.Length > 0) + if (normalCommands.Length > 0) embedBuilder.AddField("Normal Commands", normalCommands); args.context.Channel.SendMessageAsync(embed: embedBuilder.Build()); } @@ -79,7 +80,7 @@ internal class Help : DBCommand (p.Aliases is not null && p.Aliases.Contains(command))); if (cmd == null) return null; - embedBuilder.AddField("Usage", Config.Variables.GetValue("prefix") + cmd.Usage); + embedBuilder.AddField("Usage", Config.Data["prefix"] + cmd.Usage); embedBuilder.AddField("Description", cmd.Description); if (cmd.Aliases is null) return embedBuilder; diff --git a/DiscordBot/Entry.cs b/DiscordBot/Entry.cs index b77d97e..05e04d0 100644 --- a/DiscordBot/Entry.cs +++ b/DiscordBot/Entry.cs @@ -1,4 +1,5 @@ using PluginManager.Others; + using System; using System.IO; using System.Linq; @@ -10,7 +11,6 @@ namespace DiscordBot public class Entry { - internal static StartupArguments startupArguments; public static void Main(string[] args) { AppDomain currentDomain = AppDomain.CurrentDomain; diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index dd0c8bf..2865814 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -31,13 +31,14 @@ public class Program [STAThread] public static void Startup(string[] args) { + PreLoadComponents(args).Wait(); - if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") || - Config.Variables.GetValue("token") == null || - (Config.Variables.GetValue("token")?.Length != 70 && Config.Variables.GetValue("token")?.Length != 59) || - !Config.Variables.Exists("prefix") || Config.Variables.GetValue("prefix") == null || - Config.Variables.GetValue("prefix")?.Length != 1 || + if (!Config.Data.ContainsKey("ServerID") || !Config.Data.ContainsKey("token") || + Config.Data["token"] == null || + (Config.Data["token"]?.Length != 70 && Config.Data["token"]?.Length != 59) || + !Config.Data.ContainsKey("prefix") || Config.Data["prefix"] == null || + Config.Data["prefix"]?.Length != 1 || (args.Length == 1 && args[0] == "/reset")) { GenerateStartUI("First time setup. Please fill the following with your discord bot data.\nThis are saved ONLY on YOUR computer."); @@ -57,7 +58,7 @@ public class Program Logger.WriteLine(); #endif - if (loadPluginsOnStartup) + if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); while (true) @@ -91,14 +92,14 @@ public class Program Logger.WriteLine( $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); - Logger.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); + Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}"); Utilities.WriteColorText( "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); Console.ForegroundColor = ConsoleColor.White; - if (Config.Variables.Exists("LaunchMessage")) - Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage")); + if (Config.Data.ContainsKey("LaunchMessage")) + Utilities.WriteColorText(Config.Data["LaunchMessage"]); Utilities.WriteColorText( @@ -113,11 +114,11 @@ public class Program string token = ""; #if DEBUG if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt"); - else token = Config.Variables.GetValue("token"); + else token = Config.Data["token"]; #else - token = Config.Variables.GetValue("token"); + token = Config.Data["token"]; #endif - var prefix = Config.Variables.GetValue("prefix"); + var prefix = Config.Data["prefix"]; var discordbooter = new Boot(token, prefix); await discordbooter.Awake(); return discordbooter; @@ -140,8 +141,6 @@ public class Program var b = await StartNoGui(); consoleCommandsHandler = new ConsoleCommandsHandler(b.client); - if (Entry.startupArguments.loadPluginsAtStartup) { loadPluginsOnStartup = true; } - if (len > 0 && args[0] == "/remplug") { var plugName = string.Join(' ', args, 1, args.Length - 1); @@ -150,7 +149,7 @@ public class Program loadPluginsOnStartup = true; } - + var mainThread = new Thread(() => { @@ -162,10 +161,9 @@ public class Program { if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) { - if (Config.Variables.Exists("LaunchMessage")) - Config.Variables.Add("LaunchMessage", - "An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", - false); + if (Config.Data.ContainsKey("LaunchMessage")) + Config.Data.Add("LaunchMessage", + "An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !"); Logger.WriteErrFile(ex.ToString()); } } @@ -175,24 +173,15 @@ public class Program private static async Task PreLoadComponents(string[] args) { + await Config.Initialize(true); - if (!File.Exists(Functions.dataFolder + "loader.json")) - { - Entry.startupArguments = new StartupArguments(); - await Functions.SaveToJsonFile(Functions.dataFolder + "loader.json", Entry.startupArguments); - } - else - Entry.startupArguments = await Functions.ConvertFromJson(Functions.dataFolder + "loader.json"); - - await Config.Initialize("SetDB.dat", true); - Logger.WriteLine("Loading resources ..."); var main = new Utilities.ProgressBar(ProgressBarType.NO_END); main.Start(); - if (await Config.Variables.ExistsAsync("DeleteLogsAtStartup")) - if (await Config.Variables.GetValueAsync("DeleteLogsAtStartup") == "true") + if (Config.Data.ContainsKey("DeleteLogsAtStartup")) + if (Config.Data["DeleteLogsAtStartup"] == "true") foreach (var file in Directory.GetFiles("./Output/Logs/")) File.Delete(file); var OnlineDefaultKeys = @@ -200,13 +189,7 @@ public class Program "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys"); - if (!await Config.Variables.ExistsAsync("Version")) - await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(), - false); - else - await Config.Variables.SetValueAsync( - "Version", Assembly.GetExecutingAssembly().GetName().Version.ToString()); - + Config.Data["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); foreach (var key in OnlineDefaultKeys) { @@ -214,9 +197,7 @@ public class Program var s = key.Split(' '); try { - if (await Config.Variables.ExistsAsync(s[0])) await Config.Variables.SetValueAsync(s[0], s[1]); - else - await Config.Variables.AddAsync(s[0], s[1], s[2].ToLower() == "true"); + Config.Data[s[0]] = s[1]; } catch (Exception ex) { @@ -238,11 +219,11 @@ public class Program { case "CurrentVersion": var newVersion = s[1]; - var currentVersion = await Config.Variables.GetValueAsync("Version"); + var currentVersion = Config.Data["Version"]; if (!newVersion.Equals(currentVersion)) { - if(OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) + if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { Console.Clear(); Logger.WriteLine("A new update was found !"); @@ -257,10 +238,10 @@ public class Program break; } var nVer = new VersionString(newVersion.Substring(2)); - var cVer = new VersionString((await Config.Variables.GetValueAsync("Version")).Substring(2)); + var cVer = new VersionString((Config.Data["Version"]).Substring(2)); if (cVer > nVer) { - await Config.Variables.SetValueAsync("Version", "1." + cVer.ToShortString() + " (Beta)"); + Config.Data["version"] = "1." + cVer.ToShortString() + " (Beta)"; break; } @@ -285,38 +266,38 @@ public class Program Logger.WriteLine("Do you want to update the bot ? (y/n)"); if (Console.ReadKey().Key == ConsoleKey.Y) { - var url = - $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip"; - if (Logger.isConsole) - Console.SetCursorPosition(0, Console.CursorTop); - Logger.WriteLine($"executing: download_file {url}"); + var url = + $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip"; + if (Logger.isConsole) + Console.SetCursorPosition(0, Console.CursorTop); + Logger.WriteLine($"executing: download_file {url}"); - await ServerCom.DownloadFileAsync(url, "./update.zip", new Progress(percent => { Logger.Write($"\rProgress: {percent}% "); })); - await File.WriteAllTextAsync("Install.sh", - "#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot"); - Logger.WriteLine(); + await ServerCom.DownloadFileAsync(url, "./update.zip", new Progress(percent => { Logger.Write($"\rProgress: {percent}% "); })); + await File.WriteAllTextAsync("Install.sh", + "#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot"); + Logger.WriteLine(); - try - { - Logger.WriteLine("executing: chmod a+x Install.sh"); - Process.Start("chmod", "a+x Install.sh").WaitForExit(); - Process.Start("Install.sh").WaitForExit(); + try + { + Logger.WriteLine("executing: chmod a+x Install.sh"); + Process.Start("chmod", "a+x Install.sh").WaitForExit(); + Process.Start("Install.sh").WaitForExit(); - Logger.WriteLine("executing: rm Install.sh"); - Process.Start("rm", "Install.sh").WaitForExit(); + Logger.WriteLine("executing: rm Install.sh"); + Process.Start("rm", "Install.sh").WaitForExit(); + + Logger.WriteLine("The new version of the bot has been installed."); + Logger.WriteLine("Please restart the bot."); + Environment.Exit(0); + } + catch (Exception ex) + { + Logger.WriteErrFile(ex.Message); + if (ex.Message.Contains("Access de")) + Logger.WriteLine("Please run the bot as root."); + } - Logger.WriteLine("The new version of the bot has been installed."); - Logger.WriteLine("Please restart the bot."); - Environment.Exit(0); - } - catch (Exception ex) - { - Logger.WriteErrFile(ex.Message); - if (ex.Message.Contains("Access de")) - Logger.WriteLine("Please run the bot as root."); - } - } } @@ -328,9 +309,9 @@ public class Program break; Directory.CreateDirectory(Functions.dataFolder + "Applications"); - if (!await Config.Variables.ExistsAsync("LauncherVersion")) - await Config.Variables.AddAsync("LauncherVersion", "0.0.0.0", false); - if (await Config.Variables.GetValueAsync("LauncherVersion") != updaternewversion || + if (!Config.Data.ContainsKey("LauncherVersion")) + Config.Data["LauncherVersion"] = "0.0.0.0"; + if (Config.Data["LauncherVersion"] != updaternewversion || !File.Exists("./Launcher.exe")) { Console.Clear(); @@ -342,7 +323,7 @@ public class Program $"./Launcher.exe"); //await ArchiveManager.ExtractArchive("./Updater.zip", "./", null, // UnzipProgressType.PercentageFromTotalSize); - await Config.Variables.SetValueAsync("LauncherVersion", updaternewversion); + Config.Data["LauncherVersion"] = updaternewversion; // File.Delete("Updater.zip"); bar.Stop("The launcher has been updated !"); Console.Clear(); @@ -382,7 +363,7 @@ public class Program Y = 5 }; - var textFiledToken = new TextField(Config.Variables.GetValue("token") ?? "") + var textFiledToken = new TextField(Config.Data["token"] ?? "") { X = Pos.Left(labelToken) + labelToken.Text.Length + 2, Y = labelToken.Y, @@ -394,7 +375,7 @@ public class Program X = 5, Y = 8 }; - var textFiledPrefix = new TextField(Config.Variables.GetValue("prefix") ?? "") + var textFiledPrefix = new TextField(Config.Data["prefix"] ?? "") { X = Pos.Left(labelPrefix) + labelPrefix.Text.Length + 2, Y = labelPrefix.Y, @@ -406,7 +387,7 @@ public class Program X = 5, Y = 11 }; - var textFiledServerID = new TextField(Config.Variables.GetValue("ServerID") ?? "") + var textFiledServerID = new TextField(Config.Data["ServerID"] ?? "") { X = Pos.Left(labelServerid) + labelServerid.Text.Length + 2, Y = labelServerid.Y, @@ -451,9 +432,9 @@ public class Program } - Config.Variables.Add("ServerID", (string)textFiledServerID.Text, true); - Config.Variables.Add("token", (string)textFiledToken.Text, true); - Config.Variables.Add("prefix", (string)textFiledPrefix.Text, true); + Config.Data.Add("ServerID", (string)textFiledServerID.Text); + Config.Data.Add("token", (string)textFiledToken.Text); + Config.Data.Add("prefix", (string)textFiledPrefix.Text); MessageBox.Query("Discord Bot Settings", "Successfully saved config !\nJust start the bot :D", "Start :D"); diff --git a/DiscordBot/StartupArguments.cs b/DiscordBot/StartupArguments.cs deleted file mode 100644 index fd2ac56..0000000 --- a/DiscordBot/StartupArguments.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace DiscordBot -{ - internal class StartupArguments - { - public string runArgs { get; } = ""; - public bool loadPluginsAtStartup { get; } = true; - } -} diff --git a/PluginManager/Bot/Boot.cs b/PluginManager/Bot/Boot.cs index 9c3a96a..b6b8039 100644 --- a/PluginManager/Bot/Boot.cs +++ b/PluginManager/Bot/Boot.cs @@ -60,17 +60,17 @@ public class Boot /// Task public async Task Awake(DiscordSocketConfig? config = null) { - if(config is null) - config = new DiscordSocketConfig - { + if (config is null) + config = new DiscordSocketConfig + { - AlwaysDownloadUsers = true, + AlwaysDownloadUsers = true, - //Disable system clock checkup (for responses at slash commands) - UseInteractionSnowflakeDate = false, + //Disable system clock checkup (for responses at slash commands) + UseInteractionSnowflakeDate = false, - GatewayIntents = GatewayIntents.All - }; + GatewayIntents = GatewayIntents.All + }; client = new DiscordSocketClient(config); service = new CommandService(); @@ -105,7 +105,7 @@ public class Boot { if (arg.Message.Contains("401")) { - Config.Variables.RemoveKey("token"); + Config.Data.Remove("token"); Logger.LogError("The token is invalid. Please restart the bot and enter a valid token."); await Task.Delay(4000); Environment.Exit(0); diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index 0ec0e1d..462d948 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -2,15 +2,21 @@ using System.Threading.Tasks; using System.IO; +using System.Collections.Generic; +using PluginManager.Others; +using System.Collections; using PluginManager.Online.Helpers; -using PluginManager.Database; namespace PluginManager; public static class Config { private static bool IsLoaded = false; - public static async Task Initialize(string DatabaseName, bool isConsole) + + public static Json Data; + public static Json Plugins; + + public static async Task Initialize(bool isConsole) { if (IsLoaded) return; @@ -19,200 +25,126 @@ public static class Config Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/PAKS"); - Settings.sqlDatabase = new SqlDatabase(DatabaseName); - await Settings.sqlDatabase.Open(); - - - if (!await Settings.sqlDatabase.TableExistsAsync("Plugins")) - await Settings.sqlDatabase.CreateTableAsync("Plugins", "PluginName", "Version"); - if (!await Settings.sqlDatabase.TableExistsAsync("Variables")) - await Settings.sqlDatabase.CreateTableAsync("Variables", "VarName", "Value", "ReadOnly"); + Data = new Json("./Data/Resources/config.json"); + Plugins = new Json("./Data/Resources/Plugins.json"); IsLoaded = true; - Logger.Initialize(isConsole); - PluginManager.Others.ArchiveManager.Initialize(); + ArchiveManager.Initialize(); - if(isConsole) + if (isConsole) Logger.LogEvent += (message) => { Console.Write(message); }; } - public static class Variables + public class Json : IDictionary { - public static async Task GetValueAsync(string VarName) + protected IDictionary _dictionary; + + public Json(IDictionary dictionary) { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - return await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "Value"); + _dictionary = dictionary; } - public static string? GetValue(string VarName) + public Json(string file) { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - return Settings.sqlDatabase.GetValue("Variables", "VarName", VarName, "Value"); + _dictionary = PrivateReadConfig(file).GetAwaiter().GetResult(); } - - public static async Task SetValueAsync(string VarName, string Value) + public virtual void Add(TKey key, TValue value) { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - - if (await IsReadOnlyAsync(VarName)) - throw new Exception($"Variable ({VarName}) is read only and can not be changed to {Value}"); - - await Settings.sqlDatabase.SetValueAsync("Variables", "VarName", VarName, "Value", Value); + _dictionary.Add(key, value); } - public static void SetValue(string VarName, string Value) + public void Clear() { _dictionary.Clear(); } + + public bool ContainsKey(TKey key) { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - if (IsReadOnly(VarName)) - throw new Exception($"Variable ({VarName}) is read only and can not be changed to {Value}"); - Settings.sqlDatabase.SetValue("Variables", "VarName", VarName, "Value", Value); + if (_dictionary == null) + throw new Exception("Dictionary is null"); + + return _dictionary.ContainsKey(key); } + public virtual ICollection Keys => _dictionary.Keys; - public static async Task IsReadOnlyAsync(string VarName) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - return (await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "ReadOnly")).Equals("true", StringComparison.CurrentCultureIgnoreCase); - } + public virtual ICollection Values => _dictionary.Values; - public static bool IsReadOnly(string VarName) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - return (Settings.sqlDatabase.GetValue("Variables", "VarName", VarName, "ReadOnly")).Equals("true", StringComparison.CurrentCultureIgnoreCase); - } + public int Count => _dictionary.Count; - public static async Task SetReadOnlyAsync(string VarName, bool ReadOnly) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - await Settings.sqlDatabase.SetValueAsync("Variables", "VarName", VarName, "ReadOnly", ReadOnly ? "true" : "false"); - } + public bool IsReadOnly => _dictionary.IsReadOnly; - public static void SetReadOnly(string VarName, bool ReadOnly) + public virtual TValue this[TKey key] { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - Settings.sqlDatabase.SetValue("Variables", "VarName", VarName, "ReadOnly", ReadOnly ? "true" : "false"); - } - - public static async Task ExistsAsync(string VarName) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - return await Settings.sqlDatabase.KeyExistsAsync("Variables", "VarName", VarName); - } - - public static bool Exists(string VarName) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - return Settings.sqlDatabase.KeyExists("Variables", "VarName", VarName); - } - - public static async Task AddAsync(string VarName, string Value, bool ReadOnly = false) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - if (await ExistsAsync(VarName)) + get { - await SetValueAsync(VarName, Value); - await SetReadOnlyAsync(VarName, ReadOnly); - return; - } - await Settings.sqlDatabase.InsertAsync("Variables", VarName, Value, ReadOnly ? "true" : "false"); - } + if (_dictionary.TryGetValue(key, out TValue value)) return value; + return default; - public static void Add(string VarName, string Value, bool ReadOnly = false) - { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - if (Exists(VarName)) + } + set { - if (GetValue(VarName) == Value) - return; - - SetValue(VarName, Value); - SetReadOnly(VarName, ReadOnly); - return; + if (_dictionary.ContainsKey(key)) + _dictionary[key] = value; + else _dictionary.Add(key, value); } - Settings.sqlDatabase.Insert("Variables", VarName, Value, ReadOnly ? "true" : "false"); } - public static async Task RemoveKeyAsync(string VarName) + public virtual bool TryGetValue(TKey key, out TValue value) { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - await Settings.sqlDatabase.RemoveKeyAsync("Variables", "VarName", VarName); + return _dictionary.TryGetValue(key, out value); } - public static void RemoveKey(string VarName) + private async Task> PrivateReadConfig(string file) { - if (!IsLoaded) - throw new Exception("Config is not loaded"); - Settings.sqlDatabase.RemoveKey("Variables", "VarName", VarName); + if (!File.Exists(file)) + { + var dictionary = new Dictionary(); + await Functions.SaveToJsonFile(file, _dictionary); + return dictionary; + } + + var d = await Functions.ConvertFromJson>(file); + + if (d is null) + throw new Exception("Failed to read config file"); + + return d; + } + + public bool Remove(TKey key) + { + return _dictionary.Remove(key); + } + + public void Add(KeyValuePair item) + { + _dictionary.Add(item); + } + + public bool Contains(KeyValuePair item) + { + return _dictionary.Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + _dictionary.CopyTo(array, arrayIndex); + } + + public bool Remove(KeyValuePair item) + { + return _dictionary.Remove(item); + } + + public IEnumerator> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)_dictionary).GetEnumerator(); } } - public static class Plugins - { - public static async Task GetVersionAsync(string pluginName) - { - if (!IsLoaded) - throw new Exception("Config is not loaded yet"); - - string result = await Settings.sqlDatabase.GetValueAsync("Plugins", "PluginName", pluginName, "Version"); - if (result is null) - return "0.0.0"; - - return result; - } - - public static string GetVersion(string pluginName) - { - if (!IsLoaded) - throw new Exception("Config is not loaded yet"); - - string result = Settings.sqlDatabase.GetValue("Plugins", "PluginName", pluginName, "Version"); - if (result is null) - return "0.0.0"; - - return result; - } - - public static async Task SetVersionAsync(string pluginName, VersionString version) - { - if (!IsLoaded) - throw new Exception("Config is not loaded yet"); - - if (!await Settings.sqlDatabase.KeyExistsAsync("Plugins", "PluginName", pluginName)) - { - await Settings.sqlDatabase.InsertAsync("Plugins", pluginName, version.ToShortString()); - return; - } - await Settings.sqlDatabase.SetValueAsync("Plugins", "PluginName", pluginName, "Version", version.ToShortString()); - } - - public static void SetVersion(string pluginName, VersionString version) - { - if (!IsLoaded) - throw new Exception("Config is not loaded yet"); - - if (!Settings.sqlDatabase.KeyExists("Plugins", "PluginName", pluginName)) - { - Settings.sqlDatabase.Insert("Plugins", pluginName, version.ToShortString()); - return; - } - - Settings.sqlDatabase.SetValue("Plugins", "PluginName", pluginName, "Version", version.ToShortString()); - } - - } -} \ No newline at end of file +} diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 266f6b6..2bd57ef 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -254,7 +254,7 @@ public class ConsoleCommandsHandler var ver = await ServerCom.GetVersionOfPackageFromWeb(name); if (ver is null) throw new Exception("Incorrect version"); - await Config.Plugins.SetVersionAsync(name, ver); + Config.Plugins[name] = ver.ToShortString(); isDownloading = false; @@ -267,15 +267,15 @@ public class ConsoleCommandsHandler { if (args.Length != 2) return; - if (!Config.Variables.Exists(args[1])) + if (!Config.Data.ContainsKey(args[1])) return; - var data = Config.Variables.GetValue(args[1]); + var data = Config.Data[args[1]]; Logger.WriteLine($"{args[1]} => {data}"); } ); - AddCommand("add", "add variable to the system variables", "add [key] [value] [isReadOnly=true/false]", args => + AddCommand("add", "add variable to the system variables", "add [key] [value]", args => { if (args.Length < 4) return; @@ -285,7 +285,7 @@ public class ConsoleCommandsHandler try { - Config.Variables.Add(key, value, isReadOnly); + Config.Data[key] = value; Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); } catch (Exception ex) @@ -299,7 +299,7 @@ public class ConsoleCommandsHandler { if (args.Length < 2) return; - Config.Variables.RemoveKey(args[1]); + Config.Data.Remove(args[1]); } ); @@ -308,7 +308,8 @@ public class ConsoleCommandsHandler if (client is null) return; - Settings.sqlDatabase.Stop(); + await Functions.SaveToJsonFile(Functions.dataFolder + "config.json", Config.Data); + await Functions.SaveToJsonFile(Functions.dataFolder + "Plugins.json", Config.Plugins); await client.StopAsync(); await client.DisposeAsync(); await Task.Delay(1000); diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index f04b715..2610906 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -80,8 +80,8 @@ public class PluginLoader var version = await ServerCom.GetVersionOfPackageFromWeb(name); if (version is null) return; - if (Config.Plugins.GetVersion(name) is not null) - Config.Plugins.SetVersion(name, version); + if (Config.Plugins[name] is not null) + Config.Plugins[name] = version.ToShortString(); if (await PluginUpdater.CheckForUpdates(name)) await PluginUpdater.Download(name); diff --git a/PluginManager/Logger.cs b/PluginManager/Logger.cs index 9aa257d..a63da13 100644 --- a/PluginManager/Logger.cs +++ b/PluginManager/Logger.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Numerics; + using Discord; namespace PluginManager @@ -17,17 +18,19 @@ namespace PluginManager public static void Initialize(bool console) { - if (isInitialized) throw new Exception("Logger is already initialized"); + if (isInitialized) + throw new Exception("Logger is already initialized"); - if (!Config.Variables.Exists("LogFolder")) - Config.Variables.Add("LogFolder", "./Data/Output/Logs/"); + if (!Config.Data.ContainsKey("LogFolder")) + Config.Data.Add("LogFolder", "./Data/Output/Logs/"); - if (!Config.Variables.Exists("ErrorFolder")) - Config.Variables.Add("ErrorFolder", "./Data/Output/Errors/"); + if (!Config.Data.ContainsKey("ErrorFolder")) + Config.Data.Add("ErrorFolder", "./Data/Output/Errors/"); isInitialized = true; - logFolder = Config.Variables.GetValue("LogFolder"); - errFolder = Config.Variables.GetValue("ErrorFolder"); + + logFolder = Config.Data["LogFolder"]; + errFolder = Config.Data["ErrorFolder"]; isConsole = console; } @@ -105,7 +108,8 @@ namespace PluginManager public static void WriteColored(string message, ConsoleColor color) { if (!isInitialized) throw new Exception("Logger is not initialized"); - if(!isConsole) { + if (!isConsole) + { LogEvent?.Invoke(message); return; } diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs index 5a8a7c8..beaf976 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/PluginManager/Online/ServerCom.cs @@ -91,9 +91,7 @@ public static class ServerCom public static VersionString? GetVersionOfPackage(string pakName) { - if (Config.Plugins.GetVersion(pakName) is null) - return null; - return new VersionString(Config.Plugins.GetVersion(pakName)); + return new VersionString(Config.Plugins[pakName]); } public static async Task GetVersionOfPackageFromWeb(string pakName) diff --git a/PluginManager/Others/ArchiveManager.cs b/PluginManager/Others/ArchiveManager.cs index 1af60dc..6b443e1 100644 --- a/PluginManager/Others/ArchiveManager.cs +++ b/PluginManager/Others/ArchiveManager.cs @@ -15,11 +15,12 @@ namespace PluginManager.Others { if (isInitialized) throw new Exception("ArchiveManager is already initialized"); - if (!Config.Variables.Exists("ArchiveFolder")) - Config.Variables.Add("ArchiveFolder", "./Data/PAKS/"); + if (!Config.Data.ContainsKey("ArchiveFolder")) + Config.Data["ArchiveFolder"] = "./Data/PAKS/"; + + archiveFolder = Config.Data["ArchiveFolder"]; isInitialized = true; - archiveFolder = Config.Variables.GetValue("ArchiveFolder"); } /// diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 31c908c..33d538c 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -94,6 +94,7 @@ public static class Functions /// public static async Task ConvertFromJson(string input) { + Console.WriteLine(input); Stream text; if (File.Exists(input)) text = new MemoryStream(await File.ReadAllBytesAsync(input)); diff --git a/PluginManager/Variables.cs b/PluginManager/Variables.cs deleted file mode 100644 index 2c4dfab..0000000 --- a/PluginManager/Variables.cs +++ /dev/null @@ -1,17 +0,0 @@ -using PluginManager.Database; - -namespace PluginManager -{ - public class Settings - { - - public static class Variables - { - public static string WebsiteURL = "https://wizzy69.github.io/SethDiscordBot"; - public static string UpdaterURL = "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip"; - } - - public static SqlDatabase sqlDatabase; - } - -} diff --git a/SethDiscordBot.sln b/SethDiscordBot.sln index 5a6a5b4..7f482dd 100644 --- a/SethDiscordBot.sln +++ b/SethDiscordBot.sln @@ -7,6 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\Di EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotWeb", "DiscordBotWeb\DiscordBotWeb.csproj", "{5500905A-E48F-4191-BB76-8610FA19F251}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +23,10 @@ Global {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 + {5500905A-E48F-4191-BB76-8610FA19F251}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5500905A-E48F-4191-BB76-8610FA19F251}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5500905A-E48F-4191-BB76-8610FA19F251}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5500905A-E48F-4191-BB76-8610FA19F251}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE