Cleaned up code

This commit is contained in:
2022-06-12 10:22:43 +03:00
parent 97888626b6
commit 861b83cda2
8 changed files with 37 additions and 191 deletions

View File

@@ -1,6 +1,5 @@
using PluginManager.Others; using PluginManager.Others;
using System.IO; using System.IO;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Generic; using System.Collections.Generic;
@@ -9,27 +8,27 @@ namespace PluginManager
{ {
internal class AppConfig internal class AppConfig
{ {
public Dictionary<string, object> ApplicationVariables { get; set; } public Dictionary<string, object>? ApplicationVariables { get; set; }
public List<string> ProtectedKeyWords { get; set; } public List<string>? ProtectedKeyWords { get; set; }
} }
public static class Config public static class Config
{ {
private static AppConfig appConfig; private static AppConfig? appConfig { get; set; }
public static bool AddValueToVariables<T>(string key, T value, bool isProtected) public static bool AddValueToVariables<T>(string key, T value, bool isProtected)
{ {
if (appConfig.ApplicationVariables.ContainsKey(key)) return false; if (appConfig!.ApplicationVariables!.ContainsKey(key)) return false;
if (value == null) return false; if (value == null) return false;
appConfig.ApplicationVariables.Add(key, value); appConfig.ApplicationVariables.Add(key, value);
if (isProtected) appConfig.ProtectedKeyWords.Add(key); if (isProtected) appConfig.ProtectedKeyWords!.Add(key);
SaveConfig(); SaveConfig();
return true; return true;
} }
public static T? GetValue<T>(string key) public static T? GetValue<T>(string key)
{ {
if (!appConfig.ApplicationVariables.ContainsKey(key)) return default; if (!appConfig!.ApplicationVariables!.ContainsKey(key)) return default;
try try
{ {
JsonElement element = (JsonElement)appConfig.ApplicationVariables[key]; JsonElement element = (JsonElement)appConfig.ApplicationVariables[key];
@@ -43,8 +42,8 @@ namespace PluginManager
public static bool SetValue<T>(string key, T value) public static bool SetValue<T>(string key, T value)
{ {
if (!appConfig.ApplicationVariables.ContainsKey(key)) return false; if (!appConfig!.ApplicationVariables!.ContainsKey(key)) return false;
if (appConfig.ProtectedKeyWords.Contains(key)) return false; if (appConfig.ProtectedKeyWords!.Contains(key)) return false;
if (value == null) return false; if (value == null) return false;
appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value); appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value);
@@ -54,8 +53,8 @@ namespace PluginManager
public static bool RemoveKey(string key) public static bool RemoveKey(string key)
{ {
appConfig.ApplicationVariables.Remove(key); appConfig!.ApplicationVariables!.Remove(key);
appConfig.ProtectedKeyWords.Remove(key); appConfig.ProtectedKeyWords!.Remove(key);
SaveConfig(); SaveConfig();
return true; return true;
} }
@@ -63,7 +62,7 @@ namespace PluginManager
public static async void SaveConfig() public static async void SaveConfig()
{ {
string path = Functions.dataFolder + "config.json"; string path = Functions.dataFolder + "config.json";
await Functions.SaveToJsonFile<AppConfig>(path, appConfig); await Functions.SaveToJsonFile<AppConfig>(path, appConfig!);
} }
public static async Task LoadConfig() public static async Task LoadConfig()
@@ -72,15 +71,15 @@ namespace PluginManager
if (File.Exists(path)) if (File.Exists(path))
{ {
appConfig = await Functions.ConvertFromJson<AppConfig>(path); appConfig = await Functions.ConvertFromJson<AppConfig>(path);
Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords.Count} readonly variables."); Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables!.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords!.Count} readonly variables.");
} }
else else
appConfig = new() { ApplicationVariables = new Dictionary<string, object>(), ProtectedKeyWords = new List<string>() }; appConfig = new() { ApplicationVariables = new Dictionary<string, object>(), ProtectedKeyWords = new List<string>() };
} }
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 Dictionary<string, object> GetAllVariables() => new(appConfig!.ApplicationVariables!);
} }
} }

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Others; using PluginManager.Others;
@@ -41,4 +42,4 @@ internal class Command
/// The prefix that is used for the command /// The prefix that is used for the command
/// </summary> /// </summary>
public char PrefixUsed { get; } public char PrefixUsed { get; }
} }

