changed to .json file instead of database for settings

This commit is contained in:
2023-03-24 21:52:03 +02:00
parent 7e2fa02d07
commit 460a85944a
15 changed files with 207 additions and 312 deletions

1
.gitignore vendored
View File

@@ -373,3 +373,4 @@ FodyWeavers.xsd
/DiscordBot/Updater/ /DiscordBot/Updater/
.vscode/ .vscode/
.idea/ .idea/
/DiscordBotWeb/

View File

@@ -1,6 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using Discord; using Discord;
using PluginManager; using PluginManager;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Loaders; using PluginManager.Loaders;
@@ -79,7 +80,7 @@ internal class Help : DBCommand
(p.Aliases is not null && p.Aliases.Contains(command))); (p.Aliases is not null && p.Aliases.Contains(command)));
if (cmd == null) return null; 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); embedBuilder.AddField("Description", cmd.Description);
if (cmd.Aliases is null) if (cmd.Aliases is null)
return embedBuilder; return embedBuilder;

View File

@@ -1,4 +1,5 @@
using PluginManager.Others; using PluginManager.Others;
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -10,7 +11,6 @@ namespace DiscordBot
public class Entry public class Entry
{ {
internal static StartupArguments startupArguments;
public static void Main(string[] args) public static void Main(string[] args)
{ {
AppDomain currentDomain = AppDomain.CurrentDomain; AppDomain currentDomain = AppDomain.CurrentDomain;

View File

@@ -31,13 +31,14 @@ public class Program
[STAThread] [STAThread]
public static void Startup(string[] args) public static void Startup(string[] args)
{ {
PreLoadComponents(args).Wait(); PreLoadComponents(args).Wait();
if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") || if (!Config.Data.ContainsKey("ServerID") || !Config.Data.ContainsKey("token") ||
Config.Variables.GetValue("token") == null || Config.Data["token"] == null ||
(Config.Variables.GetValue("token")?.Length != 70 && Config.Variables.GetValue("token")?.Length != 59) || (Config.Data["token"]?.Length != 70 && Config.Data["token"]?.Length != 59) ||
!Config.Variables.Exists("prefix") || Config.Variables.GetValue("prefix") == null || !Config.Data.ContainsKey("prefix") || Config.Data["prefix"] == null ||
Config.Variables.GetValue("prefix")?.Length != 1 || Config.Data["prefix"]?.Length != 1 ||
(args.Length == 1 && args[0] == "/reset")) (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."); GenerateStartUI("First time setup. Please fill the following with your discord bot data.\nThis are saved ONLY on YOUR computer.");
@@ -91,14 +92,14 @@ public class Program
Logger.WriteLine( Logger.WriteLine(
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Logger.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}");
Utilities.WriteColorText( 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; Console.ForegroundColor = ConsoleColor.White;
if (Config.Variables.Exists("LaunchMessage")) if (Config.Data.ContainsKey("LaunchMessage"))
Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage")); Utilities.WriteColorText(Config.Data["LaunchMessage"]);
Utilities.WriteColorText( Utilities.WriteColorText(
@@ -113,11 +114,11 @@ public class Program
string token = ""; string token = "";
#if DEBUG #if DEBUG
if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt"); 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 #else
token = Config.Variables.GetValue("token"); token = Config.Data["token"];
#endif #endif
var prefix = Config.Variables.GetValue("prefix"); var prefix = Config.Data["prefix"];
var discordbooter = new Boot(token, prefix); var discordbooter = new Boot(token, prefix);
await discordbooter.Awake(); await discordbooter.Awake();
return discordbooter; return discordbooter;
@@ -140,8 +141,6 @@ public class Program
var b = await StartNoGui(); var b = await StartNoGui();
consoleCommandsHandler = new ConsoleCommandsHandler(b.client); consoleCommandsHandler = new ConsoleCommandsHandler(b.client);
if (Entry.startupArguments.loadPluginsAtStartup) { loadPluginsOnStartup = true; }
if (len > 0 && args[0] == "/remplug") if (len > 0 && args[0] == "/remplug")
{ {
var plugName = string.Join(' ', args, 1, args.Length - 1); var plugName = string.Join(' ', args, 1, args.Length - 1);
@@ -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 (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{ {
if (Config.Variables.Exists("LaunchMessage")) if (Config.Data.ContainsKey("LaunchMessage"))
Config.Variables.Add("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 !", "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);
Logger.WriteErrFile(ex.ToString()); Logger.WriteErrFile(ex.ToString());
} }
} }
@@ -175,24 +173,15 @@ public class Program
private static async Task PreLoadComponents(string[] args) 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<StartupArguments>(Functions.dataFolder + "loader.json");
await Config.Initialize("SetDB.dat", true);
Logger.WriteLine("Loading resources ..."); Logger.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END); var main = new Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start(); main.Start();
if (await Config.Variables.ExistsAsync("DeleteLogsAtStartup")) if (Config.Data.ContainsKey("DeleteLogsAtStartup"))
if (await Config.Variables.GetValueAsync("DeleteLogsAtStartup") == "true") if (Config.Data["DeleteLogsAtStartup"] == "true")
foreach (var file in Directory.GetFiles("./Output/Logs/")) foreach (var file in Directory.GetFiles("./Output/Logs/"))
File.Delete(file); File.Delete(file);
var OnlineDefaultKeys = var OnlineDefaultKeys =
@@ -200,13 +189,7 @@ public class Program
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys"); "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys");
if (!await Config.Variables.ExistsAsync("Version")) Config.Data["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(),
false);
else
await Config.Variables.SetValueAsync(
"Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
foreach (var key in OnlineDefaultKeys) foreach (var key in OnlineDefaultKeys)
{ {
@@ -214,9 +197,7 @@ public class Program
var s = key.Split(' '); var s = key.Split(' ');
try try
{ {
if (await Config.Variables.ExistsAsync(s[0])) await Config.Variables.SetValueAsync(s[0], s[1]); Config.Data[s[0]] = s[1];
else
await Config.Variables.AddAsync(s[0], s[1], s[2].ToLower() == "true");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -238,7 +219,7 @@ public class Program
{ {
case "CurrentVersion": case "CurrentVersion":
var newVersion = s[1]; var newVersion = s[1];
var currentVersion = await Config.Variables.GetValueAsync("Version"); var currentVersion = Config.Data["Version"];
if (!newVersion.Equals(currentVersion)) if (!newVersion.Equals(currentVersion))
{ {
@@ -257,10 +238,10 @@ public class Program
break; break;
} }
var nVer = new VersionString(newVersion.Substring(2)); 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) if (cVer > nVer)
{ {
await Config.Variables.SetValueAsync("Version", "1." + cVer.ToShortString() + " (Beta)"); Config.Data["version"] = "1." + cVer.ToShortString() + " (Beta)";
break; break;
} }
@@ -328,9 +309,9 @@ public class Program
break; break;
Directory.CreateDirectory(Functions.dataFolder + "Applications"); Directory.CreateDirectory(Functions.dataFolder + "Applications");
if (!await Config.Variables.ExistsAsync("LauncherVersion")) if (!Config.Data.ContainsKey("LauncherVersion"))
await Config.Variables.AddAsync("LauncherVersion", "0.0.0.0", false); Config.Data["LauncherVersion"] = "0.0.0.0";
if (await Config.Variables.GetValueAsync("LauncherVersion") != updaternewversion || if (Config.Data["LauncherVersion"] != updaternewversion ||
!File.Exists("./Launcher.exe")) !File.Exists("./Launcher.exe"))
{ {
Console.Clear(); Console.Clear();
@@ -342,7 +323,7 @@ public class Program
$"./Launcher.exe"); $"./Launcher.exe");
//await ArchiveManager.ExtractArchive("./Updater.zip", "./", null, //await ArchiveManager.ExtractArchive("./Updater.zip", "./", null,
// UnzipProgressType.PercentageFromTotalSize); // UnzipProgressType.PercentageFromTotalSize);
await Config.Variables.SetValueAsync("LauncherVersion", updaternewversion); Config.Data["LauncherVersion"] = updaternewversion;
// File.Delete("Updater.zip"); // File.Delete("Updater.zip");
bar.Stop("The launcher has been updated !"); bar.Stop("The launcher has been updated !");
Console.Clear(); Console.Clear();
@@ -382,7 +363,7 @@ public class Program
Y = 5 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, X = Pos.Left(labelToken) + labelToken.Text.Length + 2,
Y = labelToken.Y, Y = labelToken.Y,
@@ -394,7 +375,7 @@ public class Program
X = 5, X = 5,
Y = 8 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, X = Pos.Left(labelPrefix) + labelPrefix.Text.Length + 2,
Y = labelPrefix.Y, Y = labelPrefix.Y,
@@ -406,7 +387,7 @@ public class Program
X = 5, X = 5,
Y = 11 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, X = Pos.Left(labelServerid) + labelServerid.Text.Length + 2,
Y = labelServerid.Y, Y = labelServerid.Y,
@@ -451,9 +432,9 @@ public class Program
} }
Config.Variables.Add("ServerID", (string)textFiledServerID.Text, true); Config.Data.Add("ServerID", (string)textFiledServerID.Text);
Config.Variables.Add("token", (string)textFiledToken.Text, true); Config.Data.Add("token", (string)textFiledToken.Text);
Config.Variables.Add("prefix", (string)textFiledPrefix.Text, true); Config.Data.Add("prefix", (string)textFiledPrefix.Text);
MessageBox.Query("Discord Bot Settings", "Successfully saved config !\nJust start the bot :D", MessageBox.Query("Discord Bot Settings", "Successfully saved config !\nJust start the bot :D",
"Start :D"); "Start :D");

View File

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

View File

@@ -105,7 +105,7 @@ public class Boot
{ {
if (arg.Message.Contains("401")) 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."); Logger.LogError("The token is invalid. Please restart the bot and enter a valid token.");
await Task.Delay(4000); await Task.Delay(4000);
Environment.Exit(0); Environment.Exit(0);

View File

@@ -2,15 +2,21 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using System.IO; using System.IO;
using System.Collections.Generic;
using PluginManager.Others;
using System.Collections;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Database;
namespace PluginManager; namespace PluginManager;
public static class Config public static class Config
{ {
private static bool IsLoaded = false; private static bool IsLoaded = false;
public static async Task Initialize(string DatabaseName, bool isConsole)
public static Json<string, string> Data;
public static Json<string, string> Plugins;
public static async Task Initialize(bool isConsole)
{ {
if (IsLoaded) if (IsLoaded)
return; return;
@@ -19,200 +25,126 @@ public static class Config
Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS"); Directory.CreateDirectory("./Data/PAKS");
Settings.sqlDatabase = new SqlDatabase(DatabaseName); Data = new Json<string, string>("./Data/Resources/config.json");
await Settings.sqlDatabase.Open(); Plugins = new Json<string, string>("./Data/Resources/Plugins.json");
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");
IsLoaded = true; IsLoaded = true;
Logger.Initialize(isConsole); Logger.Initialize(isConsole);
PluginManager.Others.ArchiveManager.Initialize(); ArchiveManager.Initialize();
if (isConsole) if (isConsole)
Logger.LogEvent += (message) => { Console.Write(message); }; Logger.LogEvent += (message) => { Console.Write(message); };
} }
public static class Variables public class Json<TKey, TValue> : IDictionary<TKey, TValue>
{ {
public static async Task<string?> GetValueAsync(string VarName) protected IDictionary<TKey, TValue> _dictionary;
public Json(IDictionary<TKey, TValue> dictionary)
{ {
if (!IsLoaded) _dictionary = dictionary;
throw new Exception("Config is not loaded");
return await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "Value");
} }
public static string? GetValue(string VarName) public Json(string file)
{ {
if (!IsLoaded) _dictionary = PrivateReadConfig(file).GetAwaiter().GetResult();
throw new Exception("Config is not loaded");
return Settings.sqlDatabase.GetValue("Variables", "VarName", VarName, "Value");
} }
public virtual void Add(TKey key, TValue value)
public static async Task SetValueAsync(string VarName, string Value)
{ {
if (!IsLoaded) _dictionary.Add(key, value);
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);
} }
public static void SetValue(string VarName, string Value) public void Clear() { _dictionary.Clear(); }
public bool ContainsKey(TKey key)
{ {
if (!IsLoaded) if (_dictionary == null)
throw new Exception("Config is not loaded"); throw new Exception("Dictionary is null");
if (IsReadOnly(VarName))
throw new Exception($"Variable ({VarName}) is read only and can not be changed to {Value}"); return _dictionary.ContainsKey(key);
Settings.sqlDatabase.SetValue("Variables", "VarName", VarName, "Value", Value);
} }
public virtual ICollection<TKey> Keys => _dictionary.Keys;
public static async Task<bool> IsReadOnlyAsync(string VarName) public virtual ICollection<TValue> Values => _dictionary.Values;
public int Count => _dictionary.Count;
public bool IsReadOnly => _dictionary.IsReadOnly;
public virtual TValue this[TKey key]
{ {
if (!IsLoaded) get
throw new Exception("Config is not loaded");
return (await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "ReadOnly")).Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
public static bool IsReadOnly(string VarName)
{ {
if (!IsLoaded) if (_dictionary.TryGetValue(key, out TValue value)) return value;
throw new Exception("Config is not loaded"); return default;
return (Settings.sqlDatabase.GetValue("Variables", "VarName", VarName, "ReadOnly")).Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
public static async Task SetReadOnlyAsync(string VarName, bool ReadOnly) }
set
{ {
if (!IsLoaded) if (_dictionary.ContainsKey(key))
throw new Exception("Config is not loaded"); _dictionary[key] = value;
await Settings.sqlDatabase.SetValueAsync("Variables", "VarName", VarName, "ReadOnly", ReadOnly ? "true" : "false"); else _dictionary.Add(key, value);
}
} }
public static void SetReadOnly(string VarName, bool ReadOnly) public virtual bool TryGetValue(TKey key, out TValue value)
{ {
if (!IsLoaded) return _dictionary.TryGetValue(key, out value);
throw new Exception("Config is not loaded");
Settings.sqlDatabase.SetValue("Variables", "VarName", VarName, "ReadOnly", ReadOnly ? "true" : "false");
} }
public static async Task<bool> ExistsAsync(string VarName) private async Task<Dictionary<TKey, TValue>> PrivateReadConfig(string file)
{ {
if (!IsLoaded) if (!File.Exists(file))
throw new Exception("Config is not loaded");
return await Settings.sqlDatabase.KeyExistsAsync("Variables", "VarName", VarName);
}
public static bool Exists(string VarName)
{ {
if (!IsLoaded) var dictionary = new Dictionary<TKey, TValue>();
throw new Exception("Config is not loaded"); await Functions.SaveToJsonFile(file, _dictionary);
return Settings.sqlDatabase.KeyExists("Variables", "VarName", VarName); return dictionary;
} }
public static async Task AddAsync(string VarName, string Value, bool ReadOnly = false) var d = await Functions.ConvertFromJson<Dictionary<TKey, TValue>>(file);
if (d is null)
throw new Exception("Failed to read config file");
return d;
}
public bool Remove(TKey key)
{ {
if (!IsLoaded) return _dictionary.Remove(key);
throw new Exception("Config is not loaded"); }
if (await ExistsAsync(VarName))
public void Add(KeyValuePair<TKey, TValue> item)
{ {
await SetValueAsync(VarName, Value); _dictionary.Add(item);
await SetReadOnlyAsync(VarName, ReadOnly);
return;
}
await Settings.sqlDatabase.InsertAsync("Variables", VarName, Value, ReadOnly ? "true" : "false");
} }
public static void Add(string VarName, string Value, bool ReadOnly = false) public bool Contains(KeyValuePair<TKey, TValue> item)
{ {
if (!IsLoaded) return _dictionary.Contains(item);
throw new Exception("Config is not loaded"); }
if (Exists(VarName))
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{ {
if (GetValue(VarName) == Value) _dictionary.CopyTo(array, arrayIndex);
return;
SetValue(VarName, Value);
SetReadOnly(VarName, ReadOnly);
return;
}
Settings.sqlDatabase.Insert("Variables", VarName, Value, ReadOnly ? "true" : "false");
} }
public static async Task RemoveKeyAsync(string VarName) public bool Remove(KeyValuePair<TKey, TValue> item)
{ {
if (!IsLoaded) return _dictionary.Remove(item);
throw new Exception("Config is not loaded");
await Settings.sqlDatabase.RemoveKeyAsync("Variables", "VarName", VarName);
} }
public static void RemoveKey(string VarName) public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{ {
if (!IsLoaded) return _dictionary.GetEnumerator();
throw new Exception("Config is not loaded");
Settings.sqlDatabase.RemoveKey("Variables", "VarName", VarName);
}
} }
public static class Plugins IEnumerator IEnumerable.GetEnumerator()
{ {
public static async Task<string> GetVersionAsync(string pluginName) return ((IEnumerable)_dictionary).GetEnumerator();
{
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());
} }
} }
}

View File

@@ -254,7 +254,7 @@ public class ConsoleCommandsHandler
var ver = await ServerCom.GetVersionOfPackageFromWeb(name); var ver = await ServerCom.GetVersionOfPackageFromWeb(name);
if (ver is null) throw new Exception("Incorrect version"); if (ver is null) throw new Exception("Incorrect version");
await Config.Plugins.SetVersionAsync(name, ver); Config.Plugins[name] = ver.ToShortString();
isDownloading = false; isDownloading = false;
@@ -267,15 +267,15 @@ public class ConsoleCommandsHandler
{ {
if (args.Length != 2) if (args.Length != 2)
return; return;
if (!Config.Variables.Exists(args[1])) if (!Config.Data.ContainsKey(args[1]))
return; return;
var data = Config.Variables.GetValue(args[1]); var data = Config.Data[args[1]];
Logger.WriteLine($"{args[1]} => {data}"); 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) if (args.Length < 4)
return; return;
@@ -285,7 +285,7 @@ public class ConsoleCommandsHandler
try try
{ {
Config.Variables.Add(key, value, isReadOnly); Config.Data[key] = value;
Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
} }
catch (Exception ex) catch (Exception ex)
@@ -299,7 +299,7 @@ public class ConsoleCommandsHandler
{ {
if (args.Length < 2) if (args.Length < 2)
return; return;
Config.Variables.RemoveKey(args[1]); Config.Data.Remove(args[1]);
} }
); );
@@ -308,7 +308,8 @@ public class ConsoleCommandsHandler
if (client is null) if (client is null)
return; 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.StopAsync();
await client.DisposeAsync(); await client.DisposeAsync();
await Task.Delay(1000); await Task.Delay(1000);

View File

@@ -80,8 +80,8 @@ public class PluginLoader
var version = await ServerCom.GetVersionOfPackageFromWeb(name); var version = await ServerCom.GetVersionOfPackageFromWeb(name);
if (version is null) if (version is null)
return; return;
if (Config.Plugins.GetVersion(name) is not null) if (Config.Plugins[name] is not null)
Config.Plugins.SetVersion(name, version); Config.Plugins[name] = version.ToShortString();
if (await PluginUpdater.CheckForUpdates(name)) if (await PluginUpdater.CheckForUpdates(name))
await PluginUpdater.Download(name); await PluginUpdater.Download(name);

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Numerics; using System.Numerics;
using Discord; using Discord;
namespace PluginManager namespace PluginManager
@@ -17,17 +18,19 @@ namespace PluginManager
public static void Initialize(bool console) 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")) if (!Config.Data.ContainsKey("LogFolder"))
Config.Variables.Add("LogFolder", "./Data/Output/Logs/"); Config.Data.Add("LogFolder", "./Data/Output/Logs/");
if (!Config.Variables.Exists("ErrorFolder")) if (!Config.Data.ContainsKey("ErrorFolder"))
Config.Variables.Add("ErrorFolder", "./Data/Output/Errors/"); Config.Data.Add("ErrorFolder", "./Data/Output/Errors/");
isInitialized = true; isInitialized = true;
logFolder = Config.Variables.GetValue("LogFolder");
errFolder = Config.Variables.GetValue("ErrorFolder"); logFolder = Config.Data["LogFolder"];
errFolder = Config.Data["ErrorFolder"];
isConsole = console; isConsole = console;
} }
@@ -105,7 +108,8 @@ namespace PluginManager
public static void WriteColored(string message, ConsoleColor color) public static void WriteColored(string message, ConsoleColor color)
{ {
if (!isInitialized) throw new Exception("Logger is not initialized"); if (!isInitialized) throw new Exception("Logger is not initialized");
if(!isConsole) { if (!isConsole)
{
LogEvent?.Invoke(message); LogEvent?.Invoke(message);
return; return;
} }

View File

@@ -91,9 +91,7 @@ public static class ServerCom
public static VersionString? GetVersionOfPackage(string pakName) public static VersionString? GetVersionOfPackage(string pakName)
{ {
if (Config.Plugins.GetVersion(pakName) is null) return new VersionString(Config.Plugins[pakName]);
return null;
return new VersionString(Config.Plugins.GetVersion(pakName));
} }
public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName) public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName)

View File

@@ -15,11 +15,12 @@ namespace PluginManager.Others
{ {
if (isInitialized) throw new Exception("ArchiveManager is already initialized"); if (isInitialized) throw new Exception("ArchiveManager is already initialized");
if (!Config.Variables.Exists("ArchiveFolder")) if (!Config.Data.ContainsKey("ArchiveFolder"))
Config.Variables.Add("ArchiveFolder", "./Data/PAKS/"); Config.Data["ArchiveFolder"] = "./Data/PAKS/";
archiveFolder = Config.Data["ArchiveFolder"];
isInitialized = true; isInitialized = true;
archiveFolder = Config.Variables.GetValue("ArchiveFolder");
} }
/// <summary> /// <summary>

View File

@@ -94,6 +94,7 @@ public static class Functions
/// <returns></returns> /// <returns></returns>
public static async Task<T> ConvertFromJson<T>(string input) public static async Task<T> ConvertFromJson<T>(string input)
{ {
Console.WriteLine(input);
Stream text; Stream text;
if (File.Exists(input)) if (File.Exists(input))
text = new MemoryStream(await File.ReadAllBytesAsync(input)); text = new MemoryStream(await File.ReadAllBytesAsync(input));

View File

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

View File

@@ -7,6 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\Di
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotWeb", "DiscordBotWeb\DiscordBotWeb.csproj", "{5500905A-E48F-4191-BB76-8610FA19F251}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU 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}.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.ActiveCfg = Release|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = 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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE