Fixed some bugs with Command handler and configuration

This commit is contained in:
2022-07-13 19:48:57 +03:00
parent 3f67d7f3f9
commit b8ec6f42df
3 changed files with 89 additions and 69 deletions

View File

@@ -4,14 +4,15 @@ using System.IO;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading; using System.Threading;
namespace PluginManager namespace PluginManager
{ {
internal class AppConfig internal class AppConfig
{ {
public Dictionary<string, object>? ApplicationVariables { get; set; } public Dictionary<string, object>? ApplicationVariables { get; init; }
public List<string>? ProtectedKeyWords { get; set; } public List<string>? ProtectedKeyWords { get; init; }
} }
public static class Config public static class Config
@@ -76,20 +77,43 @@ namespace PluginManager
private static AppConfig? appConfig { get; set; } private static AppConfig? appConfig { get; set; }
public static bool AddValueToVariables<T>(string key, T value, bool isProtected) public static void AddValueToVariables<T>(string key, T value, bool isProtected)
{ {
if (appConfig!.ApplicationVariables!.ContainsKey(key)) return false; if (value == null)
if (value == null) return false; throw new Exception("The value cannot be null");
if (appConfig!.ApplicationVariables!.ContainsKey(key))
throw new Exception($"The key ({key}) already exists in the variables. Value {GetValue<T>(key)}");
appConfig.ApplicationVariables.Add(key, value); appConfig.ApplicationVariables.Add(key, value);
if (isProtected && key != "Version") appConfig.ProtectedKeyWords!.Add(key); if (isProtected && key != "Version")
appConfig.ProtectedKeyWords!.Add(key);
SaveConfig(); SaveConfig();
return true; }
public static Type GetVariableType(string value)
{
if (int.TryParse(value, out var intValue))
return typeof(int);
if (bool.TryParse(value, out var boolValue))
return typeof(bool);
if (float.TryParse(value, out var floatValue))
return typeof(float);
if (double.TryParse(value, out var doubleValue))
return typeof(double);
if (uint.TryParse(value, out var uintValue))
return typeof(uint);
if (long.TryParse(value, out var longValue))
return typeof(long);
if (byte.TryParse(value, out var byteValue))
return typeof(byte);
return typeof(string);
} }
public static void GetAndAddValueToVariable(string key, string value, bool isReadOnly) public static void GetAndAddValueToVariable(string key, string value, bool isReadOnly)
{ {
if (Config.ContainsKey(key)) return; if (Config.ContainsKey(key))
return;
if (int.TryParse(value, out var intValue)) if (int.TryParse(value, out var intValue))
Config.AddValueToVariables(key, intValue, isReadOnly); Config.AddValueToVariables(key, intValue, isReadOnly);
else if (bool.TryParse(value, out var boolValue)) else if (bool.TryParse(value, out var boolValue))
@@ -122,24 +146,26 @@ namespace PluginManager
} }
} }
public static bool SetValue<T>(string key, T value) public static void SetValue<T>(string key, T value)
{ {
if (!appConfig!.ApplicationVariables!.ContainsKey(key)) return false; if (value == null)
if (appConfig.ProtectedKeyWords!.Contains(key)) return false; throw new Exception("Value is null");
if (value == null) return false; if (!appConfig!.ApplicationVariables!.ContainsKey(key))
throw new Exception("Key does not exist in the config file");
if (appConfig.ProtectedKeyWords!.Contains(key))
throw new Exception("Key is protected");
appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value); appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value);
SaveConfig(); SaveConfig();
return true;
} }
public static bool RemoveKey(string key) public static void RemoveKey(string key)
{ {
if (key == "Version" || key == "token" || key == "prefix") return false; if (key == "Version" || key == "token" || key == "prefix")
throw new Exception("Key is protected");
appConfig!.ApplicationVariables!.Remove(key); appConfig!.ApplicationVariables!.Remove(key);
appConfig.ProtectedKeyWords!.Remove(key); appConfig.ProtectedKeyWords!.Remove(key);
SaveConfig(); SaveConfig();
return true;
} }
public static async void SaveConfig() public static async void SaveConfig()
@@ -163,6 +189,6 @@ namespace PluginManager
public static bool ContainsValue<T>(T value) => appConfig!.ApplicationVariables!.ContainsValue(value!); public static bool ContainsValue<T>(T value) => appConfig!.ApplicationVariables!.ContainsValue(value!);
public static bool ContainsKey(string key) => appConfig!.ApplicationVariables!.ContainsKey(key); public static bool ContainsKey(string key) => appConfig!.ApplicationVariables!.ContainsKey(key);
public static Dictionary<string, object> GetAllVariables() => new(appConfig!.ApplicationVariables!); public static ReadOnlyDictionary<string, object> GetAllVariables() => new(appConfig!.ApplicationVariables!);
} }
} }

View File

@@ -15,7 +15,7 @@ namespace PluginManager.Items;
public class ConsoleCommandsHandler public class ConsoleCommandsHandler
{ {
private static readonly PluginsManager manager = new("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Plugins.txt"); private static readonly PluginsManager manager = new("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Plugins.txt");
public static List<ConsoleCommand> commandList = new(); private static readonly List<ConsoleCommand> commandList = new();
private readonly DiscordSocketClient? client; private readonly DiscordSocketClient? client;
public ConsoleCommandsHandler(DiscordSocketClient client) public ConsoleCommandsHandler(DiscordSocketClient client)
@@ -43,9 +43,7 @@ public class ConsoleCommandsHandler
foreach (var command in commandList) foreach (var command in commandList)
{ {
var pa = from p in command.Action.Method.GetParameters() var pa = from p in command.Action.Method.GetParameters() where p.Name != null select p.ParameterType.FullName;
where p.Name != null
select p.ParameterType.FullName;
items.Add(new[] { command.CommandName, command.Description, command.Usage }); items.Add(new[] { command.CommandName, command.Description, command.Usage });
} }
@@ -70,12 +68,14 @@ public class ConsoleCommandsHandler
AddCommand("lp", "Load plugins", () => AddCommand("lp", "Load plugins", () =>
{ {
if (pluginsLoaded) return; if (pluginsLoaded)
return;
var loader = new PluginLoader(client!); var loader = new PluginLoader(client!);
loader.onCMDLoad += (name, typeName, success, exception) => loader.onCMDLoad += (name, typeName, success, exception) =>
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
if (name == null || name.Length < 2) name = typeName; if (name == null || name.Length < 2)
name = typeName;
if (success) if (success)
Console.WriteLine("[CMD] Successfully loaded command : " + name); Console.WriteLine("[CMD] Successfully loaded command : " + name);
else else
@@ -84,7 +84,8 @@ public class ConsoleCommandsHandler
}; };
loader.onEVELoad += (name, typeName, success, exception) => loader.onEVELoad += (name, typeName, success, exception) =>
{ {
if (name == null || name.Length < 2) name = typeName; if (name == null || name.Length < 2)
name = typeName;
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
if (success) if (success)
Console.WriteLine("[EVENT] Successfully loaded event : " + name); Console.WriteLine("[EVENT] Successfully loaded event : " + name);
@@ -120,9 +121,7 @@ public class ConsoleCommandsHandler
return; return;
} }
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" + Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" + " Use &glistplugs &ccommand to display all available plugins !");
" Use &glistplugs &ccommand to display all available plugins !"
);
return; return;
} }
@@ -136,7 +135,8 @@ public class ConsoleCommandsHandler
if (info[0] == "Command" || info[0] == "Event") if (info[0] == "Command" || info[0] == "Event")
if (info[0] == "Event") if (info[0] == "Event")
Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Event)); Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Event));
else if (info[0] == "Command") Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Command)); else if (info[0] == "Command")
Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Command));
Console.WriteLine("\n"); Console.WriteLine("\n");
@@ -151,7 +151,8 @@ public class ConsoleCommandsHandler
foreach (var line in lines) foreach (var line in lines)
{ {
if (!(line.Length > 0 && line.Contains(","))) continue; if (!(line.Length > 0 && line.Contains(",")))
continue;
var split = line.Split(','); var split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}"); Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]); await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
@@ -164,11 +165,7 @@ public class ConsoleCommandsHandler
var isExtracting = true; var isExtracting = true;
var bar = new Console_Utilities.ProgressBar { Max = 100f, Color = ConsoleColor.Green }; var bar = new Console_Utilities.ProgressBar { Max = 100f, Color = ConsoleColor.Green };
IProgress<float> extractProgress = new Progress<float>(value => IProgress<float> extractProgress = new Progress<float>(value => { proc = value; });
{
proc = value;
}
);
new Thread(new Task(() => new Thread(new Task(() =>
{ {
while (isExtracting) while (isExtracting)
@@ -199,8 +196,10 @@ public class ConsoleCommandsHandler
AddCommand("value", "read value from VariableStack", "value [key]", args => AddCommand("value", "read value from VariableStack", "value [key]", args =>
{ {
if (args.Length != 2) return; if (args.Length != 2)
if (!Config.ContainsKey(args[1])) return; return;
if (!Config.ContainsKey(args[1]))
return;
var data = Config.GetValue<string>(args[1]); var data = Config.GetValue<string>(args[1]);
Console.WriteLine($"{args[1]} => {data}"); Console.WriteLine($"{args[1]} => {data}");
@@ -209,7 +208,8 @@ public class ConsoleCommandsHandler
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] [isReadOnly=true/false]", args =>
{ {
if (args.Length < 4) return; if (args.Length < 4)
return;
var key = args[1]; var key = args[1];
var value = args[2]; var value = args[2];
var isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase); var isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase);
@@ -228,7 +228,8 @@ public class ConsoleCommandsHandler
AddCommand("remv", "remove variable from system variables", "remv [key]", args => AddCommand("remv", "remove variable from system variables", "remv [key]", args =>
{ {
if (args.Length < 2) return; if (args.Length < 2)
return;
Config.RemoveKey(args[1]); Config.RemoveKey(args[1]);
} }
); );
@@ -240,7 +241,8 @@ public class ConsoleCommandsHandler
data.Add(new[] { "-", "-" }); data.Add(new[] { "-", "-" });
data.Add(new[] { "Key", "Value" }); data.Add(new[] { "Key", "Value" });
data.Add(new[] { "-", "-" }); data.Add(new[] { "-", "-" });
foreach (var kvp in d) data.Add(new[] { kvp.Key, kvp.Value.ToString()! }); foreach (var kvp in d)
data.Add(new[] { kvp.Key, kvp.Value.ToString()! });
data.Add(new[] { "-", "-" }); data.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(data); Console_Utilities.FormatAndAlignTable(data);
} }
@@ -248,7 +250,8 @@ public class ConsoleCommandsHandler
AddCommand("sd", "Shuts down the discord bot", async () => AddCommand("sd", "Shuts down the discord bot", async () =>
{ {
if (client is null) return; if (client is null)
return;
await client.StopAsync(); await client.StopAsync();
await client.DisposeAsync(); await client.DisposeAsync();
Config.SaveConfig(); Config.SaveConfig();
@@ -263,13 +266,7 @@ public class ConsoleCommandsHandler
public static void AddCommand(string command, string description, string usage, Action<string[]> action) public static void AddCommand(string command, string description, string usage, Action<string[]> action)
{ {
commandList.Add(new ConsoleCommand commandList.Add(new ConsoleCommand { CommandName = command, Description = description, Action = action, Usage = usage });
{
CommandName = command,
Description = description,
Action = action,
Usage = usage
});
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands"); Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
} }
@@ -303,7 +300,8 @@ public class ConsoleCommandsHandler
if (removeCommandExecution) if (removeCommandExecution)
{ {
Console.SetCursorPosition(0, Console.CursorTop - 1); Console.SetCursorPosition(0, Console.CursorTop - 1);
for (int i = 0; i < command.Length; i++) Console.Write(" "); for (int i = 0; i < command.Length; i++)
Console.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop); Console.SetCursorPosition(0, Console.CursorTop);
} }

View File

@@ -1,9 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace PluginManager.Others namespace PluginManager.Others
{ {
public class Console_Utilities public static class Console_Utilities
{ {
/// <summary> /// <summary>
/// Progress bar object /// Progress bar object
@@ -28,37 +29,34 @@ namespace PluginManager.Others
for (int i = 0; i < onechunk * progress; i++) for (int i = 0; i < onechunk * progress; i++)
{ {
if (NoColor) Console.BackgroundColor = NoColor ? ConsoleColor.Black : this.Color;
Console.BackgroundColor = ConsoleColor.Black; //this.Color
else
Console.BackgroundColor = this.Color;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write("#"); Console.Write("#");
} }
for (int i = position; i <= 31; i++) for (int i = position; i <= 31; i++)
{ {
if (NoColor) Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.BackgroundColor = ConsoleColor.Black; // background of empty bar
else
Console.BackgroundColor = ConsoleColor.DarkGray;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write(" "); Console.Write(" ");
} }
Console.CursorLeft = 35; Console.CursorLeft = 35;
Console.BackgroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black;
if (speed == -1 || unit == null) if (speed is -1 || unit == null)
{ {
if (progress == Max) if (progress.CanAproximateTo(Max))
Console.Write(progress.ToString() + " % ✓"); Console.Write(progress + " % ✓");
else Console.Write(progress.ToString() + " % "); else
Console.Write(progress + " % ");
} }
else else
Console.Write(progress.ToString() + $"{speed} {unit}/s "); Console.Write(progress + $"{speed} {unit}/s ");
}
}
}
} private static bool CanAproximateTo(this float f, float y) => (MathF.Abs(f - y) < 0.000001);
/// <summary> /// <summary>
@@ -110,8 +108,7 @@ namespace PluginManager.Others
Console.Write(" "); Console.Write(" ");
} }
if (row[l][0] == tableLine) Console.Write(tableCross); Console.Write(row[l][0] == tableLine ? tableCross : tableWall);
else Console.Write(tableWall);
} }
Console.WriteLine(); //end line Console.WriteLine(); //end line
@@ -141,8 +138,7 @@ namespace PluginManager.Others
Console.ForegroundColor = colors[prefix]; Console.ForegroundColor = colors[prefix];
} }
string m = word; string m = colors.Keys.Aggregate(word, (current, key) => current.Replace(key, ""));
foreach (var key in colors.Keys) { m = m.Replace(key, ""); }
Console.Write(m + " "); Console.Write(m + " ");
} }