View File

@@ -23,7 +23,7 @@ public class ConsoleCommandsHandler
{ {
this.client = client; this.client = client;
InitializeBasicCommands(); InitializeBasicCommands();
Console.WriteLine("Initalized console command handeler !"); Console.WriteLine("Initialized console command handler !");
} }
private void InitializeBasicCommands() private void InitializeBasicCommands()
@@ -55,7 +55,7 @@ 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;
@@ -237,7 +237,7 @@ 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 string[] { kvp.Key, kvp.Value.ToString()! });
data.Add(new[] { "-", "-" }); data.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(data); Console_Utilities.FormatAndAlignTable(data);
} }

View File

@@ -1,62 +0,0 @@
using System;
using System.Threading.Tasks;
using PluginManager.Others.Exceptions;
namespace PluginManager.Items;
public class Spinner
{
/// <summary>
/// True if active, false otherwise
/// </summary>
public bool isSpinning;
/// <summary>
/// The Spinner constructor
/// </summary>
public Spinner()
{
isSpinning = false;
}
/// <summary>
/// The method that is called to start spinning the spinner
/// </summary>
public async void Start()
{
isSpinning = true;
var cnt = 0;
while (isSpinning)
{
cnt++;
switch (cnt % 4)
{
case 0:
Console.Write("/");
break;
case 1:
Console.Write("-");
break;
case 2:
Console.Write("\\");
break;
case 3:
Console.Write("|");
break;
}
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
await Task.Delay(250);
}
}
/// <summary>
/// The method that is called to stop the spinner from spinning
/// </summary>
public void Stop()
{
if (!isSpinning) throw new APIException("Spinner was not spinning", GetType());
isSpinning = false;
}
}

View File

@@ -28,6 +28,11 @@ internal class Loader<T>
private string path { get; } private string path { get; }
private string extension { get; } private string extension { get; }
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
internal event FileLoadedEventHandler? FileLoaded; internal event FileLoadedEventHandler? FileLoaded;
internal event PluginLoadedEventHandler? PluginLoaded; internal event PluginLoadedEventHandler? PluginLoaded;
@@ -100,8 +105,4 @@ internal class Loader<T>
return list; return list;
} }
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
} }

View File

@@ -87,11 +87,11 @@ public class PluginLoader
{ {
if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client); if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client);
if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); onEVELoad?.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception);
} }
private void OnCommandLoaded(LoaderArgs e) private void OnCommandLoaded(LoaderArgs e)
{ {
if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); onCMDLoad?.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
} }
} }

View File

@@ -1,91 +0,0 @@
using System;
namespace PluginManager.Others.Exceptions;
/// <summary>
/// Custom Exception for PluginManager
/// </summary>
[Serializable]
public class APIException : Exception
{
/// <summary>
/// The APIException contructor
/// </summary>
/// <param name="message">The error message</param>
/// <param name="function">The function where the message was triggered</param>
/// <param name="possible_cause">The possible cause of the error</param>
/// <param name="error">The error code</param>
public APIException(string message, string? function, string possible_cause, Error error) : base(message)
{
ErrorCode = error;
Function = function;
PossibleCause = possible_cause;
}
/// <summary>
/// The APIException contructor
/// </summary>
/// <param name="message">The error message</param>
/// <param name="function">The function where the message was triggered</param>
/// <param name="errorCode">The error code</param>
public APIException(string message, string? function, Error? errorCode) : base(message)
{
ErrorCode = errorCode;
Function = function;
}
/// <summary>
/// The APIException contructor
/// </summary>
/// <param name="message">The error message</param>
/// <param name="function">The function where the message was triggered</param>
public APIException(string message, string? function) : base(message)
{
Function = function;
}
/// <summary>
/// The APIException contructor
/// </summary>
/// <param name="message">The error message</param>
public APIException(string message) : base(message)
{
}
/// <summary>
/// The APIException constructor
/// </summary>
/// <param name="message">The error message</param>
/// <param name="errorLocation">The class where the error was thrown</param>
public APIException(string message, Type errorLocation) : base(message)
{
Function = errorLocation.FullName;
}
/// <summary>
/// The function where the error occurred
/// </summary>
public string? Function { get; } = "not specified";
/// <summary>
/// The error code
/// </summary>
public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR;
/// <summary>
/// The possible cause that determined the error
/// </summary>
public string? PossibleCause { get; } = "not specified";
/// <summary>
/// Method to print the error to <see cref="Console" />
/// </summary>
public void Print()
{
Console.WriteLine("Message Content: " + Message);
Console.WriteLine("Function: " + Function);
Console.WriteLine("Error Code: " + ErrorCode);
Console.WriteLine("Possible cause: " + PossibleCause);
if (StackTrace != null) Functions.WriteErrFile(StackTrace);
}
}

View File

@@ -32,15 +32,10 @@ namespace PluginManager.Others
/// </summary> /// </summary>
public static readonly string errFolder = @"./Output/Errors/"; public static readonly string errFolder = @"./Output/Errors/";
/// <summary>
/// The location for all languages
/// </summary>
public static readonly string langFolder = @"./Data/Languages/";
/// <summary> /// <summary>
/// Archives folder /// Archives folder
/// </summary> /// </summary>
public static readonly string pakFolder = @"./Data/Resources/PAKS/"; public static readonly string pakFolder = @"./Data/Resources/PAK/";
/// <summary> /// <summary>
@@ -49,13 +44,13 @@ namespace PluginManager.Others
/// <param name="FileName">The file name that is inside the archive or its full path</param> /// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param> /// <param name="archFile">The archive location from the PAKs folder</param>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns> /// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<string?> ReadFromPakAsync(string FileName, string archFile) public static async Task<Stream?> ReadFromPakAsync(string FileName, string archFile)
{ {
archFile = pakFolder + archFile; archFile = pakFolder + archFile;
Directory.CreateDirectory(pakFolder); Directory.CreateDirectory(pakFolder);
if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !"); if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !");
string? textValue = null; Stream? textValue = null;
var fs = new FileStream(archFile, FileMode.Open); var fs = new FileStream(archFile, FileMode.Open);
var zip = new ZipArchive(fs, ZipArchiveMode.Read); var zip = new ZipArchive(fs, ZipArchiveMode.Read);
foreach (var entry in zip.Entries) foreach (var entry in zip.Entries)
@@ -64,7 +59,8 @@ namespace PluginManager.Others
{ {
Stream s = entry.Open(); Stream s = entry.Open();
StreamReader reader = new StreamReader(s); StreamReader reader = new StreamReader(s);
textValue = await reader.ReadToEndAsync(); textValue = reader.BaseStream;
textValue.Position = 0;
reader.Close(); reader.Close();
s.Close(); s.Close();
fs.Close(); fs.Close();
@@ -239,7 +235,9 @@ namespace PluginManager.Others
/// <returns></returns> /// <returns></returns>
public static async Task SaveToJsonFile<T>(string file, T Data) public static async Task SaveToJsonFile<T>(string file, T Data)
{ {
using (var s = File.OpenWrite(file)) await JsonSerializer.SerializeAsync(s, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); var s = File.OpenWrite(file);
await JsonSerializer.SerializeAsync(s, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true });
s.Close();
} }
/// <summary> /// <summary>
@@ -259,7 +257,7 @@ namespace PluginManager.Others
text.Position = 0; text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text); var obj = await JsonSerializer.DeserializeAsync<T>(text);
text.Close(); text.Close();
return obj; return (obj ?? default)!;
} }
public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element) public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element)