improved save method

This commit is contained in:
2022-08-20 17:44:19 +03:00
parent 3ba45790e7
commit 6da9828e5c
7 changed files with 101 additions and 33 deletions

View File

@@ -115,7 +115,7 @@ 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);
@@ -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<string>("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);
}
}

View File

@@ -13,8 +13,7 @@ namespace PluginManager
{
public Dictionary<string, object>? ApplicationVariables { get; init; }
public List<string>? ProtectedKeyWords { get; init; }
public Dictionary<string, string> PluginVersions { get; init; }
public Dictionary<string, string>? 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<T>(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,24 +178,48 @@ 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)
{
if (type == SaveType.NORMAL)
{
string path = Functions.dataFolder + "config.json";
await Functions.SaveToJsonFile<AppConfig>(path, appConfig!);
return;
}
if (type == SaveType.BACKUP)
{
string path = Functions.dataFolder + "config.json.bak";
await Functions.SaveToJsonFile<AppConfig>(path, appConfig!);
return;
}
}
public static async Task LoadConfig()
{
string path = Functions.dataFolder + "config.json";
if (File.Exists(path))
{
try
{
appConfig = await Functions.ConvertFromJson<AppConfig>(path);
Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables!.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords!.Count} readonly variables.");
}
else
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<AppConfig>(path);
Functions.WriteErrFile(ex.Message);
}
Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables!.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords!.Count} readonly variables.");
return;
}
appConfig = new() { ApplicationVariables = new Dictionary<string, object>(), ProtectedKeyWords = new List<string>(), PluginVersions = new Dictionary<string, string>() };
}

View File

@@ -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);
@@ -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));
}

View File

@@ -94,7 +94,7 @@ public class PluginLoader
//Save the new config file (after the updates)
Config.SaveConfig();
Config.SaveConfig(SaveType.NORMAL);
//Load all plugins

View File

@@ -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 + "}";

View File

@@ -31,3 +31,5 @@ public enum PluginType { Command, Event, Unknown }
public enum UnzipProgressType { PercentageFromNumberOfFiles, PercentageFromTotalSize }
public enum TableFormat { CENTER_EACH_COLUMN_BASED, CENTER_OVERALL_LENGTH, DEFAULT }
public enum SaveType { NORMAL, BACKUP }

View File

@@ -261,10 +261,9 @@ namespace PluginManager.Others
/// <returns></returns>
public static async Task SaveToJsonFile<T>(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());
}
/// <summary>
@@ -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;