This commit is contained in:
2022-06-08 18:54:58 +03:00
parent c66ff52d94
commit 531edcd3cc
55 changed files with 2253 additions and 2360 deletions

View File

@@ -16,7 +16,7 @@ namespace PluginManager
public static class Config
{
private static AppConfig appConfig = null;
private static AppConfig appConfig;
public static bool AddValueToVariables<T>(string key, T value, bool isProtected)
{

View File

@@ -1,49 +1,51 @@
namespace PluginManager.Interfaces
using Discord.Commands;
using Discord.WebSocket;
namespace PluginManager.Interfaces;
public interface DBCommand
{
public interface DBCommand
{
/// <summary>
/// Command to be executed
/// It's CaSe SeNsItIvE
/// </summary>
string Command { get; }
/// <summary>
/// Command to be executed
/// It's CaSe SeNsItIvE
/// </summary>
string Command { get; }
/// <summary>
/// Command description
/// </summary>
string Description { get; }
/// <summary>
/// Command description
/// </summary>
string Description { get; }
/// <summary>
/// The usage for your command.
/// It will be displayed when users type help
/// </summary>
string Usage { get; }
/// <summary>
/// The usage for your command.
/// It will be displayed when users type help
/// </summary>
string Usage { get; }
/// <summary>
/// true if the command can be used in a DM channel, otherwise false
/// </summary>
bool canUseDM { get; }
/// <summary>
/// true if the command can be used in a DM channel, otherwise false
/// </summary>
bool canUseDM { get; }
/// <summary>
/// true if the command can be used in a server, otherwise false
/// </summary>
bool canUseServer { get; }
/// <summary>
/// true if the command can be used in a server, otherwise false
/// </summary>
bool canUseServer { get; }
/// <summary>
/// true if the command requre admin, otherwise false
/// </summary>
bool requireAdmin { get; }
/// <summary>
/// true if the command requre admin, otherwise false
/// </summary>
bool requireAdmin { get; }
/// <summary>
/// The main body of the command. This is what is executed when user calls the command
/// </summary>
/// <param name="context">The disocrd Context</param>
/// <param name="message">The message that the user types</param>
/// <param name="client">The discord client of the bot</param>
/// <param name="isDM">true if the message was sent from DM, otherwise false. It is always false if canUseDM is false</param>
void Execute(Discord.Commands.SocketCommandContext context,
Discord.WebSocket.SocketMessage message,
Discord.WebSocket.DiscordSocketClient client,
bool isDM);
}
}
/// <summary>
/// The main body of the command. This is what is executed when user calls the command
/// </summary>
/// <param name="context">The disocrd Context</param>
/// <param name="message">The message that the user types</param>
/// <param name="client">The discord client of the bot</param>
/// <param name="isDM">true if the message was sent from DM, otherwise false. It is always false if canUseDM is false</param>
void Execute(SocketCommandContext context,
SocketMessage message,
DiscordSocketClient client,
bool isDM);
}

View File

@@ -1,23 +1,22 @@
using Discord.WebSocket;
namespace PluginManager.Interfaces
namespace PluginManager.Interfaces;
public interface DBEvent
{
public interface DBEvent
{
/// <summary>
/// The name of the event
/// </summary>
string name { get; }
/// <summary>
/// The name of the event
/// </summary>
string name { get; }
/// <summary>
/// The description of the event
/// </summary>
string description { get; }
/// <summary>
/// The description of the event
/// </summary>
string description { get; }
/// <summary>
/// The method that is invoked when the event is loaded into memory
/// </summary>
/// <param name="client">The discord bot client</param>
void Start(DiscordSocketClient client);
}
/// <summary>
/// The method that is invoked when the event is loaded into memory
/// </summary>
/// <param name="client">The discord bot client</param>
void Start(DiscordSocketClient client);
}

View File

@@ -1,51 +1,44 @@
using Discord.WebSocket;
using PluginManager.Loaders;
using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Others;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Items;
namespace PluginManager.Items
internal class Command
{
internal class Command
/// <summary>
/// The author of the command
/// </summary>
public SocketUser? Author;
/// <summary>
/// The Command class contructor
/// </summary>
/// <param name="message">The message that was sent</param>
public Command(SocketMessage message)
{
/// <summary>
/// The author of the command
/// </summary>
public SocketUser? Author;
/// <summary>
/// The list of arguments
/// </summary>
public List<string> Arguments { get; private set; }
/// <summary>
/// The command that is executed
/// </summary>
public string CommandName { get; private set; }
/// <summary>
/// The prefix that is used for the command
/// </summary>
public char PrefixUsed { get; private set; }
/// <summary>
/// The Command class contructor
/// </summary>
/// <param name="message">The message that was sent</param>
public Command(SocketMessage message)
{
this.Author = message.Author;
string[] data = message.Content.Split(' ');
if (data.Length > 1)
this.Arguments = new List<string>(data.MergeStrings(1).Split(' '));
else this.Arguments = new List<string>();
this.CommandName = data[0].Substring(1);
this.PrefixUsed = data[0][0];
}
Author = message.Author;
var data = message.Content.Split(' ');
if (data.Length > 1)
Arguments = new List<string>(data.MergeStrings(1).Split(' '));
else
Arguments = new List<string>();
CommandName = data[0].Substring(1);
PrefixUsed = data[0][0];
}
/// <summary>
/// The list of arguments
/// </summary>
public List<string> Arguments { get; }
/// <summary>
/// The command that is executed
/// </summary>
public string CommandName { get; }
/// <summary>
/// The prefix that is used for the command
/// </summary>
public char PrefixUsed { get; }
}

View File

@@ -1,98 +1,89 @@
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Newtonsoft.Json.Converters;
namespace PluginManager.Items
namespace PluginManager.Items;
public class ConsoleCommandsHandler
{
public class ConsoleCommandsHandler
private static readonly PluginsManager manager = new("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
public static List<Tuple<string, string, Action<string[]>>> commandList = new();
private readonly DiscordSocketClient? client;
public ConsoleCommandsHandler(DiscordSocketClient client)
{
private static PluginsManager manager = new("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
this.client = client;
InitializeBasicCommands();
Console.WriteLine("Initalized console command handeler !");
}
public static List<Tuple<string, string, Action<string[]>>>? commandList = new List<Tuple<string, string, Action<string[]>>>();
private DiscordSocketClient client;
private void InitializeBasicCommands()
{
var pluginsLoaded = false;
commandList.Clear();
public ConsoleCommandsHandler(DiscordSocketClient client)
{
this.client = client;
InitializeBasicCommands();
Console.WriteLine("Initalized console command handeler !");
}
private void InitializeBasicCommands()
{
bool pluginsLoaded = false;
commandList.Clear();
AddCommand("help", "Show help", (args) =>
AddCommand("help", "Show help", args =>
{
if (args.Length <= 1)
{
Console.WriteLine("Available commands:");
foreach (var command in commandList)
{
Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
}
foreach (var command in commandList) Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
}
else
{
foreach (var command in commandList)
{
if (command.Item1 == args[1])
{
Console.WriteLine(command.Item2);
return;
}
}
Console.WriteLine("Command not found");
}
});
}
);
AddCommand("lp", "Load plugins", () =>
AddCommand("lp", "Load plugins", () =>
{
if (pluginsLoaded) return;
var loader = new PluginLoader(client);
loader.onCMDLoad += (name, typeName, success, exception) =>
{
Console.ForegroundColor = ConsoleColor.Green;
if (name == null || name.Length < 2)
name = typeName;
if (name == null || name.Length < 2) name = typeName;
if (success)
Console.WriteLine("[CMD] Successfully loaded command : " + name);
else
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception.Message);
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
Console.ForegroundColor = ConsoleColor.Red;
};
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;
if (success)
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception.Message);
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
Console.ForegroundColor = ConsoleColor.Red;
};
loader.LoadPlugins();
pluginsLoaded = true;
});
}
);
AddCommand("listplugs", "list available plugins", async () =>
{
await manager.ListAvailablePlugins();
});
AddCommand("listplugs", "list available plugins", async () => { await manager.ListAvailablePlugins(); });
AddCommand("dwplug", "download plugin", async (args) =>
AddCommand("dwplug", "download plugin", async args =>
{
if (args.Length == 1)
{
@@ -100,27 +91,30 @@ namespace PluginManager.Items
return;
}
string name = args.MergeStrings(1);
var name = args.MergeStrings(1);
// info[0] = plugin type
// info[1] = plugin link
// info[2] = if others are required, or string.Empty if none
string[] info = await manager.GetPluginLinkByName(name);
var info = await manager.GetPluginLinkByName(name);
if (info[1] == null) // link is null
{
if (name == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
Console_Utilities.WriteColorText("Name is invalid");
return;
}
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
$" Use &glistplugs &ccommand to display all available plugins !");
return;
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
" Use &glistplugs &ccommand to display all available plugins !"
);
return;
}
string path;
if (info[0] == "Command" || info[0] == "Event")
path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll";
else path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
else
path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
await ServerCom.DownloadFileAsync(info[1], path);
Console.WriteLine("\n");
@@ -130,47 +124,41 @@ namespace PluginManager.Items
{
Console.WriteLine($"Downloading requirements for plugin : {name}");
List<string> lines = await ServerCom.ReadTextFromFile(info[2]);
var lines = await ServerCom.ReadTextFromFile(info[2]);
foreach (var line in lines)
{
string[] split = line.Split(',');
var split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine();
if (split[0].EndsWith(".zip"))
{
Console.WriteLine($"Extracting {split[1]}");
double proc = 0d;
bool isExtracting = true;
Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "");
var proc = 0d;
var isExtracting = true;
var bar = new Console_Utilities.ProgressBar { Max = 100, Color = ConsoleColor.Green };
IProgress<float> extractProgress = new Progress<float>(value =>
{
proc = value;
});
IProgress<float> extractProgress = new Progress<float>(value => { proc = value; });
new Thread(new Task(() =>
{
while (isExtracting)
{
bar.Update((int)proc);
if (proc >= 99.9f)
break;
Thread.Sleep(500);
}
}).Start).Start();
{
while (isExtracting)
{
bar.Update((int)proc);
if (proc >= 99.9f) break;
Thread.Sleep(500);
}
}
).Start
).Start();
await Functions.ExtractArchive("./" + split[1], "./", extractProgress);
bar.Update(100);
isExtracting = false;
await Task.Delay(1000);
bar.Update(100);
Console.WriteLine("\n");
System.IO.File.Delete("./" + split[1]);
File.Delete("./" + split[1]);
}
if (name == "DBUI")
@@ -183,121 +171,122 @@ namespace PluginManager.Items
}
}
}
Console.WriteLine();
}
});
}
);
AddCommand("value", "read value from VariableStack", (args) =>
{
if (args.Length != 2) return;
if (!Config.ContainsKey(args[1])) return;
string data = Config.GetValue<string>(args[1]);
Console.WriteLine($"{args[1]} => {data}");
}
);
AddCommand("add", "add variable to the system variables\nadd [key] [value] [isReadOnly=true/false]", async (args) =>
{
if (args.Length < 4) return;
string key = args[1];
string value = args[2];
bool isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase);
try
{
if (Config.ContainsKey(key)) return;
if (int.TryParse(value, out int intValue))
Config.AddValueToVariables(key, intValue, isReadOnly);
else if (bool.TryParse(value, out bool boolValue))
Config.AddValueToVariables(key, boolValue, isReadOnly);
else if (float.TryParse(value, out float floatValue))
Config.AddValueToVariables(key, floatValue, isReadOnly);
else if (double.TryParse(value, out double doubleValue))
Config.AddValueToVariables(key, doubleValue, isReadOnly);
else if (uint.TryParse(value, out uint uintValue))
Config.AddValueToVariables(key, uintValue, isReadOnly);
else if (long.TryParse(value, out long longValue))
Config.AddValueToVariables(key, longValue, isReadOnly);
else if (byte.TryParse(value, out byte byteValue))
Config.AddValueToVariables(key, byteValue, isReadOnly);
else
Config.AddValueToVariables(key, value, isReadOnly);
Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
);
AddCommand("remv", "remove variable from system variables", (args) =>
{
if (args.Length < 2) return;
Config.RemoveKey(args[1]);
}
);
AddCommand("vars", "Display all variables", () =>
{
var d = Config.GetAllVariables();
List<string[]> data = new List<string[]>();
data.Add(new string[] { "-", "-" });
data.Add(new string[] { "Key", "Value" });
data.Add(new string[] { "-", "-" });
foreach (var kvp in d) data.Add(new string[] { kvp.Key, kvp.Value.ToString() });
data.Add(new string[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(data);
}
);
AddCommand("sd", "Shuts down the discord bot", async () =>
{
await client.StopAsync();
await client.DisposeAsync();
Config.SaveConfig();
Environment.Exit(0);
}
);
}
public static void AddCommand(string command, string description, Action<string[]> action)
{
commandList.Add(new Tuple<string, string, Action<string[]>>(command, description, action));
Console.ForegroundColor = ConsoleColor.White;
Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
}
public static void AddCommand(string command, string description, Action action)
{
AddCommand(command, description, (args) => action());
}
public static void RemoveCommand(string command)
{
commandList.RemoveAll(x => x.Item1 == command);
}
public static Tuple<string, string, Action<string[]>>? SearchCommand(string command)
{
return commandList.FirstOrDefault(t => t.Item1 == command);
}
public void HandleCommand(string command)
{
string[] args = command.Split(' ');
foreach (var item in commandList.ToList())
AddCommand("value", "read value from VariableStack", args =>
{
if (item.Item1 == args[0])
if (args.Length != 2) return;
if (!Config.ContainsKey(args[1])) return;
var data = Config.GetValue<string>(args[1]);
Console.WriteLine($"{args[1]} => {data}");
}
);
AddCommand("add", "add variable to the system variables\nadd [key] [value] [isReadOnly=true/false]", async args =>
{
if (args.Length < 4) return;
var key = args[1];
var value = args[2];
var isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase);
try
{
item.Item3(args);
//Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
if (Config.ContainsKey(key)) return;
if (int.TryParse(value, out var intValue))
Config.AddValueToVariables(key, intValue, isReadOnly);
else if (bool.TryParse(value, out var boolValue))
Config.AddValueToVariables(key, boolValue, isReadOnly);
else if (float.TryParse(value, out var floatValue))
Config.AddValueToVariables(key, floatValue, isReadOnly);
else if (double.TryParse(value, out var doubleValue))
Config.AddValueToVariables(key, doubleValue, isReadOnly);
else if (uint.TryParse(value, out var uintValue))
Config.AddValueToVariables(key, uintValue, isReadOnly);
else if (long.TryParse(value, out var longValue))
Config.AddValueToVariables(key, longValue, isReadOnly);
else if (byte.TryParse(value, out var byteValue))
Config.AddValueToVariables(key, byteValue, isReadOnly);
else
Config.AddValueToVariables(key, value, isReadOnly);
Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
);
AddCommand("remv", "remove variable from system variables", args =>
{
if (args.Length < 2) return;
Config.RemoveKey(args[1]);
}
);
AddCommand("vars", "Display all variables", () =>
{
var d = Config.GetAllVariables();
var data = new List<string[]>();
data.Add(new[] { "-", "-" });
data.Add(new[] { "Key", "Value" });
data.Add(new[] { "-", "-" });
foreach (var kvp in d) data.Add(new[] { kvp.Key, kvp.Value.ToString() });
data.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(data);
}
);
AddCommand("sd", "Shuts down the discord bot", async () =>
{
if (client is null) return;
await client.StopAsync();
await client.DisposeAsync();
Config.SaveConfig();
Environment.Exit(0);
}
);
}
public static void AddCommand(string command, string description, Action<string[]> action)
{
commandList.Add(new Tuple<string, string, Action<string[]>>(command, description, action));
Console.ForegroundColor = ConsoleColor.White;
Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
}
public static void AddCommand(string command, string description, Action action)
{
AddCommand(command, description, args => action());
}
public static void RemoveCommand(string command)
{
commandList.RemoveAll(x => x.Item1 == command);
}
public static bool CommandExists(string command)
{
return !(GetCommand(command) is null);
}
public static Tuple<string, string, Action<string[]>>? GetCommand(string command)
{
return commandList.FirstOrDefault(t => t.Item1 == command);
}
public void HandleCommand(string command)
{
var args = command.Split(' ');
foreach (var item in commandList.ToList())
if (item.Item1 == args[0])
item.Item3(args);
//Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
}
}

View File

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

@@ -3,116 +3,105 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace PluginManager.Loaders
namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs
{
internal class LoaderArgs : EventArgs
{
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; }
internal object? Plugin { get; init; }
}
internal class Loader<T>
{
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal event FileLoadedEventHandler? FileLoaded;
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
internal event PluginLoadedEventHandler? PluginLoaded;
private string path { get; }
private string extension { get; }
internal Loader(string path, string extension)
{
this.path = path;
this.extension = extension;
}
internal List<T>? Load()
{
List<T> list = new List<T>();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return null;
}
string[] files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files)
{
Assembly.LoadFrom(file);
if (FileLoaded != null)
{
LoaderArgs args = new LoaderArgs()
{
Exception = null,
TypeName = nameof(T),
IsLoaded = false,
PluginName = file,
Plugin = null
};
FileLoaded.Invoke(args);
}
}
try
{
Type interfaceType = typeof(T);
Type[] types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
list.Clear();
foreach (Type type in types)
{
try
{
T plugin = (T)(Activator.CreateInstance(type)!);
list.Add(plugin);
if (PluginLoaded != null)
{
PluginLoaded.Invoke(new()
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = nameof(T),
Plugin = plugin
}
);
}
}
catch (Exception ex)
{
if (PluginLoaded != null)
{
PluginLoaded.Invoke(new() { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) });
}
}
}
}
catch (Exception ex)
{
Functions.WriteErrFile(ex.ToString());
}
return list;
}
}
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; }
internal object? Plugin { get; init; }
}
internal class Loader<T>
{
internal Loader(string path, string extension)
{
this.path = path;
this.extension = extension;
}
private string path { get; }
private string extension { get; }
internal event FileLoadedEventHandler? FileLoaded;
internal event PluginLoadedEventHandler? PluginLoaded;
internal List<T>? Load()
{
var list = new List<T>();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return null;
}
var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files)
{
Assembly.LoadFrom(file);
if (FileLoaded != null)
{
var args = new LoaderArgs
{
Exception = null,
TypeName = nameof(T),
IsLoaded = false,
PluginName = file,
Plugin = null
};
FileLoaded.Invoke(args);
}
}
try
{
var interfaceType = typeof(T);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
list.Clear();
foreach (var type in types)
try
{
var plugin = (T)Activator.CreateInstance(type)!;
list.Add(plugin);
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = nameof(T),
Plugin = plugin
}
);
}
catch (Exception ex)
{
if (PluginLoaded != null) PluginLoaded.Invoke(new LoaderArgs { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) });
}
}
catch (Exception ex)
{
Functions.WriteErrFile(ex.ToString());
}
return list;
}
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
}

View File

@@ -1,97 +1,97 @@
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Others;
using System;
using System.Collections.Generic;
namespace PluginManager.Loaders
namespace PluginManager.Loaders;
public class PluginLoader
{
public class PluginLoader
public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
private const string pluginEVEFolder = @"./Data/Plugins/Events/";
private const string pluginCMDExtension = "dll";
private const string pluginEVEExtension = "dll";
private readonly DiscordSocketClient _client;
/// <summary>
/// Event that is fired when a <see cref="DBCommand" /> is successfully loaded into commands list
/// </summary>
public CMDLoaded? onCMDLoad;
/// <summary>
/// Event that is fired when a <see cref="DBEvent" /> is successfully loaded into events list
/// </summary>
public EVELoaded? onEVELoad;
/// <summary>
/// The Plugin Loader constructor
/// </summary>
/// <param name="discordSocketClient">The discord bot client where the plugins will pe attached to</param>
public PluginLoader(DiscordSocketClient discordSocketClient)
{
private readonly DiscordSocketClient _client;
/// <summary>
/// The Plugin Loader constructor
/// </summary>
/// <param name="discordSocketClient">The discord bot client where the plugins will pe attached to</param>
public PluginLoader(DiscordSocketClient discordSocketClient) { this._client = discordSocketClient; }
private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
private const string pluginEVEFolder = @"./Data/Plugins/Events/";
private const string pluginCMDExtension = "dll";
private const string pluginEVEExtension = "dll";
_client = discordSocketClient;
}
/// <summary>
/// A list of <see cref="DBCommand"/> commands
/// </summary>
public static List<DBCommand>? Commands { get; set; }
/// <summary>
/// A list of <see cref="DBCommand" /> commands
/// </summary>
public static List<DBCommand>? Commands { get; set; }
/// <summary>
/// A list of <see cref="DBEvent"/> commands
/// </summary>
public static List<DBEvent>? Events { get; set; }
/// <summary>
/// A list of <see cref="DBEvent" /> commands
/// </summary>
public static List<DBEvent>? Events { get; set; }
/// <summary>
/// The main mathod that is called to load all events
/// </summary>
public void LoadPlugins()
{
Commands = new List<DBCommand>();
Events = new List<DBEvent>();
public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Console.WriteLine("Loading plugins");
public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
var commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
var eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
/// <summary>
/// Event that is fired when a <see cref="DBCommand"/> is successfully loaded into commands list
/// </summary>
public CMDLoaded? onCMDLoad;
commandsLoader.FileLoaded += OnCommandFileLoaded;
commandsLoader.PluginLoaded += OnCommandLoaded;
/// <summary>
/// Event that is fired when a <see cref="DBEvent"/> is successfully loaded into events list
/// </summary>
public EVELoaded? onEVELoad;
eventsLoader.FileLoaded += EventFileLoaded;
eventsLoader.PluginLoaded += OnEventLoaded;
/// <summary>
/// The main mathod that is called to load all events
/// </summary>
public void LoadPlugins()
{
Commands = new List<DBCommand>();
Events = new List<DBEvent>();
Commands = commandsLoader.Load();
Events = eventsLoader.Load();
}
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Console.WriteLine("Loading plugins");
private void EventFileLoaded(LoaderArgs e)
{
if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !");
}
Loader<DBCommand> commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
Loader<DBEvent> eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
private void OnCommandFileLoaded(LoaderArgs e)
{
if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !");
}
commandsLoader.FileLoaded += OnCommandFileLoaded;
commandsLoader.PluginLoaded += OnCommandLoaded;
private void OnEventLoaded(LoaderArgs e)
{
if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client);
eventsLoader.FileLoaded += EventFileLoaded;
eventsLoader.PluginLoaded += OnEventLoaded;
if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception);
}
Commands = commandsLoader.Load();
Events = eventsLoader.Load();
}
private void EventFileLoaded(LoaderArgs e)
{
if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !");
}
private void OnCommandFileLoaded(LoaderArgs e)
{
if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !");
}
private void OnEventLoaded(LoaderArgs e)
{
if (e.IsLoaded) { ((DBEvent)e.Plugin!).Start(_client); }
if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception);
}
private void OnCommandLoaded(LoaderArgs e)
{
if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
}
private void OnCommandLoaded(LoaderArgs e)
{
if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
}
}

