diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/.gitignore b/.idea/.idea.DiscordBotWithAPI/.idea/.gitignore deleted file mode 100644 index 1e2399a..0000000 --- a/.idea/.idea.DiscordBotWithAPI/.idea/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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 deleted file mode 100644 index c0fdb9d..0000000 --- a/.idea/.idea.DiscordBotWithAPI/.idea/avalonia.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/encodings.xml b/.idea/.idea.DiscordBotWithAPI/.idea/encodings.xml deleted file mode 100644 index df87cf9..0000000 --- a/.idea/.idea.DiscordBotWithAPI/.idea/encodings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/indexLayout.xml b/.idea/.idea.DiscordBotWithAPI/.idea/indexLayout.xml deleted file mode 100644 index 7b08163..0000000 --- a/.idea/.idea.DiscordBotWithAPI/.idea/indexLayout.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/.idea.DiscordBotWithAPI/.idea/vcs.xml b/.idea/.idea.DiscordBotWithAPI/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/.idea.DiscordBotWithAPI/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/BUILDS/net6.0/EVE_LevelingSystem.dll b/BUILDS/net6.0/EVE_LevelingSystem.dll index 58c77e5..e443461 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 484c585..856115d 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 828bd34..2a5ff10 100644 --- a/DiscordBot/App.config +++ b/DiscordBot/App.config @@ -1,7 +1,4 @@ - - - - - - - + + + + \ No newline at end of file diff --git a/DiscordBot/Discord/Commands/Help.cs b/DiscordBot/Discord/Commands/Help.cs index 26a1c51..67840a5 100644 --- a/DiscordBot/Discord/Commands/Help.cs +++ b/DiscordBot/Discord/Commands/Help.cs @@ -75,11 +75,12 @@ namespace DiscordBot.Discord.Commands string normalCommands = ""; string DMCommands = ""; - foreach (var cmd in PluginLoader.Commands!) + foreach (var cmd in PluginLoader.Plugins!) { - 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 + " "; } @@ -93,7 +94,7 @@ namespace DiscordBot.Discord.Commands private EmbedBuilder GenerateHelpCommand(string command) { EmbedBuilder embedBuilder = new EmbedBuilder(); - DBCommand cmd = PluginLoader.Commands.Find(p => p.Command == command); + DBCommand cmd = PluginLoader.Plugins.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 b877f79..5ed266b 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.Commands!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); + DBCommand plugin = PluginLoader.Plugins!.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 903d078..9c1a719 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -1,14 +1,16 @@ 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 @@ -18,23 +20,21 @@ 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,14 +72,17 @@ namespace DiscordBot /// The main loop for the discord bot /// /// The discord booter used to start the application - private static Task NoGUI(Boot discordbooter) + private static async 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) { @@ -95,14 +98,23 @@ 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); @@ -116,8 +128,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]); @@ -133,6 +145,7 @@ namespace DiscordBot /// The arguments private static async Task HandleInput(string[] args) { + if (args.Length == 0) { if (File.Exists("./ref/startupArguments.txt")) @@ -151,12 +164,8 @@ namespace DiscordBot if (len == 1 && args[0] == "--logout") { - File.Delete(Functions.dataFolder + "DiscordBotCore.dat"); - await Task.Run(async () => - { - await Task.Delay(1000); - Environment.Exit(0x08); - }); + File.Delete(Functions.dataFolder + "Login.dat"); + Console.WriteLine("Logged out. Please restart the application !"); return; } @@ -170,14 +179,20 @@ 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 456aca5..a3b2c89 100644 --- a/DiscordBotGUI/App.axaml.cs +++ b/DiscordBotGUI/App.axaml.cs @@ -1,8 +1,6 @@ -using System.IO; using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; -using PluginManager.Others; namespace DiscordBotGUI { @@ -15,7 +13,13 @@ 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 8c4dccc..ecc5405 100644 --- a/DiscordBotGUI/AppUpdater.axaml.cs +++ b/DiscordBotGUI/AppUpdater.axaml.cs @@ -21,48 +21,42 @@ 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() - { - //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; - }); + /* private async void DownloadDiscordBotClientNoGUIAsDLL() + { - this.progressBar1.IsIndeterminate = false; - try - { - await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.zip", progress); + //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; + }); - actiontype++; + 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."; - await Functions.ExtractArchive("./DiscordBot.zip", "./", progress); - } - catch - { - textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding."; + await Task.Delay(1000); + return; + } - await Task.Delay(1000); - - new MainWindow() { Height = 425, Width = 500 }.Show(); - Close(); - } - } + //new MainWindow() { Height = 425, Width = 500 }.Show(); + //Close(); + }*/ private async void Updates() { diff --git a/DiscordBotWithAPI.sln b/DiscordBotWithAPI.sln index 7bf0ffe..3f9ab41 100644 --- a/DiscordBotWithAPI.sln +++ b/DiscordBotWithAPI.sln @@ -23,6 +23,8 @@ 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 @@ -59,6 +61,10 @@ 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 @@ -75,6 +81,7 @@ 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 new file mode 100644 index 0000000..919fa6b --- /dev/null +++ b/PluginManager/Loaders/CommandsLoader.cs @@ -0,0 +1,99 @@ +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 new file mode 100644 index 0000000..28c1766 --- /dev/null +++ b/PluginManager/Loaders/EventsLoader.cs @@ -0,0 +1,100 @@ +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 deleted file mode 100644 index 955bc9f..0000000 --- a/PluginManager/Loaders/Loader.cs +++ /dev/null @@ -1,94 +0,0 @@ -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 813ba1b..520112d 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -1,32 +1,35 @@ using Discord.WebSocket; + using PluginManager.Interfaces; using PluginManager.Others; + using System; using System.Collections.Generic; - namespace PluginManager.Loaders { public class PluginLoader { - private readonly DiscordSocketClient _client; + private 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? Commands { get; set; } + public static List? Plugins { get; set; } /// /// A list of commands @@ -35,7 +38,6 @@ 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); /// @@ -53,10 +55,11 @@ namespace PluginManager.Loaders /// public void LoadPlugins() { - Commands = new List(); - Events = new List(); - Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); + Plugins = new List(); + Events = new List(); + + Functions.WriteLogFile("Starting plugin loader ... Client: " + client.CurrentUser.Username); if (LanguageSystem.Language.ActiveLanguage != null) Console_Utilities.WriteColorText( LanguageSystem.Language.ActiveLanguage.FormatText( @@ -64,40 +67,45 @@ 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); - commandsLoader.FileLoaded += OnCommandFileLoaded; - commandsLoader.PluginLoaded += OnCommandLoaded; + //Load Events + EventsLoader EVLoader = new EventsLoader(pluginEVEFolder, pluginEVEExtension); + EVLoader.EventLoad += OnEventLoaded!; + EVLoader.EventFileLoaded += EventFileLoaded; + Events = EVLoader.LoadEvents(); - eventsLoader.FileLoaded += EventFileLoaded; - eventsLoader.PluginLoaded += OnEventLoaded; - - Commands = commandsLoader.Load(); - Events = eventsLoader.Load(); } - private void EventFileLoaded(LoaderArgs e) + private void EventFileLoaded(string path) { - if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !"); + if (path != null) + Functions.WriteLogFile($"[EVENT] Event from file [{path}] has been successfully created !"); } - private void OnCommandFileLoaded(LoaderArgs e) + private void OnCommandFileLoaded(string path) { - if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !"); + if (path != null) + Functions.WriteLogFile($"[CMD] Command from file [{path}] has been successfully loaded !"); } - private void OnEventLoaded(LoaderArgs e) + private void OnEventLoaded(string typename, bool success, DBEvent eve, Exception exception) { - if (e.IsLoaded) { ((DBEvent)e.Plugin!).Start(_client); } - - if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); + if (eve != null && success) + eve.Start(client); + if (onEVELoad != null) + onEVELoad.Invoke(eve!.name, typename, success, exception); } - private void OnCommandLoaded(LoaderArgs e) + private void OnCommandLoaded(string name, bool success, DBCommand command, Exception exception) { - if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); + if (onCMDLoad != null) + onCMDLoad.Invoke(command.Command, name, success, exception); } } } diff --git a/PluginManager/Others/Console Utilities.cs b/PluginManager/Others/Console Utilities.cs index cf710d8..1cdf29a 100644 --- a/PluginManager/Others/Console Utilities.cs +++ b/PluginManager/Others/Console Utilities.cs @@ -1,5 +1,9 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; namespace PluginManager.Others { @@ -10,20 +14,17 @@ namespace PluginManager.Others /// public class ProgressBar { - public int Max { get; set; } - public string Message { get; set; } - public ConsoleColor Color { get; init; } - + public int Progress { get; set; } + public int Max { get; set; } + public string Message { get; set; } 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 void Update(int progress, double speed = -1, string? unit = null) + public async void Update(int progress, double speed = -1, string? unit = null) { //progress bar @@ -38,8 +39,8 @@ namespace PluginManager.Others for (int i = 0; i < onechunk * progress; i++) { - Console.BackgroundColor = this.Color; - Console.CursorLeft = position++; + Console.BackgroundColor = ConsoleColor.Green; + Console.CursorLeft = position++; Console.Write(" "); } @@ -129,12 +130,11 @@ namespace PluginManager.Others ConsoleColor fg = Console.ForegroundColor; Dictionary colors = new Dictionary() { - { "&g", ConsoleColor.Green }, - { "&b", ConsoleColor.Blue }, - { "&r", ConsoleColor.Red }, - { "&m", ConsoleColor.Magenta }, - { "&y", ConsoleColor.Yellow }, - { "&c", fg } + {"&g", ConsoleColor.Green }, + {"&b", ConsoleColor.Blue }, + {"&r", ConsoleColor.Red }, + {"&m", ConsoleColor.Magenta }, + {"&c", fg } }; foreach (string word in words) { @@ -145,9 +145,7 @@ namespace PluginManager.Others Console.ForegroundColor = colors[prefix]; } - string m = word; - foreach (var key in colors.Keys) { m = m.Replace(key, ""); } - + string m = word.Replace("&g", "").Replace("&b", "").Replace("&r", "").Replace("&c", "").Replace("&m", ""); Console.Write(m + " "); } if (appendNewLine) diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index a87d603..9e8091b 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -259,13 +259,16 @@ namespace PluginManager.Others foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith("/")) + { + currentZIPFile++; Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); - + } else - try { entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); } - catch { } + { + entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); + currentZIPFile++; + } - currentZIPFile++; await Task.Delay(10); progress.Report((float)currentZIPFile / totalZIPFiles * 100); } diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj index 7eafd1b..7d2d32a 100644 --- a/PluginManager/PluginManager.csproj +++ b/PluginManager/PluginManager.csproj @@ -19,4 +19,10 @@ + + + MSBuild:Compile + + +