diff --git a/DiscordBot/Bot/Actions/Clear.cs b/DiscordBot/Bot/Actions/Clear.cs index b024c75..fa6674e 100644 --- a/DiscordBot/Bot/Actions/Clear.cs +++ b/DiscordBot/Bot/Actions/Clear.cs @@ -11,7 +11,7 @@ public class Clear : ICommandAction public string Description => "Clears the console"; public string Usage => "clear"; public InternalActionRunType RunType => InternalActionRunType.ON_CALL; - + public Task Execute(string[] args) { Console.Clear(); diff --git a/DiscordBot/Bot/Actions/Exit.cs b/DiscordBot/Bot/Actions/Exit.cs index 922b2b1..f01014a 100644 --- a/DiscordBot/Bot/Actions/Exit.cs +++ b/DiscordBot/Bot/Actions/Exit.cs @@ -17,21 +17,21 @@ public class Exit : ICommandAction { if (args is null || args.Length == 0) { - Config.Logger.Log("Exiting...", "Exit", isInternal:false); - await Config.Data.Save(); + Config.Logger.Log("Exiting...", "Exit", isInternal: false); + await Config.AppSettings.SaveToFile(); await Config.Logger.SaveToFile(); Environment.Exit(0); } else { - switch (args[0]) + switch ( args[0] ) { case "help": Console.WriteLine("Usage : exit [help|force]"); Console.WriteLine("help : Displays this message"); Console.WriteLine("force | -f : Exits the bot without saving the config"); break; - + case "-f": case "force": Config.Logger.Log("Exiting (FORCE)...", "Exit", LogLevel.WARNING, false); diff --git a/DiscordBot/Bot/Actions/Help.cs b/DiscordBot/Bot/Actions/Help.cs index efcb4e2..849d2e3 100644 --- a/DiscordBot/Bot/Actions/Help.cs +++ b/DiscordBot/Bot/Actions/Help.cs @@ -34,7 +34,8 @@ public class Help : ICommandAction items.Add(new[] { "-", "-", "-" }); Utilities.Utilities.FormatAndAlignTable(items, - TableFormat.CENTER_EACH_COLUMN_BASED); + TableFormat.CENTER_EACH_COLUMN_BASED + ); return; } @@ -55,6 +56,7 @@ public class Help : ICommandAction }; Utilities.Utilities.FormatAndAlignTable(actionData, - TableFormat.CENTER_EACH_COLUMN_BASED); + TableFormat.CENTER_EACH_COLUMN_BASED + ); } } diff --git a/DiscordBot/Bot/Actions/Plugin.cs b/DiscordBot/Bot/Actions/Plugin.cs index 52bdb23..8804fd8 100644 --- a/DiscordBot/Bot/Actions/Plugin.cs +++ b/DiscordBot/Bot/Actions/Plugin.cs @@ -31,7 +31,7 @@ public class Plugin : ICommandAction return; } - switch (args[0]) + switch ( args[0] ) { case "list": var manager = @@ -75,7 +75,8 @@ public class Plugin : ICommandAction Console.WriteLine("An error occured while loading: " + name); else Console.WriteLine("[CMD] Failed to load command : " + name + " because " + - exception!.Message); + exception!.Message + ); } Console.ForegroundColor = cc; @@ -113,7 +114,8 @@ public class Plugin : ICommandAction { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[SLASH] Failed to load command : " + name + " because " + - exception!.Message); + exception!.Message + ); } Console.ForegroundColor = cc; @@ -156,7 +158,7 @@ public class Plugin : ICommandAction //download plugin progress bar for linux and windows terminals var spinner = new Utilities.Utilities.Spinner(); spinner.Start(); - IProgress progress = new Progress(p => { spinner.Message = $"Downloading {pluginName}... {Math.Round(p,2)}% " ; }); + IProgress progress = new Progress(p => { spinner.Message = $"Downloading {pluginName}... {Math.Round(p, 2)}% "; }); await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress); spinner.Stop(); Console.WriteLine(); diff --git a/DiscordBot/Bot/Commands/NormalCommands/Help.cs b/DiscordBot/Bot/Commands/NormalCommands/Help.cs index d472837..0fa3256 100644 --- a/DiscordBot/Bot/Commands/NormalCommands/Help.cs +++ b/DiscordBot/Bot/Commands/NormalCommands/Help.cs @@ -75,10 +75,11 @@ internal class Help : DBCommand { var embedBuilder = new EmbedBuilder(); var cmd = PluginLoader.Commands.Find(p => p.Command == command || - (p.Aliases is not null && p.Aliases.Contains(command))); + p.Aliases is not null && p.Aliases.Contains(command) + ); if (cmd == null) return null; - embedBuilder.AddField("Usage", Config.Data["prefix"] + cmd.Usage); + embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); embedBuilder.AddField("Description", cmd.Description); if (cmd.Aliases is null) return embedBuilder; diff --git a/DiscordBot/DiscordBot.csproj b/DiscordBot/DiscordBot.csproj index ed95d3b..a3ef8e7 100644 --- a/DiscordBot/DiscordBot.csproj +++ b/DiscordBot/DiscordBot.csproj @@ -3,8 +3,8 @@ Exe net6.0 disable - - + + False True 1.0.2.2 @@ -16,25 +16,25 @@ none - - - + + + - - - + + + - - - + + + - - + + - + \ No newline at end of file diff --git a/DiscordBot/Entry.cs b/DiscordBot/Entry.cs index d5df92f..3f553c0 100644 --- a/DiscordBot/Entry.cs +++ b/DiscordBot/Entry.cs @@ -14,7 +14,8 @@ public class Entry static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) { var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), - "./Libraries"); + "./Libraries" + ); var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll"); if (!File.Exists(assemblyPath)) return null; var assembly = Assembly.LoadFrom(assemblyPath); diff --git a/DiscordBot/Installer.cs b/DiscordBot/Installer.cs index 62c5b01..7a9e87e 100644 --- a/DiscordBot/Installer.cs +++ b/DiscordBot/Installer.cs @@ -15,30 +15,30 @@ public static class Installer Console.WriteLine("The following information will be stored in the config.json file in the ./Data/Resources folder. You can change it later from there."); Console.WriteLine("The bot token is required to run the bot. You can get it from the Discord Developer Portal. (https://discord.com/developers/applications)"); - if (!Config.Data.ContainsKey("token")) + if (!Config.AppSettings.ContainsKey("token")) { Console.WriteLine("Please enter the bot token :"); var token = Console.ReadLine(); - Config.Data.Add("token", token); + Config.AppSettings.Add("token", token); } - if (!Config.Data.ContainsKey("prefix")) + if (!Config.AppSettings.ContainsKey("prefix")) { Console.WriteLine("Please enter the bot prefix :"); var prefix = Console.ReadLine(); - Config.Data.Add("prefix", prefix); + Config.AppSettings.Add("prefix", prefix); } - if (!Config.Data.ContainsKey("ServerID")) + if (!Config.AppSettings.ContainsKey("ServerID")) { Console.WriteLine("Please enter the Server ID :"); var serverId = Console.ReadLine(); - Config.Data.Add("ServerID", serverId); + Config.AppSettings.Add("ServerID", serverId); } - Config.Logger.Log("Config Saved", "Installer", isInternal:true); + Config.Logger.Log("Config Saved", "Installer", isInternal: true); - Config.Data.Save(); + Config.AppSettings.SaveToFile(); Console.WriteLine("Config saved !"); } @@ -94,7 +94,8 @@ public static class Installer ""LinuxBot"": """", ""WindowsLauncher"": """", } - ".Replace(" ", "")); + ".Replace(" ", "") + ); Environment.Exit(0); } } diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index a1ef889..dfe87e6 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -15,8 +15,8 @@ namespace DiscordBot; public class Program { - public static Json URLs; - public static InternalActionManager internalActionManager; + public static SettingsDictionary URLs; + public static InternalActionManager internalActionManager; /// /// The main entry point for the application. @@ -26,12 +26,12 @@ public class Program { PreLoadComponents(args).Wait(); - if (!Data.ContainsKey("ServerID") || !Data.ContainsKey("token") || - Data["token"] == null || - (Data["token"]?.Length != 70 && Data["token"]?.Length != 59) || - !Data.ContainsKey("prefix") || Data["prefix"] == null || - Data["prefix"]?.Length != 1 || - (args.Length == 1 && args[0] == "/reset")) + if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || + AppSettings["token"] == null || + AppSettings["token"]?.Length != 70 && AppSettings["token"]?.Length != 59 || + !AppSettings.ContainsKey("prefix") || AppSettings["prefix"] == null || + AppSettings["prefix"]?.Length != 1 || + args.Length == 1 && args[0] == "/reset") Installer.GenerateStartupConfig(); HandleInput(args.ToList()).Wait(); @@ -49,9 +49,9 @@ public class Program while (true) { - string cmd = Console.ReadLine(); - string[] args = cmd.Split(' '); - string command = args[0]; + var cmd = Console.ReadLine(); + var args = cmd.Split(' '); + var command = args[0]; args = args.Skip(1).ToArray(); if (args.Length == 0) args = null; @@ -76,19 +76,22 @@ public class Program Console.WriteLine(message); Console.WriteLine( - $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); - Console.WriteLine($"Git URL: {Data["GitURL"]}"); + $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}" + ); + Console.WriteLine($"Git URL: {AppSettings["GitURL"]}"); Utilities.Utilities.WriteColorText( - "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); + "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n" + ); Console.ForegroundColor = ConsoleColor.White; - if (Data.ContainsKey("LaunchMessage")) - Utilities.Utilities.WriteColorText(Data["LaunchMessage"]); + if (AppSettings.ContainsKey("LaunchMessage")) + Utilities.Utilities.WriteColorText(AppSettings["LaunchMessage"]); Utilities.Utilities.WriteColorText( - "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); + "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)" + ); Console.WriteLine("Running on " + Functions.GetOperatingSystem()); Console.WriteLine("============================ LOG ============================"); @@ -98,16 +101,16 @@ public class Program var token = ""; #if DEBUG if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt"); - else token = Data["token"]; + else token = AppSettings["token"]; #else token = Config.Data["token"]; #endif - var prefix = Data["prefix"]; + var prefix = AppSettings["prefix"]; var discordbooter = new Boot(token, prefix); await discordbooter.Awake(); return discordbooter; } - catch (Exception ex) + catch ( Exception ex ) { Logger.Log(ex.ToString(), "Bot", LogLevel.ERROR); return null; @@ -141,16 +144,18 @@ public class Program NoGUI(); } - catch (IOException ex) + catch ( IOException ex ) { if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) { - if (Data.ContainsKey("LaunchMessage")) - 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 !"); + if (AppSettings.ContainsKey("LaunchMessage")) + AppSettings.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 .Log("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 !", - "Bot", LogLevel.ERROR); + "Bot", LogLevel.ERROR + ); } } } @@ -163,7 +168,9 @@ public class Program await Installer.SetupPluginDatabase(); - URLs = new Json("./Data/Resources/URLs.json"); + URLs = new SettingsDictionary("./Data/Resources/URLs.json"); + + File.WriteAllText("temp.txt", string.Join(" ", URLs.Keys)); Logger.LogEvent += (message, type, isInternal) => { @@ -174,28 +181,25 @@ public class Program Console.ForegroundColor = ConsoleColor.DarkYellow; else if (type == LogLevel.ERROR) Console.ForegroundColor = ConsoleColor.Red; - else if(type == LogLevel.CRITICAL) + else if (type == LogLevel.CRITICAL) Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine($"[{type.ToString()}] {message}"); Console.ResetColor(); - - - }; Console.WriteLine("Loading resources ..."); - if (Data.ContainsKey("DeleteLogsAtStartup")) - if (Data["DeleteLogsAtStartup"] == "true") + if (AppSettings.ContainsKey("DeleteLogsAtStartup")) + if (AppSettings["DeleteLogsAtStartup"] == "true") foreach (var file in Directory.GetFiles("./Output/Logs/")) File.Delete(file); - var OnlineDefaultKeys = - await ServerCom.ReadTextFromURL(URLs["SetupKeys"]); + + var OnlineDefaultKeys = await ServerCom.ReadTextFromURL(URLs["SetupKeys"]); - Data["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); foreach (var key in OnlineDefaultKeys) { @@ -203,9 +207,9 @@ public class Program var s = key.Split(' '); try { - Data[s[0]] = s[1]; + AppSettings[s[0]] = s[1]; } - catch (Exception ex) + catch ( Exception ex ) { Logger.Log(ex.ToString(), "Bot", LogLevel.ERROR); } @@ -218,10 +222,10 @@ public class Program if (key.Length <= 3 || !key.Contains(' ')) continue; var s = key.Split(' '); - switch (s[0]) + switch ( s[0] ) { case "CurrentVersion": - var currentVersion = Data["Version"]; + var currentVersion = AppSettings["Version"]; var newVersion = s[1]; if (new VersionString(newVersion) != new VersionString(newVersion)) { diff --git a/DiscordBot/Utilities/Console Utilities.cs b/DiscordBot/Utilities/Console Utilities.cs index c7f5ba4..124a9d4 100644 --- a/DiscordBot/Utilities/Console Utilities.cs +++ b/DiscordBot/Utilities/Console Utilities.cs @@ -203,9 +203,9 @@ public static class Utilities { private readonly string[] Sequence; private bool isRunning; + public string Message; private int position; private Thread thread; - public string Message; public Spinner() { @@ -218,17 +218,18 @@ public static class Utilities Console.CursorVisible = false; isRunning = true; thread = new Thread(() => - { - while (isRunning) - { - Console.SetCursorPosition(0, Console.CursorTop); - Console.Write(" " + Sequence[position] + " " + Message + " "); - position++; - if (position >= Sequence.Length) - position = 0; - Thread.Sleep(100); - } - }); + { + while (isRunning) + { + Console.SetCursorPosition(0, Console.CursorTop); + Console.Write(" " + Sequence[position] + " " + Message + " "); + position++; + if (position >= Sequence.Length) + position = 0; + Thread.Sleep(100); + } + } + ); thread.Start(); } diff --git a/PluginManager/Bot/Boot.cs b/PluginManager/Bot/Boot.cs index 4e432af..28fd187 100644 --- a/PluginManager/Bot/Boot.cs +++ b/PluginManager/Bot/Boot.cs @@ -107,10 +107,10 @@ public class Boot { if (arg.Message.Contains("401")) { - Config.Data.Remove("token"); + Config.AppSettings.Remove("token"); Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", this, LogLevel.ERROR); - Config.Data.Save(); + await Config.AppSettings.SaveToFile(); await Task.Delay(4000); Environment.Exit(0); } diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index fd7d0f6..f3b31c4 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; +using System.IO; using System.Threading.Tasks; using PluginManager.Bot; using PluginManager.Others; @@ -13,8 +10,7 @@ public class Config { private static bool IsLoaded; public static DBLogger Logger; - public static Json? Data; - // public static Json? Plugins; + public static SettingsDictionary? AppSettings; internal static Boot? _DiscordBotClient; @@ -22,8 +18,7 @@ public class Config public static async Task Initialize() { - if (IsLoaded) - return; + if (IsLoaded) return; Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Plugins"); @@ -31,11 +26,10 @@ public class Config Directory.CreateDirectory("./Data/Logs/Logs"); Directory.CreateDirectory("./Data/Logs/Errors"); - Data = new Json("./Data/Resources/config.json"); - // Plugins = new Json("./Data/Resources/Plugins.json"); + AppSettings = new SettingsDictionary("./Data/Resources/config.json"); - Data["LogFolder"] = "./Data/Logs/Logs"; - Data["ErrorFolder"] = "./Data/Logs/Errors"; + AppSettings["LogFolder"] = "./Data/Logs/Logs"; + AppSettings["ErrorFolder"] = "./Data/Logs/Errors"; Logger = new DBLogger(); @@ -45,129 +39,5 @@ public class Config Logger.Log("Config initialized", LogLevel.INFO); } - - public class Json : IDictionary - { - private readonly string _file = ""; - private readonly IDictionary? _dictionary; - - public Json(string file) - { - if (file is null) throw new FileLoadException("The file can not be null"); - if(!File.Exists(file)) - File.Create(file).Close(); - - _dictionary = PrivateReadConfig(file).GetAwaiter().GetResult(); - _file = file; - } - - public virtual void Add(TKey key, TValue value) - { - _dictionary.Add(key, value); - } - - public void Clear() { _dictionary.Clear(); } - - public bool ContainsKey(TKey key) - { - if (_dictionary == null) - throw new Exception("Dictionary is null"); - - return _dictionary.ContainsKey(key); - } - - public virtual ICollection Keys => _dictionary.Keys; - - public virtual ICollection Values => _dictionary.Values; - - public int Count => _dictionary.Count; - - public bool IsReadOnly => _dictionary.IsReadOnly; - - public virtual TValue this[TKey key] - { - get - { - if (_dictionary.TryGetValue(key, out var value)) return value; - throw new Exception("Key not found in dictionary " + key + " (Json )" + GetType().Name + - ")"); - } - set - { - if (_dictionary.ContainsKey(key)) - _dictionary[key] = value; - else _dictionary.Add(key, value); - } - } - - public virtual bool TryGetValue(TKey key, out TValue value) - { - return _dictionary.TryGetValue(key, out value); - } - - 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 async Task Save() - { - if (!string.IsNullOrEmpty(_file)) - await Functions.SaveToJsonFile(_file, _dictionary); - } - - private async Task> PrivateReadConfig(string file) - { - if (!File.Exists(file)) - { - var dictionary = new Dictionary(); - await Functions.SaveToJsonFile(file, _dictionary); - return dictionary; - } - - try - { - var d = await Functions.ConvertFromJson>(file); - if (d is null) - throw new Exception("Failed to read config file"); - - return d; - } - catch (Exception ex) - { - File.Delete(file); - return new Dictionary(); - } - } - } + } diff --git a/PluginManager/Database/SqlDatabase.cs b/PluginManager/Database/SqlDatabase.cs index ce47e86..43289a4 100644 --- a/PluginManager/Database/SqlDatabase.cs +++ b/PluginManager/Database/SqlDatabase.cs @@ -10,7 +10,6 @@ namespace PluginManager.Database; public class SqlDatabase { private readonly SQLiteConnection Connection; - private readonly string ConnectionString; /// /// Initialize a SQL connection by specifing its private path @@ -22,8 +21,8 @@ public class SqlDatabase fileName = Path.Combine("./Data/Resources", fileName); if (!File.Exists(fileName)) SQLiteConnection.CreateFile(fileName); - ConnectionString = $"URI=file:{fileName}"; - Connection = new SQLiteConnection(ConnectionString); + var connectionString = $"URI=file:{fileName}"; + Connection = new SQLiteConnection(connectionString); } diff --git a/PluginManager/Others/ArchiveManager.cs b/PluginManager/Others/ArchiveManager.cs index 89fa858..d08e7e6 100644 --- a/PluginManager/Others/ArchiveManager.cs +++ b/PluginManager/Others/ArchiveManager.cs @@ -16,10 +16,10 @@ public static class ArchiveManager { if (isInitialized) throw new Exception("ArchiveManager is already initialized"); - if (!Config.Data.ContainsKey("ArchiveFolder")) - Config.Data["ArchiveFolder"] = "./Data/PAKS/"; + if (!Config.AppSettings.ContainsKey("ArchiveFolder")) + Config.AppSettings["ArchiveFolder"] = "./Data/PAKS/"; - archiveFolder = Config.Data["ArchiveFolder"]; + archiveFolder = Config.AppSettings["ArchiveFolder"]; isInitialized = true; } diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 4a3d8db..64503b3 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -76,42 +76,7 @@ public static class Functions progress?.Report(totalBytesRead); } } - - /// - /// Save to JSON file - /// - /// The class type - /// The file path - /// The values - /// - public static async Task SaveToJsonFile(string file, T Data) - { - var str = new MemoryStream(); - await JsonSerializer.SerializeAsync(str, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); - await File.WriteAllBytesAsync(file, str.ToArray()); - await str.FlushAsync(); - str.Close(); - } - - /// - /// Convert json text or file to some kind of data - /// - /// The data type - /// The file or json text - /// - public static async Task ConvertFromJson(string input) - { - Stream text; - if (File.Exists(input)) - text = new MemoryStream(await File.ReadAllBytesAsync(input)); - else - text = new MemoryStream(Encoding.ASCII.GetBytes(input)); - text.Position = 0; - var obj = await JsonSerializer.DeserializeAsync(text); - await text.FlushAsync(); - text.Close(); - return (obj ?? default)!; - } + public static T SelectRandomValueOf() { diff --git a/PluginManager/Others/JsonManager.cs b/PluginManager/Others/JsonManager.cs new file mode 100644 index 0000000..ea3576a --- /dev/null +++ b/PluginManager/Others/JsonManager.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace PluginManager; + +public class JsonManager +{ + /// + /// Save to JSON file + /// + /// The class type + /// The file path + /// The values + /// + public static async Task SaveToJsonFile(string file, T Data) + { + var str = new MemoryStream(); + await JsonSerializer.SerializeAsync(str, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); + await File.WriteAllBytesAsync(file, str.ToArray()); + await str.FlushAsync(); + str.Close(); + } + + /// + /// Convert json text or file to some kind of data + /// + /// The data type + /// The file or json text + /// + public static async Task ConvertFromJson(string input) + { + Console.WriteLine(input); + Stream text; + if (File.Exists(input)) + text = new MemoryStream(await File.ReadAllBytesAsync(input)); + else + text = new MemoryStream(Encoding.ASCII.GetBytes(input)); + text.Position = 0; + var obj = await JsonSerializer.DeserializeAsync(text); + await text.FlushAsync(); + text.Close(); + return (obj ?? default)!; + } +} \ No newline at end of file diff --git a/PluginManager/Others/Logger/DBLogger.cs b/PluginManager/Others/Logger/DBLogger.cs index 0e92308..bfd3977 100644 --- a/PluginManager/Others/Logger/DBLogger.cs +++ b/PluginManager/Others/Logger/DBLogger.cs @@ -16,8 +16,8 @@ public class DBLogger public DBLogger() { - _logFolder = Config.Data["LogFolder"]; - _errFolder = Config.Data["ErrorFolder"]; + _logFolder = Config.AppSettings["LogFolder"]; + _errFolder = Config.AppSettings["ErrorFolder"]; } public IReadOnlyList Logs => LogHistory; @@ -69,9 +69,9 @@ public class DBLogger public async Task SaveToFile(bool ErrorsOnly = true) { if(!ErrorsOnly) - await Functions.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", + await JsonManager.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", LogHistory); - await Functions.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", + await JsonManager.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", ErrorHistory); } } diff --git a/PluginManager/Others/SettingsDictionary.cs b/PluginManager/Others/SettingsDictionary.cs new file mode 100644 index 0000000..faac195 --- /dev/null +++ b/PluginManager/Others/SettingsDictionary.cs @@ -0,0 +1,102 @@ +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; + +namespace PluginManager.Others; + +public class SettingsDictionary : IDictionary +{ + public string _file { get; set; } + private IDictionary? _dictionary; + + public SettingsDictionary(string file) + { + if (file is null) + throw new FileLoadException("The file can not be null"); + + if (!File.Exists(file)) + File.Create(file).Close(); + + _file = file; + LoadFromFile(); + } + + public async Task SaveToFile() + { + if (!string.IsNullOrEmpty(_file)) + await JsonManager.SaveToJsonFile(_file, _dictionary); + } + + private void LoadFromFile() + { + if (!string.IsNullOrEmpty(_file)) + _dictionary = JsonManager.ConvertFromJson>(_file).Result; + } + + public IEnumerator> GetEnumerator() + { + return _dictionary!.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) _dictionary!).GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + this._dictionary!.Add(item); + } + + public void Clear() + { + this._dictionary!.Clear(); + } + + public bool Contains(KeyValuePair item) + { + return this._dictionary!.Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + this._dictionary!.CopyTo(array, arrayIndex); + } + + public bool Remove(KeyValuePair item) + { + return this._dictionary!.Remove(item); + } + + public int Count => _dictionary!.Count; + public bool IsReadOnly => _dictionary!.IsReadOnly; + public void Add(TKey key, TValue value) + { + this._dictionary!.Add(key, value); + } + + public bool ContainsKey(TKey key) + { + return this._dictionary!.ContainsKey(key); + } + + public bool Remove(TKey key) + { + return this._dictionary!.Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + return this._dictionary!.TryGetValue(key, out value); + } + + public TValue this[TKey key] + { + get => this._dictionary![key]; + set => this._dictionary![key] = value; + } + + public ICollection Keys => _dictionary!.Keys; + public ICollection Values => _dictionary!.Values; +} \ No newline at end of file