View File

@@ -1,86 +1,82 @@
using System;
using System.IO;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager.Online
namespace PluginManager.Online;
public class LanguageManager
{
public class LanguageManager
private readonly string link;
/// <summary>
/// The Language Manager constructor
/// </summary>
/// <param name="link">The link to where all the languages for the bot are stored</param>
public LanguageManager(string link)
{
private string link;
this.link = link;
}
/// <summary>
/// The Language Manager constructor
/// </summary>
/// <param name="link">The link to where all the languages for the bot are stored</param>
public LanguageManager(string link) => this.link = link;
/// <summary>
/// The method to list all languages
/// </summary>
/// <returns></returns>
public async Task ListAllLanguages()
/// <summary>
/// The method to list all languages
/// </summary>
/// <returns></returns>
public async Task ListAllLanguages()
{
try
{
var list = await ServerCom.ReadTextFromFile(link);
var lines = list.ToArray();
try
var info = new List<string[]>();
info.Add(new[] { "-", "-" });
info.Add(new[] { "Language Name", "File Size" });
info.Add(new[] { "-", "-" });
foreach (var line in lines)
{
List<string> list = await ServerCom.ReadTextFromFile(link);
string[] lines = list.ToArray();
List<string[]> info = new List<string[]>();
info.Add(new string[] { "-", "-" });
info.Add(new string[] { "Language Name", "File Size" });
info.Add(new string[] { "-", "-" });
foreach (var line in lines)
{
if (line.Length <= 2) continue;
string[] d = line.Split(',');
if (d[3].Contains("cp") || d[3].Contains("CrossPlatform"))
info.Add(new string[] { d[0], d[1] });
}
info.Add(new string[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(info);
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString());
if (line.Length <= 2) continue;
var d = line.Split(',');
if (d[3].Contains("cp") || d[3].Contains("CrossPlatform")) info.Add(new[] { d[0], d[1] });
}
info.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(info);
}
/// <summary>
/// A function that gets the download link for specified language
/// </summary>
/// <param name="langName">The name of the language</param>
/// <returns></returns>
public async Task<string[]?> GetDownloadLink(string langName)
catch (Exception exception)
{
try
{
List<string> list = await ServerCom.ReadTextFromFile(link);
string[] lines = list.ToArray();
foreach (var line in lines)
{
if (line.Length <= 2) continue;
string[] d = line.Split(',');
if (d[0].Equals(langName) && (d[3].Contains("cp") || d[3].Contains("CrossPlatform")))
return new string[] { d[2], d[3] };
}
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString());
}
return null;
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
}
}
}
/// <summary>
/// A function that gets the download link for specified language
/// </summary>
/// <param name="langName">The name of the language</param>
/// <returns></returns>
public async Task<string[]?> GetDownloadLink(string langName)
{
try
{
var list = await ServerCom.ReadTextFromFile(link);
var lines = list.ToArray();
foreach (var line in lines)
{
if (line.Length <= 2) continue;
var d = line.Split(',');
if (d[0].Equals(langName) && (d[3].Contains("cp") || d[3].Contains("CrossPlatform"))) return new[] { d[2], d[3] };
}
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
}
return null;
}
}

View File

@@ -1,128 +1,118 @@
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading.Tasks;
using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Online
namespace PluginManager.Online;
public class PluginsManager
{
public class PluginsManager
/// <summary>
/// The Plugin Manager constructor
/// </summary>
/// <param name="link">The link to the file where all plugins are stored</param>
public PluginsManager(string link)
{
/// <summary>
/// The URL of the server
/// </summary>
public string PluginsLink { get; private set; }
PluginsLink = link;
}
/// <summary>
/// The Plugin Manager constructor
/// </summary>
/// <param name="link">The link to the file where all plugins are stored</param>
public PluginsManager(string link)
{
PluginsLink = link;
}
/// <summary>
/// The URL of the server
/// </summary>
public string PluginsLink { get; }
/// <summary>
/// The method to load all plugins
/// </summary>
/// <returns></returns>
public async Task ListAvailablePlugins()
/// <summary>
/// The method to load all plugins
/// </summary>
/// <returns></returns>
public async Task ListAvailablePlugins()
{
try
{
try
var list = await ServerCom.ReadTextFromFile(PluginsLink);
var lines = list.ToArray();
var data = new List<string[]>();
var op = Functions.GetOperatingSystem();
var len = lines.Length;
string[] titles = { "Name", "Description", "Plugin Type", "Libraries" };
data.Add(new[] { "-", "-", "-", "-" });
data.Add(titles);
data.Add(new[] { "-", "-", "-", "-" });
for (var i = 0; i < len; i++)
{
List<string> list = await ServerCom.ReadTextFromFile(PluginsLink);
string[] lines = list.ToArray();
List<string[]> data = new List<string[]>();
var op = Functions.GetOperatingSystem();
int len = lines.Length;
string[] titles = { "Name", "Description", "Plugin Type", "Libraries" };
data.Add(new string[] { "-", "-", "-", "-" });
data.Add(titles);
data.Add(new string[] { "-", "-", "-", "-" });
for (int i = 0; i < len; i++)
if (lines[i].Length <= 2) continue;
var content = lines[i].Split(',');
var display = new string[4];
if (op == OperatingSystem.WINDOWS)
{
if (lines[i].Length <= 2) continue;
string[] content = lines[i].Split(',');
string[] display = new string[4];
if (op == Others.OperatingSystem.WINDOWS)
if (content[4].Contains("Windows"))
{
if (content[4].Contains("Windows"))
{
display[0] = content[0];
display[1] = content[1];
display[2] = content[2];
if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
display[0] = content[0];
display[1] = content[1];
display[2] = content[2];
if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
else display[3] = "1";
data.Add(display);
continue;
}
}
else if (op == Others.OperatingSystem.LINUX)
{
if (content[4].Contains("Linux"))
{
display[0] = content[0];
display[1] = content[1];
display[2] = content[2];
data.Add(display);
continue;
}
else
display[3] = "1";
data.Add(display);
}
}
data.Add(new string[] { "-", "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(data);
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString());
}
}
/// <summary>
/// The method to get plugin information by its name
/// </summary>
/// <param name="name">The plugin name</param>
/// <returns></returns>
public async Task<string[]> GetPluginLinkByName(string name)
{
try
{
List<string> list = await ServerCom.ReadTextFromFile(PluginsLink);
string[] lines = list.ToArray();
int len = lines.Length;
for (int i = 0; i < len; i++)
else if (op == OperatingSystem.LINUX)
{
string[] contents = lines[i].Split(',');
if (contents[0] == name)
if (content[4].Contains("Linux"))
{
if (contents.Length == 6)
return new string[] { contents[2], contents[3], contents[5] };
else if (contents.Length == 5)
return new string[] { contents[2], contents[3], string.Empty };
else throw new Exception("Failed to download plugin. Invalid Argument Length");
display[0] = content[0];
display[1] = content[1];
display[2] = content[2];
data.Add(display);
}
}
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString());
}
return new string[] { null!, null!, null! };
data.Add(new[] { "-", "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(data);
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
}
}
/// <summary>
/// The method to get plugin information by its name
/// </summary>
/// <param name="name">The plugin name</param>
/// <returns></returns>
public async Task<string[]> GetPluginLinkByName(string name)
{
try
{
var list = await ServerCom.ReadTextFromFile(PluginsLink);
var lines = list.ToArray();
var len = lines.Length;
for (var i = 0; i < len; i++)
{
var contents = lines[i].Split(',');
if (contents[0] == name)
{
if (contents.Length == 6) return new[] { contents[2], contents[3], contents[5] };
if (contents.Length == 5) return new[] { contents[2], contents[3], string.Empty };
throw new Exception("Failed to download plugin. Invalid Argument Length");
}
}
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
}
return new string[] { null!, null!, null! };
}
}

View File

@@ -1,10 +1,11 @@
using PluginManager.Online.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager.Online
{
@@ -51,37 +52,35 @@ namespace PluginManager.Online
/// <returns></returns>
public static async Task DownloadFileAsync(string URL, string location)
{
bool isDownloading = true;
int c_progress = 0;
bool isDownloading = true;
int c_progress = 0;
Others.Console_Utilities.ProgressBar pbar = new Others.Console_Utilities.ProgressBar(100, "");
Console_Utilities.ProgressBar pbar = new Console_Utilities.ProgressBar { Max = 100, NoColor = true };
IProgress<float> progress = new Progress<float>(percent =>
{
c_progress = (int)percent;
});
Task updateProgressBarTask = new Task(() =>
{
while (isDownloading)
{
pbar.Update(c_progress);
if (c_progress == 100)
break;
System.Threading.Thread.Sleep(500);
}
});
new System.Threading.Thread(updateProgressBarTask.Start).Start();
Task updateProgressBarTask = new Task(() =>
{
while (isDownloading)
{
pbar.Update(c_progress);
if (c_progress == 100) break;
Thread.Sleep(500);
}
}
);
new Thread(updateProgressBarTask.Start).Start();
await DownloadFileAsync(URL, location, progress);
c_progress = 100;
pbar.Update(100);
isDownloading = false;
}
}
}

View File

@@ -1,42 +1,60 @@
using System.Threading.Tasks;
using Discord;
using System.Threading.Tasks;
namespace PluginManager.Others;
namespace PluginManager.Others
/// <summary>
/// A class that handles the sending of messages to the user.
/// </summary>
public static class ChannelManagement
{
/// <summary>
/// A class that handles the sending of messages to the user.
/// Get the text channel by name from server
/// </summary>
public static class ChannelManagement
/// <param name="server">The server</param>
/// <param name="name">The channel name</param>
/// <returns>
/// <see cref="IGuildChannel" />
/// </returns>
public static IGuildChannel GetTextChannel(this IGuild server, string name)
{
/// <summary>
/// Get the text channel by name from server
/// </summary>
/// <param name="server">The server</param>
/// <param name="name">The channel name</param>
/// <returns><see cref="IGuildChannel"/></returns>
public static IGuildChannel GetTextChannel(this IGuild server, string name) => server.GetTextChannel(name);
/// <summary>
/// Get the voice channel by name from server
/// </summary>
/// <param name="server">The server</param>
/// <param name="name">The channel name</param>
/// <returns><see cref="IGuildChannel"/></returns>
public static IGuildChannel GetVoiceChannel(this IGuild server, string name) => server.GetVoiceChannel(name);
/// <summary>
/// Get the DM channel between <see cref="Discord.WebSocket.DiscordSocketClient"/> and <see cref="IGuildUser"/>
/// </summary>
/// <param name="user"></param>
/// <returns><see cref="IDMChannel"/></returns>
public static async Task<IDMChannel> GetDMChannel(IGuildUser user) => await user.CreateDMChannelAsync();
/// <summary>
/// Get the channel where the message was sent
/// </summary>
/// <param name="message">The message</param>
/// <returns><see cref="IChannel"/></returns>
public static IChannel GetChannel(IMessage message) => message.Channel;
return server.GetTextChannel(name);
}
}
/// <summary>
/// Get the voice channel by name from server
/// </summary>
/// <param name="server">The server</param>
/// <param name="name">The channel name</param>
/// <returns>
/// <see cref="IGuildChannel" />
/// </returns>
public static IGuildChannel GetVoiceChannel(this IGuild server, string name)
{
return server.GetVoiceChannel(name);
}
/// <summary>
/// Get the DM channel between <see cref="Discord.WebSocket.DiscordSocketClient" /> and <see cref="IGuildUser" />
/// </summary>
/// <param name="user"></param>
/// <returns>
/// <see cref="IDMChannel" />
/// </returns>
public static async Task<IDMChannel> GetDMChannel(IGuildUser user)
{
return await user.CreateDMChannelAsync();
}
/// <summary>
/// Get the channel where the message was sent
/// </summary>
/// <param name="message">The message</param>
/// <returns>
/// <see cref="IChannel" />
/// </returns>
public static IChannel GetChannel(IMessage message)
{
return message.Channel;
}
}

