diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index be17bb4..f0d3f6b 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -271,7 +271,7 @@ public class Program if (len > 0 && args[0] == "/remplug") { - var plugName = args.MergeStrings(1); + var plugName = string.Join(' ', args, 1, args.Length - 1); Console.WriteLine("Starting to remove " + plugName); await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName); loadPluginsOnStartup = true; diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index 80f7dd0..90cf1d1 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -4,6 +4,7 @@ using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; + using PluginManager.Loaders; using PluginManager.Others; @@ -11,10 +12,10 @@ namespace PluginManager; internal class AppConfig { - public string? UpdaterVersion { get; set; } + public string? UpdaterVersion { get; set; } public Dictionary? ApplicationVariables { get; init; } - public List? ProtectedKeyWords { get; init; } - public Dictionary? PluginVersions { get; init; } + public List? ProtectedKeyWords { get; init; } + public Dictionary? PluginVersions { get; init; } } public static class Config @@ -23,8 +24,8 @@ public static class Config public static string UpdaterVersion { - get => appConfig.UpdaterVersion; - set => appConfig.UpdaterVersion = value; + get => appConfig!.UpdaterVersion!; + set => appConfig!.UpdaterVersion = value; } public static string GetPluginVersion(string pluginName) @@ -133,6 +134,25 @@ public static class Config SaveConfig(SaveType.NORMAL); } + public static bool TrySetValue(string key, T value) + { + if (Config.ContainsKey(key)) + { + try + { + Config.SetValue(key, value); + return true; + } + catch + { + return false; + } + } + + Config.AddValueToVariables(key, value, false); + return true; + } + public static void RemoveKey(string key) { if (key == "Version" || key == "token" || key == "prefix") @@ -176,7 +196,7 @@ public static class Config { File.Delete(path); Console.WriteLine("An error occured while loading the settings. Importing from backup file..."); - path = Functions.dataFolder + "config.json.bak"; + path = Functions.dataFolder + "config.json.bak"; appConfig = await Functions.ConvertFromJson(path); Functions.WriteErrFile(ex.Message); } @@ -192,7 +212,7 @@ public static class Config try { Console.WriteLine("An error occured while loading the settings. Importing from backup file..."); - path = Functions.dataFolder + "config.json.bak"; + path = Functions.dataFolder + "config.json.bak"; appConfig = await Functions.ConvertFromJson(path); return; @@ -205,8 +225,10 @@ public static class Config appConfig = new AppConfig { - ApplicationVariables = new Dictionary(), ProtectedKeyWords = new List(), - PluginVersions = new Dictionary(), UpdaterVersion = "-1" + ApplicationVariables = new Dictionary(), + ProtectedKeyWords = new List(), + PluginVersions = new Dictionary(), + UpdaterVersion = "-1" }; } @@ -220,9 +242,9 @@ public static class Config return appConfig!.ApplicationVariables!.ContainsKey(key); } - public static IDictionary GetAllVariables() + public static IDictionary? GetAllVariables() { - return appConfig.ApplicationVariables; + return appConfig?.ApplicationVariables; } public static class PluginConfig diff --git a/PluginManager/Items/Command.cs b/PluginManager/Items/Command.cs index 822365b..de41b21 100644 --- a/PluginManager/Items/Command.cs +++ b/PluginManager/Items/Command.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; + using Discord.WebSocket; -using PluginManager.Others; namespace PluginManager.Items; @@ -20,9 +20,9 @@ public class Command { Author = message.Author; var data = message.Content.Split(' '); - Arguments = data.Length > 1 ? new List(data.MergeStrings(1).Split(' ')) : new List(); + Arguments = data.Length > 1 ? new List(string.Join(' ', data, 1, data.Length - 1).Split(' ')) : new List(); CommandName = data[0].Substring(1); - PrefixUsed = data[0][0]; + PrefixUsed = data[0][0]; } /// @@ -43,8 +43,8 @@ public class Command public class ConsoleCommand { - public string CommandName { get; init; } - public string Description { get; init; } - public string Usage { get; init; } - public Action Action { get; init; } + public string CommandName { get; init; } + public string Description { get; init; } + public string Usage { get; init; } + public Action Action { get; init; } } \ No newline at end of file diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 21aacb3..f10ebec 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -1,11 +1,4 @@ -using Discord.WebSocket; - -using PluginManager.Interfaces; -using PluginManager.Loaders; -using PluginManager.Online; -using PluginManager.Others; - -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -14,6 +7,13 @@ using System.Net.Http; using System.Reflection; using System.Threading.Tasks; +using Discord.WebSocket; + +using PluginManager.Interfaces; +using PluginManager.Loaders; +using PluginManager.Online; +using PluginManager.Others; + using OperatingSystem = PluginManager.Others.OperatingSystem; namespace PluginManager.Items; @@ -101,7 +101,7 @@ public class ConsoleCommandsHandler if (exception is null) Console.WriteLine("An error occured while loading: " + 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 = cc; @@ -143,7 +143,7 @@ public class ConsoleCommandsHandler return; } - var name = args.MergeStrings(1); + var name = string.Join(' ', args, 1, args.Length - 1); // info[0] = plugin type // info[1] = plugin link // info[2] = if others are required, or string.Empty if none @@ -313,7 +313,7 @@ public class ConsoleCommandsHandler if (args.Length <= 1) return; try { - var pName = args.MergeStrings(1); + var pName = string.Join(' ', args, 1, args.Length - 1); var client = new HttpClient(); var url = (await manager.GetPluginLinkByName(pName))[1]; if (url is null) throw new Exception($"Invalid plugin name {pName}."); @@ -347,7 +347,7 @@ public class ConsoleCommandsHandler if (args.Length <= 1) return; isDownloading = true; - var plugName = args.MergeStrings(1); + var plugName = string.Join(' ', args, 1, args.Length - 1); if (pluginsLoaded) { if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS) diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index d12c632..6958e4f 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -2,7 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; + using Discord.WebSocket; + using PluginManager.Interfaces; using PluginManager.Online; using PluginManager.Online.Updates; @@ -19,8 +21,8 @@ public class PluginLoader private const string pluginCMDFolder = @"./Data/Plugins/Commands/"; private const string pluginEVEFolder = @"./Data/Plugins/Events/"; - internal const string pluginCMDExtension = "dll"; - internal const string pluginEVEExtension = "dll"; + internal const string pluginCMDExtension = "dll"; + internal const string pluginEVEExtension = "dll"; private readonly DiscordSocketClient _client; /// @@ -64,9 +66,12 @@ public class PluginLoader await Task.Run(async () => { var name = new FileInfo(file).Name.Split('.')[0]; + var version = await ServerCom.GetVersionOfPackageFromWeb(name); + if (version is null) + return; if (!Config.PluginVersionsContainsKey(name)) Config.SetPluginVersion( - name, (await ServerCom.GetVersionOfPackageFromWeb(name))?.PackageVersionID + ".0.0"); + name, (version.PackageVersionID + ".0.0")); if (await PluginUpdater.CheckForUpdates(name)) await PluginUpdater.Download(name); @@ -78,9 +83,12 @@ public class PluginLoader await Task.Run(async () => { var name = new FileInfo(file).Name.Split('.')[0]; + var version = await ServerCom.GetVersionOfPackageFromWeb(name); + if (version is null) + return; if (!Config.PluginVersionsContainsKey(name)) Config.SetPluginVersion( - name, (await ServerCom.GetVersionOfPackageFromWeb(name))?.PackageVersionID + ".0.0"); + name, (version.PackageVersionID + ".0.0")); if (await PluginUpdater.CheckForUpdates(name)) await PluginUpdater.Download(name); @@ -94,22 +102,24 @@ public class PluginLoader //Load all plugins Commands = new List(); - Events = new List(); + Events = new List(); Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Console.WriteLine("Loading plugins"); var commandsLoader = new Loader(pluginCMDFolder, pluginCMDExtension); - var eventsLoader = new Loader(pluginEVEFolder, pluginEVEExtension); + var eventsLoader = new Loader(pluginEVEFolder, pluginEVEExtension); - commandsLoader.FileLoaded += OnCommandFileLoaded; + + commandsLoader.FileLoaded += OnCommandFileLoaded; commandsLoader.PluginLoaded += OnCommandLoaded; - eventsLoader.FileLoaded += EventFileLoaded; + eventsLoader.FileLoaded += EventFileLoaded; eventsLoader.PluginLoaded += OnEventLoaded; Commands = commandsLoader.Load(); - Events = eventsLoader.Load(); + Events = eventsLoader.Load(); + } private void EventFileLoaded(LoaderArgs e) @@ -136,8 +146,8 @@ public class PluginLoader catch (Exception ex) { Console.WriteLine(ex.ToString()); - Console.WriteLine("Plugin: " + e.PluginName); - Console.WriteLine("Type: " + e.TypeName); + Console.WriteLine("Plugin: " + e.PluginName); + Console.WriteLine("Type: " + e.TypeName); Console.WriteLine("IsLoaded: " + e.IsLoaded); } } diff --git a/PluginManager/Online/Helpers/VersionString.cs b/PluginManager/Online/Helpers/VersionString.cs index 9437630..e06bc87 100644 --- a/PluginManager/Online/Helpers/VersionString.cs +++ b/PluginManager/Online/Helpers/VersionString.cs @@ -13,19 +13,20 @@ public class VersionString var data = version.Split('.'); try { - PackageVersionID = int.Parse(data[0]); - PackageMainVersion = int.Parse(data[1]); + PackageVersionID = int.Parse(data[0]); + PackageMainVersion = int.Parse(data[1]); PackageCheckVersion = int.Parse(data[2]); } catch (Exception ex) { + Console.WriteLine(version); throw new Exception("Failed to write Version", ex); } } public override string ToString() { - return "{PackageID: " + PackageVersionID + ", PackageVersion: " + PackageMainVersion + + return "{PackageID: " + PackageVersionID + ", PackageVersion: " + PackageMainVersion + ", PackageCheckVersion: " + PackageCheckVersion + "}"; } @@ -45,7 +46,7 @@ public class VersionString if (s1.PackageVersionID == s2.PackageVersionID) { if (s1.PackageMainVersion > s2.PackageMainVersion) return true; - if (s1.PackageMainVersion == s2.PackageMainVersion && + if (s1.PackageMainVersion == s2.PackageMainVersion && s1.PackageCheckVersion > s2.PackageCheckVersion) return true; } @@ -59,7 +60,7 @@ public class VersionString public static bool operator ==(VersionString s1, VersionString s2) { - if (s1.PackageVersionID == s2.PackageVersionID && s1.PackageMainVersion == s2.PackageMainVersion && + if (s1.PackageVersionID == s2.PackageVersionID && s1.PackageMainVersion == s2.PackageMainVersion && s1.PackageCheckVersion == s2.PackageCheckVersion) return true; return false; } diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs index 6dd2bf9..3fbdcfb 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/PluginManager/Online/ServerCom.cs @@ -1,7 +1,4 @@ -using PluginManager.Online.Helpers; -using PluginManager.Others; - -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -9,6 +6,9 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using PluginManager.Online.Helpers; +using PluginManager.Others; + namespace PluginManager.Online; public static class ServerCom @@ -100,10 +100,15 @@ public static class ServerCom { var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions"; var data = await ReadTextFromURL(url); - var version = (from item in data - where !item.StartsWith("#") && item.StartsWith(pakName) - select item.Split(',')[1]).FirstOrDefault(); - if (version == default || version == null) return null; - return new VersionString(version); + foreach (var item in data) + { + if (item.StartsWith("#")) + continue; + + string[] split = item.Split(','); + if (split[0] == pakName) + return new VersionString(split[1]); + } + return null; } } \ No newline at end of file diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 1784acd..7be6825 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -9,7 +9,9 @@ using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; + using Discord.WebSocket; + using PluginManager.Items; namespace PluginManager.Others; @@ -113,31 +115,6 @@ public static class Functions WriteErrFile(ex.ToString()); } - /// - /// Merge one array of strings into one string - /// - /// The array of strings - /// The index from where the merge should start (included) - /// A string built based on the array - public static string MergeStrings(this string[] s, int indexToStart) - { - return string.Join(' ', s, indexToStart, s.Length - 1); - - /* string r = ""; - - int len = s.Length; - if (len <= indexToStart) return ""; - for (int i = indexToStart; i < len - 1; ++i) - { - r += s[i] + " "; - } - - r += s[len - 1]; - - return r; - */ - } - /// /// Get the Operating system you are runnin on /// @@ -168,22 +145,21 @@ public static class Functions /// Triggered if is less then or equal to 0 /// Triggered if is not readable /// Triggered in is not writable - public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize, - IProgress? progress = null, + public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize, + IProgress? progress = null, CancellationToken cancellationToken = default) { - if (stream == null) throw new ArgumentNullException(nameof(stream)); + if (stream == null) throw new ArgumentNullException(nameof(stream)); if (destination == null) throw new ArgumentNullException(nameof(destination)); - if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize)); + if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize)); if (!stream.CanRead) throw new InvalidOperationException("The stream is not readable."); if (!destination.CanWrite) throw new ArgumentException("Destination stream is not writable", nameof(destination)); - var buffer = new byte[bufferSize]; + var buffer = new byte[bufferSize]; long totalBytesRead = 0; - int bytesRead; - while ((bytesRead = - await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) + int bytesRead; + while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); totalBytesRead += bytesRead; @@ -199,7 +175,7 @@ public static class Functions /// The progress that is updated as a file is processed /// The type of progress /// - public static async Task ExtractArchive(string zip, string folder, IProgress progress, + public static async Task ExtractArchive(string zip, string folder, IProgress progress, UnzipProgressType type) { Directory.CreateDirectory(folder); @@ -207,7 +183,7 @@ public static class Functions { if (type == UnzipProgressType.PercentageFromNumberOfFiles) { - var totalZIPFiles = archive.Entries.Count(); + var totalZIPFiles = archive.Entries.Count(); var currentZIPFile = 0; foreach (var entry in archive.Entries) { @@ -264,32 +240,6 @@ public static class Functions } } - - /// - /// Convert Bytes to highest measurement unit possible - /// - /// The amount of bytes - /// - public static (double, string) ConvertBytes(long bytes) - { - var units = new List - { - "B", - "KB", - "MB", - "GB", - "TB" - }; - var i = 0; - while (bytes >= 1024) - { - i++; - bytes /= 1024; - } - - return (bytes, units[i]); - } - /// /// Save to JSON file /// @@ -323,36 +273,6 @@ public static class Functions return (obj ?? default)!; } - /// - /// Check if all words from are in
- /// This function returns true if
- /// 1. The is part of
- /// 2. The words (split by a space) of are located (separately) in - ///
- /// - /// The following example will return
- /// STRContains("Hello World !", "I type word Hello and then i typed word World !")
- /// The following example will return
- /// STRContains("Hello World !", "I typed Hello World !"
- /// The following example will return
- /// STRContains("Hello World", "I type World then Hello")
- /// The following example will return
- /// STRContains("Hello World !", "I typed Hello World")
- ///
- ///
- /// The string you are checking - /// The main string that should contain - /// - public static bool STRContains(this string str, string baseString) - { - if (baseString.Contains(str)) return true; - var array = str.Split(' '); - foreach (var s in array) - if (!baseString.Contains(s)) - return false; - return true; - } - public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element) { Stream text; @@ -373,7 +293,7 @@ public static class Functions using (var md5 = MD5.Create()) { var inputBytes = Encoding.ASCII.GetBytes(input); - var hashBytes = md5.ComputeHash(inputBytes); + var hashBytes = md5.ComputeHash(inputBytes); return Convert.ToHexString(hashBytes); } } diff --git a/SethDiscordBot.sln b/SethDiscordBot.sln index 5a6a5b4..93c8ecc 100644 --- a/SethDiscordBot.sln +++ b/SethDiscordBot.sln @@ -7,6 +7,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\Di EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MusicLibrary", "..\DiscordBotItems\Plugins\MusicLibrary\MusicLibrary.csproj", "{878DFE01-4596-4EBC-9651-0679598CE794}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MusicLibraryEvent", "..\DiscordBotItems\Plugins\MusicLibraryEvent\MusicLibraryEvent.csproj", "{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +25,14 @@ Global {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = Release|Any CPU + {878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.Build.0 = Debug|Any CPU + {878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.ActiveCfg = Release|Any CPU + {878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.Build.0 = Release|Any CPU + {3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE