From 6da9828e5cdef8f9e4ecf080f4194d4a6de5c97c Mon Sep 17 00:00:00 2001 From: Wizzy69 Date: Sat, 20 Aug 2022 17:44:19 +0300 Subject: [PATCH] improved save method --- DiscordBot/Program.cs | 35 +++++++++-- PluginManager/Config.cs | 58 +++++++++++++------ PluginManager/Items/ConsoleCommandsHandler.cs | 22 ++++++- PluginManager/Loaders/PluginLoader.cs | 2 +- PluginManager/Online/Helpers/VersionString.cs | 3 + PluginManager/Others/Enums.cs | 4 +- PluginManager/Others/Functions.cs | 10 ++-- 7 files changed, 101 insertions(+), 33 deletions(-) diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index 3383372..98faa69 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -115,10 +115,10 @@ public class Program if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs"); #endif - Config.SaveConfig(); + Config.SaveConfig(SaveType.NORMAL); while (true) { - //Console_Utilities.WriteColorText("&rSethBot (&yDEBUG&r) &c> ", false); + // Console_Utilities.WriteColorText("&rSethBot (&yDEBUG&r) &c> ", false); var cmd = Console.ReadLine(); if (!consoleCommandsHandler.HandleCommand(cmd! #if DEBUG @@ -149,6 +149,14 @@ public class Program Console_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.ContainsKey("LaunchMessage")) + { + Console_Utilities.WriteColorText(Config.GetValue("LaunchMessage")); + Config.RemoveKey("LaunchMessage"); + } + + Console_Utilities.WriteColorText("Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); Console.WriteLine($"============================ LOG ============================"); try @@ -243,7 +251,26 @@ public class Program if (len == 0 || (args[0] != "--exec" && args[0] != "--execute")) { - Thread mainThread = new Thread(() => NoGUI(b)); + + Thread mainThread = new Thread(() => + { + try + { + NoGUI(b); + } + catch (IOException ex) + { + if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) + { + if (!Config.ContainsKey("LaunchMessage")) + Config.AddValueToVariables("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); + Functions.WriteErrFile(ex.ToString()); + } + } + + + + }); mainThread.Start(); return; } @@ -377,6 +404,6 @@ public class Program Console_Utilities.Initialize(); - Config.SaveConfig(); + Config.SaveConfig(SaveType.NORMAL); } } diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index 9d6d630..881ca8d 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -13,8 +13,7 @@ namespace PluginManager { public Dictionary? ApplicationVariables { get; init; } public List? ProtectedKeyWords { get; init; } - - public Dictionary PluginVersions { get; init; } + public Dictionary? PluginVersions { get; init; } } public static class Config @@ -59,9 +58,8 @@ namespace PluginManager public static bool Contains(string pluginName) { foreach (var tuple in InstalledPlugins) - { - if (tuple.Item1 == pluginName) return true; - } + if (tuple.Item1 == pluginName) + return true; return false; } @@ -79,18 +77,18 @@ namespace PluginManager private static AppConfig? appConfig { get; set; } - public static string GetPluginVersion(string pluginName) => appConfig.PluginVersions[pluginName]; + public static string GetPluginVersion(string pluginName) => appConfig!.PluginVersions![pluginName]; public static void SetPluginVersion(string pluginName, string newVersion) { - if (appConfig.PluginVersions.ContainsKey(pluginName)) + if (appConfig!.PluginVersions!.ContainsKey(pluginName)) appConfig.PluginVersions[pluginName] = newVersion; else appConfig.PluginVersions.Add(pluginName, newVersion); // SaveConfig(); } - public static void RemovePluginVersion(string pluginName) => appConfig.PluginVersions.Remove(pluginName); - public static bool PluginVersionsContainsKey(string pluginName) => appConfig.PluginVersions.ContainsKey(pluginName); + public static void RemovePluginVersion(string pluginName) => appConfig!.PluginVersions!.Remove(pluginName); + public static bool PluginVersionsContainsKey(string pluginName) => appConfig!.PluginVersions!.ContainsKey(pluginName); public static void AddValueToVariables(string key, T value, bool isProtected) { @@ -103,7 +101,7 @@ namespace PluginManager if (isProtected && key != "Version") appConfig.ProtectedKeyWords!.Add(key); - SaveConfig(); + SaveConfig(SaveType.NORMAL); } public static Type GetVariableType(string value) @@ -171,7 +169,7 @@ namespace PluginManager throw new Exception("Key is protected"); appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value); - SaveConfig(); + SaveConfig(SaveType.NORMAL); } public static void RemoveKey(string key) @@ -180,13 +178,24 @@ namespace PluginManager throw new Exception("Key is protected"); appConfig!.ApplicationVariables!.Remove(key); appConfig.ProtectedKeyWords!.Remove(key); - SaveConfig(); + SaveConfig(SaveType.NORMAL); } - public static async void SaveConfig() + public static async void SaveConfig(SaveType type) { - string path = Functions.dataFolder + "config.json"; - await Functions.SaveToJsonFile(path, appConfig!); + if (type == SaveType.NORMAL) + { + string path = Functions.dataFolder + "config.json"; + await Functions.SaveToJsonFile(path, appConfig!); + return; + } + if (type == SaveType.BACKUP) + { + string path = Functions.dataFolder + "config.json.bak"; + await Functions.SaveToJsonFile(path, appConfig!); + return; + } + } public static async Task LoadConfig() @@ -194,11 +203,24 @@ namespace PluginManager string path = Functions.dataFolder + "config.json"; if (File.Exists(path)) { - appConfig = await Functions.ConvertFromJson(path); + try + { + appConfig = await Functions.ConvertFromJson(path); + } + catch (Exception ex) + { + File.Delete(path); + Console.WriteLine("An error occured while loading the settings. Importing from backup file..."); + path = Functions.dataFolder + "config.json.bak"; + appConfig = await Functions.ConvertFromJson(path); + Functions.WriteErrFile(ex.Message); + } + + Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables!.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords!.Count} readonly variables."); + return; } - else - appConfig = new() { ApplicationVariables = new Dictionary(), ProtectedKeyWords = new List(), PluginVersions = new Dictionary() }; + appConfig = new() { ApplicationVariables = new Dictionary(), ProtectedKeyWords = new List(), PluginVersions = new Dictionary() }; } public static bool ContainsValue(T value) => appConfig!.ApplicationVariables!.ContainsValue(value!); diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 3c93b76..2532636 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -261,7 +261,8 @@ public class ConsoleCommandsHandler return; client.StopAsync(); client.DisposeAsync(); - Config.SaveConfig(); + Config.SaveConfig(SaveType.NORMAL); + Config.SaveConfig(SaveType.BACKUP); Console.WriteLine("Bot is closing in 2 seconds ! Please wait to save data !"); Thread.Sleep(2000); Environment.Exit(0); @@ -307,7 +308,7 @@ public class ConsoleCommandsHandler { if (Functions.GetOperatingSystem() == Others.OperatingSystem.WINDOWS) { - Process.Start("DiscordBot.exe ", $"/remplug {plugName}"); + Process.Start("DiscordBot.exe", $"/remplug {plugName}"); await Task.Delay(100); Environment.Exit(0); } @@ -345,7 +346,7 @@ public class ConsoleCommandsHandler Console.WriteLine("Found: " + tuple.ToString()); Config.PluginConfig.InstalledPlugins.Remove(tuple); Config.RemovePluginVersion(plugName); - Config.SaveConfig(); + Config.SaveConfig(SaveType.NORMAL); } Console.WriteLine("Removed the plugin DLL. Checking for other files ..."); @@ -374,6 +375,21 @@ public class ConsoleCommandsHandler }); + AddCommand("reload", "Reload the bot with all plugins", () => + { + if (Functions.GetOperatingSystem() == Others.OperatingSystem.WINDOWS) + { + Process.Start("DiscordBot.exe", $"lp"); + HandleCommand("sd"); + } + else + { + + Process.Start("./DiscordBot", $"lp"); + HandleCommand("sd"); + } + }); + //Sort the commands by name commandList.Sort((x, y) => x.CommandName.CompareTo(y.CommandName)); } diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index ad5b796..0f20fb8 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -94,7 +94,7 @@ public class PluginLoader //Save the new config file (after the updates) - Config.SaveConfig(); + Config.SaveConfig(SaveType.NORMAL); //Load all plugins diff --git a/PluginManager/Online/Helpers/VersionString.cs b/PluginManager/Online/Helpers/VersionString.cs index 0cbafbf..1cf9732 100644 --- a/PluginManager/Online/Helpers/VersionString.cs +++ b/PluginManager/Online/Helpers/VersionString.cs @@ -37,6 +37,7 @@ namespace PluginManager.Online.Helpers return false; } + #region operators public static bool operator <(VersionString s1, VersionString s2) => !(s1 > s2) && s1 != s2; public static bool operator ==(VersionString s1, VersionString s2) @@ -50,6 +51,8 @@ namespace PluginManager.Online.Helpers public static bool operator <=(VersionString s1, VersionString s2) => (s1 < s2 || s1 == s2); public static bool operator >=(VersionString s1, VersionString s2) => (s1 > s2 || s1 == s2); + #endregion + public override string ToString() { return "{PackageID: " + PackageID + ", PackageVersion: " + PackageMainVersion + ", PackageCheckVersion: " + PackageCheckVersion + "}"; diff --git a/PluginManager/Others/Enums.cs b/PluginManager/Others/Enums.cs index 322230d..e1e3f77 100644 --- a/PluginManager/Others/Enums.cs +++ b/PluginManager/Others/Enums.cs @@ -30,4 +30,6 @@ public enum PluginType { Command, Event, Unknown } public enum UnzipProgressType { PercentageFromNumberOfFiles, PercentageFromTotalSize } -public enum TableFormat { CENTER_EACH_COLUMN_BASED, CENTER_OVERALL_LENGTH, DEFAULT } \ No newline at end of file +public enum TableFormat { CENTER_EACH_COLUMN_BASED, CENTER_OVERALL_LENGTH, DEFAULT } + +public enum SaveType { NORMAL, BACKUP } \ No newline at end of file diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index a99bc7f..8b17397 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -261,10 +261,9 @@ namespace PluginManager.Others /// public static async Task SaveToJsonFile(string file, T Data) { - File.Delete(file); - var s = File.Open(file, FileMode.OpenOrCreate); - await JsonSerializer.SerializeAsync(s, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); - s.Close(); + MemoryStream str = new MemoryStream(); + await JsonSerializer.SerializeAsync(str, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); + await File.WriteAllBytesAsync(file, str.ToArray()); } /// @@ -277,8 +276,7 @@ namespace PluginManager.Others { Stream text; if (File.Exists(input)) - text = File.OpenRead(input); - + text = new MemoryStream(await File.ReadAllBytesAsync(input)); else text = new MemoryStream(Encoding.ASCII.GetBytes(input)); text.Position = 0;