View File

@@ -10,23 +10,13 @@ namespace PluginManager.Others
/// </summary>
public class ProgressBar
{
public int Max { get; set; }
public string Message { get; set; }
public int Max { get; init; }
public ConsoleColor Color { get; init; }
public bool NoColor { get; init; }
public ProgressBar(int max, string message)
{
Max = max;
Message = message;
var consoleColors = Enum.GetValues(typeof(ConsoleColor));
while ((Color = (ConsoleColor)consoleColors.GetValue(new Random().Next(consoleColors.Length))!) == ConsoleColor.White && Color != ConsoleColor.Black) ;
}
public void Update(int progress, double speed = -1, string? unit = null)
{
//progress bar
Console.CursorLeft = 0;
Console.Write("[");
Console.CursorLeft = 32;
@@ -38,15 +28,21 @@ namespace PluginManager.Others
for (int i = 0; i < onechunk * progress; i++)
{
Console.BackgroundColor = this.Color;
if (NoColor)
Console.BackgroundColor = ConsoleColor.Black; //this.Color
else
Console.BackgroundColor = this.Color;
Console.CursorLeft = position++;
Console.Write(" ");
Console.Write("#");
}
for (int i = position; i <= 31; i++)
{
Console.BackgroundColor = ConsoleColor.Gray;
Console.CursorLeft = position++;
if (NoColor)
Console.BackgroundColor = ConsoleColor.Black; // background of empty bar
else
Console.BackgroundColor = ConsoleColor.DarkGray;
Console.CursorLeft = position++;
Console.Write(" ");
}

View File

@@ -1,91 +1,88 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others
namespace PluginManager.Others;
public class Cryptography
{
public class Cryptography
/// <summary>
/// Translate hex to string
/// </summary>
/// <param name="hexString">The encrypted string</param>
/// <returns></returns>
public static string FromHexToString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++) bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
/// <summary>
/// Translate hex to string
/// </summary>
/// <param name="hexString">The encrypted string</param>
/// <returns></returns>
public static string FromHexToString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return System.Text.Encoding.Unicode.GetString(bytes);
}
/// <summary>
/// Translate string to hex
/// </summary>
/// <param name="str">The string to encrypt</param>
/// <returns></returns>
public static string ToHexString(string str)
{
var sb = new System.Text.StringBuilder();
var bytes = System.Text.Encoding.Unicode.GetBytes(str);
foreach (var t in bytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Create MD5 hash
/// </summary>
/// <param name="text">The text to encrypt</param>
/// <returns></returns>
public static async System.Threading.Tasks.Task<string> CreateMD5(string text)
{
string output = "";
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
using (var s = GenerateStreamFromString(text))
{
byte[] t = await md5.ComputeHashAsync(s);
output = System.Convert.ToBase64String(t);
}
}
return output;
}
/// <summary>
/// Create SHA256 hash
/// </summary>
/// <param name="text">The text to encrypt</param>
/// <returns></returns>
public static async System.Threading.Tasks.Task<string> CreateSHA256(string text)
{
string output = "";
using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create())
{
using (var s = GenerateStreamFromString(text))
{
byte[] t = await sha.ComputeHashAsync(s);
output = System.Convert.ToBase64String(t);
}
}
return output;
}
private static System.IO.Stream GenerateStreamFromString(string s)
{
var stream = new System.IO.MemoryStream();
var writer = new System.IO.StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
return Encoding.Unicode.GetString(bytes);
}
}
/// <summary>
/// Translate string to hex
/// </summary>
/// <param name="str">The string to encrypt</param>
/// <returns></returns>
public static string ToHexString(string str)
{
var sb = new StringBuilder();
var bytes = Encoding.Unicode.GetBytes(str);
foreach (var t in bytes) sb.Append(t.ToString("X2"));
return sb.ToString();
}
/// <summary>
/// Create MD5 hash
/// </summary>
/// <param name="text">The text to encrypt</param>
/// <returns></returns>
public static async Task<string> CreateMD5(string text)
{
var output = "";
using (var md5 = MD5.Create())
{
using (var s = GenerateStreamFromString(text))
{
var t = await md5.ComputeHashAsync(s);
output = Convert.ToBase64String(t);
}
}
return output;
}
/// <summary>
/// Create SHA256 hash
/// </summary>
/// <param name="text">The text to encrypt</param>
/// <returns></returns>
public static async Task<string> CreateSHA256(string text)
{
var output = "";
using (var sha = SHA256.Create())
{
using (var s = GenerateStreamFromString(text))
{
var t = await sha.ComputeHashAsync(s);
output = Convert.ToBase64String(t);
}
}
return output;
}
private static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}

