diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/.gitignore b/.idea/.idea.DiscordBotWithAPI/.idea/.gitignore new file mode 100644 index 0000000..1e2399a --- /dev/null +++ b/.idea/.idea.DiscordBotWithAPI/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/modules.xml +/contentModel.xml +/.idea.DiscordBotWithAPI.iml +/projectSettingsUpdater.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/avalonia.xml b/.idea/.idea.DiscordBotWithAPI/.idea/avalonia.xml new file mode 100644 index 0000000..c0fdb9d --- /dev/null +++ b/.idea/.idea.DiscordBotWithAPI/.idea/avalonia.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/encodings.xml b/.idea/.idea.DiscordBotWithAPI/.idea/encodings.xml new file mode 100644 index 0000000..df87cf9 --- /dev/null +++ b/.idea/.idea.DiscordBotWithAPI/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/indexLayout.xml b/.idea/.idea.DiscordBotWithAPI/.idea/indexLayout.xml new file mode 100644 index 0000000..7b08163 --- /dev/null +++ b/.idea/.idea.DiscordBotWithAPI/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/vcs.xml b/.idea/.idea.DiscordBotWithAPI/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/.idea.DiscordBotWithAPI/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/BUILDS/net6.0/EVE_LevelingSystem.dll b/BUILDS/net6.0/EVE_LevelingSystem.dll index e443461..58c77e5 100644 Binary files a/BUILDS/net6.0/EVE_LevelingSystem.dll and b/BUILDS/net6.0/EVE_LevelingSystem.dll differ diff --git a/BUILDS/net6.0/PluginManager.dll b/BUILDS/net6.0/PluginManager.dll index 856115d..484c585 100644 Binary files a/BUILDS/net6.0/PluginManager.dll and b/BUILDS/net6.0/PluginManager.dll differ diff --git a/DiscordBot/App.config b/DiscordBot/App.config index 2a5ff10..828bd34 100644 --- a/DiscordBot/App.config +++ b/DiscordBot/App.config @@ -1,4 +1,7 @@ - - - - \ No newline at end of file + + + + + + + diff --git a/DiscordBot/Discord/Commands/Help.cs b/DiscordBot/Discord/Commands/Help.cs index 67840a5..26a1c51 100644 --- a/DiscordBot/Discord/Commands/Help.cs +++ b/DiscordBot/Discord/Commands/Help.cs @@ -75,12 +75,11 @@ namespace DiscordBot.Discord.Commands string normalCommands = ""; string DMCommands = ""; - foreach (var cmd in PluginLoader.Plugins!) + foreach (var cmd in PluginLoader.Commands!) { - if (cmd.canUseDM) - DMCommands += cmd.Command + " "; + if (cmd.canUseDM) DMCommands += cmd.Command + " "; if (cmd.requireAdmin) - adminCommands += cmd.Command + " "; + adminCommands += cmd.Command + " "; else if (cmd.canUseServer) normalCommands += cmd.Command + " "; } @@ -94,7 +93,7 @@ namespace DiscordBot.Discord.Commands private EmbedBuilder GenerateHelpCommand(string command) { EmbedBuilder embedBuilder = new EmbedBuilder(); - DBCommand cmd = PluginLoader.Plugins.Find(p => p.Command == command); + DBCommand cmd = PluginLoader.Commands.Find(p => p.Command == command); if (cmd == null) return null; diff --git a/DiscordBot/Discord/Core/CommandHandler.cs b/DiscordBot/Discord/Core/CommandHandler.cs index 5ed266b..b877f79 100644 --- a/DiscordBot/Discord/Core/CommandHandler.cs +++ b/DiscordBot/Discord/Core/CommandHandler.cs @@ -80,7 +80,7 @@ namespace PluginManager.Core services: null ); - DBCommand plugin = PluginLoader.Plugins!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); + DBCommand plugin = PluginLoader.Commands!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); if (plugin != null) diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index 9c1a719..903d078 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -1,16 +1,14 @@ using Discord; - using System; using System.IO; using System.Threading.Tasks; - using PluginManager.Core; using PluginManager.Others; using PluginManager.LanguageSystem; using PluginManager.Online; - using System.Collections.Generic; using System.Linq; +using System.Threading; using PluginManager.Items; namespace DiscordBot @@ -20,21 +18,23 @@ namespace DiscordBot private static bool loadPluginsOnStartup = false; private static bool listPluginsAtStartup = false; private static bool listLanguagAtStartup = false; - - private static bool ShowStartupMessage = true; + //private static bool ShowStartupMessage = true; /// /// The main entry point for the application. /// [STAThread] [Obsolete] - public static void Main(string[] args) { Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Languages"); Directory.CreateDirectory("./Data/Plugins/Commands"); Directory.CreateDirectory("./Data/Plugins/Events"); + Directory.CreateDirectory("./Data/runtime"); + + AppDomain.CurrentDomain.AppendPrivatePath("./Data/runtime"); + if (!File.Exists("./Data/Resources/DiscordBotCore.data") || (Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 59 && Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 70)) { File.WriteAllText("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN=token\nBOT_PREFIX=!\n"); @@ -45,13 +45,13 @@ namespace DiscordBot string botToken = Console.ReadLine(); if (botToken.Length == 59 || botToken.Length == 70) { - string prefix = Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_PREFIX", '='); - if (prefix == string.Empty || prefix == null) - prefix = "!"; + string prefix = Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_PREFIX", '='); + if (prefix == string.Empty || prefix == null) prefix = "!"; File.WriteAllText("./Data/Resources/DiscordBotCore.data", $"BOT_TOKEN={botToken}\nBOT_PREFIX={prefix}\n"); break; } - else Console.WriteLine("Invalid Token !"); + else + Console.WriteLine("Invalid Token !"); } } @@ -72,17 +72,14 @@ namespace DiscordBot /// The main loop for the discord bot /// /// The discord booter used to start the application - private static async Task NoGUI(Boot discordbooter) + private static Task NoGUI(Boot discordbooter) { Language.LoadLanguage(); ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client); - if (loadPluginsOnStartup) - consoleCommandsHandler.HandleCommand("lp"); - if (listPluginsAtStartup) - consoleCommandsHandler.HandleCommand("listplugs"); - if (listLanguagAtStartup) - consoleCommandsHandler.HandleCommand("listlang"); + if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); + if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs"); + if (listLanguagAtStartup) consoleCommandsHandler.HandleCommand("listlang"); while (true) { @@ -98,23 +95,14 @@ namespace DiscordBot /// Returns the boot loader for the Discord Bot private static async Task StartNoGUI() { - Console.Clear(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Discord BOT for Cross Platform"); Console.WriteLine("Created by: Wizzy\nDiscord: Wizzy#9181"); - if (ShowStartupMessage) - try - { - Console.WriteLine("Connecting to server ..."); - List text = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/StartupMessage"); - foreach (var t in text) Console_Utilities.WriteColorText(t); - } - catch { Console.WriteLine("Failed to connect to server."); } Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("============================ Discord BOT - Cross Platform ============================"); - string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '='); + string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '='); string prefix = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_PREFIX", '='); var discordbooter = new Boot(token, prefix); @@ -128,8 +116,8 @@ namespace DiscordBot /// Directory path private static Task ClearFolder(string d) { - string[] files = Directory.GetFiles(d); - int fileNumb = files.Length; + string[] files = Directory.GetFiles(d); + int fileNumb = files.Length; for (var i = 0; i < fileNumb; i++) { File.Delete(files[i]); @@ -145,7 +133,6 @@ namespace DiscordBot /// The arguments private static async Task HandleInput(string[] args) { - if (args.Length == 0) { if (File.Exists("./ref/startupArguments.txt")) @@ -164,8 +151,12 @@ namespace DiscordBot if (len == 1 && args[0] == "--logout") { - File.Delete(Functions.dataFolder + "Login.dat"); - Console.WriteLine("Logged out. Please restart the application !"); + File.Delete(Functions.dataFolder + "DiscordBotCore.dat"); + await Task.Run(async () => + { + await Task.Delay(1000); + Environment.Exit(0x08); + }); return; } @@ -179,20 +170,14 @@ namespace DiscordBot if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage"))) { - if (args.Contains("lp") || args.Contains("loadplugins")) - loadPluginsOnStartup = true; - if (args.Contains("listplugs")) - listPluginsAtStartup = true; - if (args.Contains("listlang")) - listLanguagAtStartup = true; - if (args.Contains("--nomessage")) - ShowStartupMessage = false; + if (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true; + if (args.Contains("listplugs")) listPluginsAtStartup = true; + if (args.Contains("listlang")) listLanguagAtStartup = true; + //if (args.Contains("--nomessage")) ShowStartupMessage = false; len = 0; } - - if (len == 0 || args[0] != "--exec" && args[0] != "--execute") { Boot b = await StartNoGUI(); diff --git a/DiscordBotGUI/App.axaml.cs b/DiscordBotGUI/App.axaml.cs index a3b2c89..456aca5 100644 --- a/DiscordBotGUI/App.axaml.cs +++ b/DiscordBotGUI/App.axaml.cs @@ -1,6 +1,8 @@ +using System.IO; using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; +using PluginManager.Others; namespace DiscordBotGUI { @@ -13,13 +15,7 @@ namespace DiscordBotGUI public override void OnFrameworkInitializationCompleted() { - if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - { - - - desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen }; - - } + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen }; } base.OnFrameworkInitializationCompleted(); } diff --git a/DiscordBotGUI/AppUpdater.axaml.cs b/DiscordBotGUI/AppUpdater.axaml.cs index ecc5405..8c4dccc 100644 --- a/DiscordBotGUI/AppUpdater.axaml.cs +++ b/DiscordBotGUI/AppUpdater.axaml.cs @@ -21,42 +21,48 @@ namespace DiscordBotGUI InitializeComponent(); if (!File.Exists("./Version.txt")) { - textBox1.Text = "Checking ..."; File.WriteAllText("./Version.txt", "DiscordBotVersion=0"); - //DownloadDiscordBotClientNoGUIAsDLL(); + DownloadDiscordBotClientNoGUIAsDLL(); } + if (!File.Exists("./DiscordBot.exe")) DownloadDiscordBotClientNoGUIAsDLL(); Updates(); } - /* private async void DownloadDiscordBotClientNoGUIAsDLL() - { + private async void DownloadDiscordBotClientNoGUIAsDLL() + { + //await Task.Delay(5000); + string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.zip"; + int actiontype = 0; //0 - downolad, 1- extract + IProgress progress = new Progress((percent) => + { + if (actiontype == 0) + textBox1.Text = "Downloading DiscordBot ... " + MathF.Round(percent, 2) + "%"; + else + textBox1.Text = "Extracting package ..." + MathF.Round(percent, 2) + "%"; + this.progressBar1.Value = percent; + }); - //await Task.Delay(5000); - string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.dll"; - IProgress progress = new Progress((percent) => - { - textBox1.Text = "Downloading DiscordBot.dll ... " + (percent * 100).ToString() + "%"; - this.progressBar1.Value = percent * 100; - }); + this.progressBar1.IsIndeterminate = false; + try + { + await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.zip", progress); - this.progressBar1.IsIndeterminate = false; - try - { - await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.dll", progress); - } - catch - { - textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding."; + actiontype++; - await Task.Delay(1000); - return; - } + await Functions.ExtractArchive("./DiscordBot.zip", "./", progress); + } + catch + { + textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding."; - //new MainWindow() { Height = 425, Width = 500 }.Show(); - //Close(); - }*/ + await Task.Delay(1000); + + new MainWindow() { Height = 425, Width = 500 }.Show(); + Close(); + } + } private async void Updates() { diff --git a/DiscordBotWithAPI.sln b/DiscordBotWithAPI.sln index 3f9ab41..7bf0ffe 100644 --- a/DiscordBotWithAPI.sln +++ b/DiscordBotWithAPI.sln @@ -23,8 +23,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CMD_Utils", "CMD_Utils\CMD_ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicCommands", "MusicCommands\MusicCommands.csproj", "{B1B4976E-5112-4217-B57B-3A03C5207B6E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Games", "FreeGames\Games.csproj", "{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotGUI", "DiscordBotGUI\DiscordBotGUI.csproj", "{7B5899F0-0218-4537-8C74-6210ED2D3690}" EndProject Global @@ -61,10 +59,6 @@ Global {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.Build.0 = Release|Any CPU - {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Release|Any CPU.Build.0 = Release|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -81,7 +75,6 @@ Global {CE9DBF06-38A0-4192-8B3E-4009210D040D} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012} {E26C87A4-3DD6-4B58-B14B-C8E086B852F9} = {449FA364-0B72-43FF-B3A3-806E2916200E} {B1B4976E-5112-4217-B57B-3A03C5207B6E} = {449FA364-0B72-43FF-B3A3-806E2916200E} - {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB} = {449FA364-0B72-43FF-B3A3-806E2916200E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF} diff --git a/PluginManager/Loaders/CommandsLoader.cs b/PluginManager/Loaders/CommandsLoader.cs deleted file mode 100644 index 919fa6b..0000000 --- a/PluginManager/Loaders/CommandsLoader.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; - -using PluginManager.Interfaces; - -namespace PluginManager.Loaders -{ - internal class CommandsLoader - { - private readonly string CMDPath; - private readonly string CMDExtension; - - - internal delegate void onCommandLoaded(string name, bool success, DBCommand? command = null, Exception? exception = null); - internal delegate void onCommandFileLoaded(string path); - - /// - /// Event fired when a command is loaded - /// - internal onCommandLoaded? OnCommandLoaded; - - /// - /// Event fired when the file is loaded - /// - internal onCommandFileLoaded? OnCommandFileLoaded; - - /// - /// Command Loader contructor - /// - /// The path to the commands - /// The extension to search for in the - internal CommandsLoader(string CommandPath, string CommandExtension) - { - CMDPath = CommandPath; - CMDExtension = CommandExtension; - } - - /// - /// The method that loads all commands - /// - /// - internal List? LoadCommands() - { - if (!Directory.Exists(CMDPath)) - { - Directory.CreateDirectory(CMDPath); - return null; - } - string[] files = Directory.GetFiles(CMDPath, $"*{CMDExtension}", SearchOption.AllDirectories); - - foreach (var file in files) - { - Assembly.LoadFile(Path.GetFullPath(file)); - if (OnCommandFileLoaded != null) - OnCommandFileLoaded.Invoke(file); - } - - List plugins = new List(); - - try - { - Type interfaceType = typeof(DBCommand); - Type[] types = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(a => a.GetTypes()) - .Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass) - .ToArray(); - foreach (Type type in types) - { - try - { - DBCommand plugin = (DBCommand)Activator.CreateInstance(type)!; - plugins.Add(plugin); - - if (OnCommandLoaded != null) - OnCommandLoaded.Invoke(type.FullName!, true, plugin); - } - catch (Exception e) - { - if (OnCommandLoaded != null) - OnCommandLoaded.Invoke(type.FullName!, false, null, e); - } - - } - - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - return null; - } - - return plugins; - - } - } -} diff --git a/PluginManager/Loaders/EventsLoader.cs b/PluginManager/Loaders/EventsLoader.cs deleted file mode 100644 index 28c1766..0000000 --- a/PluginManager/Loaders/EventsLoader.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; - -using PluginManager.Interfaces; - -namespace PluginManager.Loaders -{ - internal class EventsLoader - { - - private readonly string EVPath; - private readonly string EVExtension; - - internal delegate void onEventLoad(string name, bool success, DBEvent? ev = null, Exception? e = null); - internal delegate void onEventFileLoaded(string path); - - /// - /// An event that is fired whenever a event is loaded in memory - /// - internal onEventLoad? EventLoad; - - /// - /// An event that is fired whenever a event file is loaded - /// - internal onEventFileLoaded? EventFileLoaded; - - /// - /// The Event Loader constructor - /// - /// The path to all events - /// The extension for events - internal EventsLoader(string path, string ext) - { - EVPath = path; - EVExtension = ext; - } - - /// - /// The method that loads all events - /// - /// - internal List? LoadEvents() - { - - if (!Directory.Exists(EVPath)) - { - Directory.CreateDirectory(EVPath); - return null; - } - - string[] files = Directory.GetFiles(EVPath, $"*{EVExtension}", SearchOption.AllDirectories); - - foreach (var file in files) - { - Assembly.LoadFile(Path.GetFullPath(file)); - if (EventFileLoaded != null) - EventFileLoaded.Invoke(file); - } - - List events = new List(); - - try - { - Type interfaceType = typeof(DBEvent); - Type[] types = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(a => a.GetTypes()) - .Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass) - .ToArray(); - foreach (Type type in types) - { - try - { - DBEvent ev = (DBEvent)Activator.CreateInstance(type)!; - events.Add(ev); - - if (EventLoad != null) - EventLoad.Invoke(type.FullName!, true, ev, null); - } - catch (Exception e) - { - if (EventLoad != null) - EventLoad.Invoke(type.FullName!, false, null, e); - } - - } - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - return null; - } - - return events; - - } - } -} \ No newline at end of file diff --git a/PluginManager/Loaders/Loader.cs b/PluginManager/Loaders/Loader.cs new file mode 100644 index 0000000..955bc9f --- /dev/null +++ b/PluginManager/Loaders/Loader.cs @@ -0,0 +1,94 @@ +using System; +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 +{ + 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 + { + 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? Load() + { + List list = new List(); + 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; + } + } +} diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index 520112d..813ba1b 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -1,35 +1,32 @@ using Discord.WebSocket; - using PluginManager.Interfaces; using PluginManager.Others; - using System; using System.Collections.Generic; + namespace PluginManager.Loaders { public class PluginLoader { - private DiscordSocketClient client; + private readonly DiscordSocketClient _client; /// /// The Plugin Loader constructor /// /// The discord bot client where the plugins will pe attached to - public PluginLoader(DiscordSocketClient discordSocketClient) - { - this.client = discordSocketClient; - } + 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"; + private const string pluginCMDExtension = "dll"; + private const string pluginEVEExtension = "dll"; + /// /// A list of commands /// - public static List? Plugins { get; set; } + public static List? Commands { get; set; } /// /// A list of commands @@ -38,6 +35,7 @@ namespace PluginManager.Loaders 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); /// @@ -55,11 +53,10 @@ namespace PluginManager.Loaders /// public void LoadPlugins() { + Commands = new List(); + Events = new List(); - Plugins = new List(); - Events = new List(); - - Functions.WriteLogFile("Starting plugin loader ... Client: " + client.CurrentUser.Username); + Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); if (LanguageSystem.Language.ActiveLanguage != null) Console_Utilities.WriteColorText( LanguageSystem.Language.ActiveLanguage.FormatText( @@ -67,45 +64,40 @@ namespace PluginManager.Loaders ) ); - //Load commands - CommandsLoader CMDLoader = new CommandsLoader(pluginCMDFolder, pluginCMDExtension); - CMDLoader.OnCommandLoaded += OnCommandLoaded!; - CMDLoader.OnCommandFileLoaded += OnCommandFileLoaded; - Plugins = CMDLoader.LoadCommands(); + Loader commandsLoader = new Loader(pluginCMDFolder, pluginCMDExtension); + Loader eventsLoader = new Loader(pluginEVEFolder, pluginEVEExtension); - //Load Events - EventsLoader EVLoader = new EventsLoader(pluginEVEFolder, pluginEVEExtension); - EVLoader.EventLoad += OnEventLoaded!; - EVLoader.EventFileLoaded += EventFileLoaded; - Events = EVLoader.LoadEvents(); + commandsLoader.FileLoaded += OnCommandFileLoaded; + commandsLoader.PluginLoaded += OnCommandLoaded; + eventsLoader.FileLoaded += EventFileLoaded; + eventsLoader.PluginLoaded += OnEventLoaded; + + Commands = commandsLoader.Load(); + Events = eventsLoader.Load(); } - private void EventFileLoaded(string path) + private void EventFileLoaded(LoaderArgs e) { - if (path != null) - Functions.WriteLogFile($"[EVENT] Event from file [{path}] has been successfully created !"); + if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !"); } - private void OnCommandFileLoaded(string path) + private void OnCommandFileLoaded(LoaderArgs e) { - if (path != null) - Functions.WriteLogFile($"[CMD] Command from file [{path}] has been successfully loaded !"); + if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !"); } - private void OnEventLoaded(string typename, bool success, DBEvent eve, Exception exception) + private void OnEventLoaded(LoaderArgs e) { - if (eve != null && success) - eve.Start(client); - if (onEVELoad != null) - onEVELoad.Invoke(eve!.name, typename, success, exception); + 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(string name, bool success, DBCommand command, Exception exception) + private void OnCommandLoaded(LoaderArgs e) { - if (onCMDLoad != null) - onCMDLoad.Invoke(command.Command, name, success, exception); + if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); } } } diff --git a/PluginManager/Others/Console Utilities.cs b/PluginManager/Others/Console Utilities.cs index 1cdf29a..cf710d8 100644 --- a/PluginManager/Others/Console Utilities.cs +++ b/PluginManager/Others/Console Utilities.cs @@ -1,9 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace PluginManager.Others { @@ -14,17 +10,20 @@ namespace PluginManager.Others /// public class ProgressBar { - public int Progress { get; set; } - public int Max { get; set; } - public string Message { get; set; } + public int Max { get; set; } + public string Message { get; set; } + public ConsoleColor Color { get; init; } + public ProgressBar(int max, string message) { - Max = max; + 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 async void Update(int progress, double speed = -1, string? unit = null) + public void Update(int progress, double speed = -1, string? unit = null) { //progress bar @@ -39,8 +38,8 @@ namespace PluginManager.Others for (int i = 0; i < onechunk * progress; i++) { - Console.BackgroundColor = ConsoleColor.Green; - Console.CursorLeft = position++; + Console.BackgroundColor = this.Color; + Console.CursorLeft = position++; Console.Write(" "); } @@ -130,11 +129,12 @@ namespace PluginManager.Others ConsoleColor fg = Console.ForegroundColor; Dictionary colors = new Dictionary() { - {"&g", ConsoleColor.Green }, - {"&b", ConsoleColor.Blue }, - {"&r", ConsoleColor.Red }, - {"&m", ConsoleColor.Magenta }, - {"&c", fg } + { "&g", ConsoleColor.Green }, + { "&b", ConsoleColor.Blue }, + { "&r", ConsoleColor.Red }, + { "&m", ConsoleColor.Magenta }, + { "&y", ConsoleColor.Yellow }, + { "&c", fg } }; foreach (string word in words) { @@ -145,7 +145,9 @@ namespace PluginManager.Others Console.ForegroundColor = colors[prefix]; } - string m = word.Replace("&g", "").Replace("&b", "").Replace("&r", "").Replace("&c", "").Replace("&m", ""); + string m = word; + foreach (var key in colors.Keys) { m = m.Replace(key, ""); } + Console.Write(m + " "); } if (appendNewLine) diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 9e8091b..a87d603 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -259,16 +259,13 @@ namespace PluginManager.Others foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith("/")) - { - currentZIPFile++; Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); - } - else - { - entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); - currentZIPFile++; - } + else + try { entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); } + catch { } + + currentZIPFile++; await Task.Delay(10); progress.Report((float)currentZIPFile / totalZIPFiles * 100); } diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj index 7d2d32a..7eafd1b 100644 --- a/PluginManager/PluginManager.csproj +++ b/PluginManager/PluginManager.csproj @@ -19,10 +19,4 @@ - - - MSBuild:Compile - - -