View File

@@ -1,20 +1,22 @@
namespace PluginManager.Others
namespace PluginManager.Others;
/// <summary>
/// A list of operating systems
/// </summary>
public enum OperatingSystem
{
WINDOWS, LINUX, MAC_OS, UNKNOWN
}
/// <summary>
/// A list of operating systems
/// </summary>
public enum OperatingSystem
{ WINDOWS, LINUX, MAC_OS, UNKNOWN }
/// <summary>
/// A list with all errors
/// </summary>
public enum Error
{
UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS
}
/// <summary>
/// A list with all errors
/// </summary>
public enum Error
{ UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS }
/// <summary>
/// The output log type
/// </summary>
public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL }
}
/// <summary>
/// The output log type
/// </summary>
public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL }

View File

@@ -1,94 +1,91 @@
using System;
namespace PluginManager.Others.Exceptions
namespace PluginManager.Others.Exceptions;
/// <summary>
/// Custom Exception for PluginManager
/// </summary>
[Serializable]
public class APIException : Exception
{
/// <summary>
/// Custom Exception for PluginManager
/// The APIException contructor
/// </summary>
[Serializable]
public class APIException : Exception
/// <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)
{
/// <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>
/// 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>
/// 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.ToString());
Console.WriteLine("Possible cause: " + PossibleCause);
if (this.StackTrace != null)
Functions.WriteErrFile(this.StackTrace);
}
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

@@ -212,11 +212,22 @@ namespace PluginManager.Others
/// <returns></returns>
public static (double, string) ConvertBytes(long bytes)
{
if (bytes < 1024) return (bytes, "B");
if (bytes < 1024 * 1024) return (bytes / 1024.0, "KB");
if (bytes < 1024 * 1024 * 1024) return (bytes / 1024.0 / 1024.0, "MB");
return (bytes / 1024.0 / 1024.0 / 1024.0, "GB");
List<string> units = new List<string>()
{
"B",
"KB",
"MB",
"GB",
"TB"
};
int i = 0;
while (bytes >= 1024)
{
i++;
bytes /= 1024;
}
return (bytes, units[i]);
}
/// <summary>

View File

@@ -1,55 +1,64 @@
using Discord;
using System.Linq;
using Discord;
using Discord.WebSocket;
using System.Linq;
namespace PluginManager.Others.Permissions;
namespace PluginManager.Others.Permissions
/// <summary>
/// A class whith all discord permissions
/// </summary>
public static class DiscordPermissions
{
/// <summary>
/// A class whith all discord permissions
/// Checks if the role has the specified permission
/// </summary>
public static class DiscordPermissions
/// <param name="role">The role</param>
/// <param name="permission">The permission</param>
/// <returns></returns>
public static bool hasPermission(this IRole role, GuildPermission permission)
{
/// <summary>
/// Checks if the role has the specified permission
/// </summary>
/// <param name="role">The role</param>
/// <param name="permission">The permission</param>
/// <returns></returns>
public static bool hasPermission(this IRole role, GuildPermission permission) => role.Permissions.Has(permission);
/// <summary>
/// Check if user has the specified role
/// </summary>
/// <param name="user">The user</param>
/// <param name="role">The role</param>
/// <returns></returns>
public static bool hasRole(this SocketGuildUser user, IRole role) => user.Roles.Contains(role);
/// <summary>
/// Check if user has the specified permission
/// </summary>
/// <param name="user">The user</param>
/// <param name="permission">The permission</param>
/// <returns></returns>
public static bool hasPermission(this SocketGuildUser user, GuildPermission permission)
=> user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user;
/// <summary>
/// Check if user is administrator of server
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketGuildUser user) => user.hasPermission(GuildPermission.Administrator);
/// <summary>
/// Check if user is administrator of server
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketUser user) => isAdmin((SocketGuildUser)user);
return role.Permissions.Has(permission);
}
/// <summary>
/// Check if user has the specified role
/// </summary>
/// <param name="user">The user</param>
/// <param name="role">The role</param>
/// <returns></returns>
public static bool hasRole(this SocketGuildUser user, IRole role)
{
return user.Roles.Contains(role);
}
/// <summary>
/// Check if user has the specified permission
/// </summary>
/// <param name="user">The user</param>
/// <param name="permission">The permission</param>
/// <returns></returns>
public static bool hasPermission(this SocketGuildUser user, GuildPermission permission)
{
return user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user;
}
/// <summary>
/// Check if user is administrator of server
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketGuildUser user)
{
return user.hasPermission(GuildPermission.Administrator);
}
}
/// <summary>
/// Check if user is administrator of server
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketUser user)
{
return isAdmin((SocketGuildUser)user);
}
}