From 0527d43dd2e3955eb4d15034f92ffeaa45c3f258 Mon Sep 17 00:00:00 2001 From: Wizzy69 Date: Fri, 9 Dec 2022 14:46:10 +0200 Subject: [PATCH] patch --- DiscordBot/Discord/Commands/Restart.cs | 8 +- DiscordBot/Discord/Core/Boot.cs | 10 +- DiscordBot/Discord/Core/CommandHandler.cs | 3 +- DiscordBot/Program.cs | 21 +- PluginManager/Items/ConsoleCommandsHandler.cs | 23 ++- PluginManager/Loaders/Loader.cs | 4 +- PluginManager/Loaders/LoaderV2.cs | 15 +- PluginManager/Loaders/PluginLoader.cs | 5 +- PluginManager/Logger.cs | 67 ++++++- PluginManager/Online/PluginsManager.cs | 4 +- PluginManager/Others/ArchiveManager.cs | 139 +++++++++++++ PluginManager/Others/Functions.cs | 185 ------------------ 12 files changed, 258 insertions(+), 226 deletions(-) create mode 100644 PluginManager/Others/ArchiveManager.cs diff --git a/DiscordBot/Discord/Commands/Restart.cs b/DiscordBot/Discord/Commands/Restart.cs index 939346d..1d1e8cd 100644 --- a/DiscordBot/Discord/Commands/Restart.cs +++ b/DiscordBot/Discord/Commands/Restart.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.Diagnostics; + +using PluginManager; using PluginManager.Interfaces; using PluginManager.Others; + using DiscordLibCommands = Discord.Commands; -using DiscordLib = Discord; using OperatingSystem = PluginManager.Others.OperatingSystem; namespace DiscordBot.Discord.Commands; @@ -40,7 +42,7 @@ internal class Restart : DBCommand public async void ExecuteServer(DiscordLibCommands.SocketCommandContext context) { var args = Functions.GetArguments(context.Message); - var OS = Functions.GetOperatingSystem(); + var OS = Functions.GetOperatingSystem(); if (args.Count == 0) { switch (OS) @@ -79,7 +81,7 @@ internal class Restart : DBCommand switch (OS) { case OperatingSystem.WINDOWS: - Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\""); + Logger.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\""); Process.Start("./DiscordBot.exe", cmd); break; case OperatingSystem.LINUX: diff --git a/DiscordBot/Discord/Core/Boot.cs b/DiscordBot/Discord/Core/Boot.cs index aefffab..47412d0 100644 --- a/DiscordBot/Discord/Core/Boot.cs +++ b/DiscordBot/Discord/Core/Boot.cs @@ -5,7 +5,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; -using static PluginManager.Others.Functions; +using PluginManager; namespace DiscordBot.Discord.Core; @@ -98,7 +98,7 @@ internal class Boot private async Task Client_LoggedOut() { - WriteLogFile("Successfully Logged Out"); + Logger.WriteLine("Successfully Logged Out"); await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); /* var cmds = await client.GetGlobalApplicationCommandsAsync(); @@ -117,7 +117,7 @@ internal class Boot private Task LoggedIn() { Console.Title = "CONNECTED"; - WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" + + Logger.WriteLine("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" + DateTime.Now.ToShortTimeString() + ")" ); return Task.CompletedTask; @@ -129,7 +129,7 @@ internal class Boot { case LogSeverity.Error: case LogSeverity.Critical: - WriteErrFile(message.Message); + Logger.WriteErrFile(message.Message); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[ERROR] " + message.Message); @@ -139,7 +139,7 @@ internal class Boot case LogSeverity.Info: case LogSeverity.Debug: - WriteLogFile(message.Message); + Logger.WriteLogFile(message.Message); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[INFO] " + message.Message); diff --git a/DiscordBot/Discord/Core/CommandHandler.cs b/DiscordBot/Discord/Core/CommandHandler.cs index 100dfe4..87eaf22 100644 --- a/DiscordBot/Discord/Core/CommandHandler.cs +++ b/DiscordBot/Discord/Core/CommandHandler.cs @@ -7,9 +7,10 @@ using Discord.Commands; using Discord.WebSocket; using PluginManager.Loaders; -using PluginManager.Others; using PluginManager.Others.Permissions; +using static PluginManager.Logger; + namespace DiscordBot.Discord.Core; internal class CommandHandler diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index adcfcea..70c10c0 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -309,7 +309,7 @@ public class Program Config.Variables.Add("LaunchMessage", "An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", false); - Functions.WriteErrFile(ex.ToString()); + Logger.WriteErrFile(ex.ToString()); } } }); @@ -318,6 +318,14 @@ public class Program private static async Task PreLoadComponents() { + Settings.sqlDatabase = new SqlDatabase(Functions.dataFolder + "SetDB.dat"); + + await Settings.sqlDatabase.Open(); + await Config.Initialize(); + Logger.Initialize(true); + ArchiveManager.Initialize(); + + Logger.LogEvent += (message) => { Console.Write(message); @@ -330,13 +338,6 @@ public class Program Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/PAKS"); - Settings.sqlDatabase = new SqlDatabase(Functions.dataFolder + "SetDB.dat"); - - await Settings.sqlDatabase.Open(); - await Config.Initialize(); - - - if (await Config.Variables.ExistsAsync("DeleteLogsAtStartup")) if (await Config.Variables.GetValueAsync("DeleteLogsAtStartup") == "true") foreach (var file in Directory.GetFiles("./Output/Logs/")) @@ -364,7 +365,7 @@ public class Program } catch (Exception ex) { - Functions.WriteErrFile(ex.Message); + Logger.WriteErrFile(ex.Message); } } @@ -451,7 +452,7 @@ public class Program await ServerCom.DownloadFileNoProgressAsync( "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip", "./Updater.zip"); - await Functions.ExtractArchive("./Updater.zip", "./", null, + await ArchiveManager.ExtractArchive("./Updater.zip", "./", null, UnzipProgressType.PercentageFromTotalSize); await Config.Variables.SetValueAsync("UpdaterVersion", updaternewversion); File.Delete("Updater.zip"); diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index 475ea69..a68c60c 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -31,6 +31,7 @@ public class ConsoleCommandsHandler public ConsoleCommandsHandler(DiscordSocketClient client) { + if (!Logger.isConsole) throw new Exception("Can not use ConsoleCommandsHandler for Non console apps"); this.client = client; InitializeBasicCommands(); @@ -242,7 +243,7 @@ public class ConsoleCommandsHandler var bar = new Utilities.ProgressBar( ProgressBarType.NO_END); bar.Start(); - await Functions.ExtractArchive("./" + split[1], "./", null, + await ArchiveManager.ExtractArchive("./" + split[1], "./", null, UnzipProgressType.PercentageFromTotalSize); bar.Stop("Extracted"); Logger.WriteLine("\n"); @@ -471,6 +472,8 @@ public class ConsoleCommandsHandler public static async Task ExecuteCommad(string command) { + if (!Logger.isConsole) + throw new Exception("Can not use console based commands on non console based application !"); var args = command.Split(' '); foreach (var item in commandList.ToList()) if (item.CommandName == args[0]) @@ -482,18 +485,20 @@ public class ConsoleCommandsHandler public bool HandleCommand(string command, bool removeCommandExecution = true) { - Console.ForegroundColor = ConsoleColor.White; + if (Logger.isConsole) + Console.ForegroundColor = ConsoleColor.White; var args = command.Split(' '); foreach (var item in commandList.ToList()) if (item.CommandName == args[0]) { - if (removeCommandExecution) - { - Console.SetCursorPosition(0, Console.CursorTop - 1); - for (var i = 0; i < command.Length + 30; i++) - Logger.Write(" "); - Console.SetCursorPosition(0, Console.CursorTop); - } + if (Logger.isConsole) + if (removeCommandExecution) + { + Console.SetCursorPosition(0, Console.CursorTop - 1); + for (var i = 0; i < command.Length + 30; i++) + Logger.Write(" "); + Console.SetCursorPosition(0, Console.CursorTop); + } Logger.WriteLine(); item.Action(args); diff --git a/PluginManager/Loaders/Loader.cs b/PluginManager/Loaders/Loader.cs index 52cc988..2c61f8d 100644 --- a/PluginManager/Loaders/Loader.cs +++ b/PluginManager/Loaders/Loader.cs @@ -4,8 +4,6 @@ using System.IO; using System.Linq; using System.Reflection; -using PluginManager.Others; - namespace PluginManager.Loaders; internal class LoaderArgs : EventArgs @@ -102,7 +100,7 @@ internal class Loader } catch (Exception ex) { - Functions.WriteErrFile(ex.ToString()); + Logger.WriteErrFile(ex.ToString()); } diff --git a/PluginManager/Loaders/LoaderV2.cs b/PluginManager/Loaders/LoaderV2.cs index ed1d2c2..9cbfd84 100644 --- a/PluginManager/Loaders/LoaderV2.cs +++ b/PluginManager/Loaders/LoaderV2.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Reflection; using PluginManager.Interfaces; -using PluginManager.Others; namespace PluginManager.Loaders { @@ -47,7 +46,17 @@ namespace PluginManager.Loaders var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories); foreach (var file in files) { - Assembly.LoadFrom(file); + try + { + Assembly.LoadFrom(file); + } + catch (Exception ex) + { + Logger.WriteLine(ex.Message); + Logger.WriteLine("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded"); + + continue; + } if (FileLoaded != null) { var args = new LoaderArgs @@ -116,7 +125,7 @@ namespace PluginManager.Loaders } catch (Exception ex) { - Functions.WriteErrFile(ex.ToString()); + Logger.WriteErrFile(ex.ToString()); return null; } diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index da303e1..2b9beba 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -10,7 +10,6 @@ using Discord.WebSocket; using PluginManager.Interfaces; using PluginManager.Online; using PluginManager.Online.Updates; -using PluginManager.Others; namespace PluginManager.Loaders; @@ -95,11 +94,11 @@ public class PluginLoader Events = new List(); SlashCommands = new List(); - Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); + Logger.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Logger.WriteLine("Loading plugins"); var loader = new LoaderV2("./Data/Plugins", "dll"); - loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded"); + loader.FileLoaded += (args) => Logger.WriteLogFile($"{args.PluginName} file Loaded"); loader.PluginLoaded += Loader_PluginLoaded; var res = loader.Load(); Events = res.Item1; diff --git a/PluginManager/Logger.cs b/PluginManager/Logger.cs index c643aa8..284b2fd 100644 --- a/PluginManager/Logger.cs +++ b/PluginManager/Logger.cs @@ -1,11 +1,34 @@ -using Discord; +using System; +using System.IO; + +using Discord; namespace PluginManager { public static class Logger { - public static bool isConsole = true; + public static bool isConsole { get; private set; } + private static bool isInitialized; + + private static string? logFolder; + private static string? errFolder; + + public static void Initialize(bool console) + { + if (isInitialized) throw new Exception("Logger is already initialized"); + + if (!Config.Variables.Exists("LogFolder")) + Config.Variables.Add("LogFolder", "./Data/Output/Logs/"); + + if (!Config.Variables.Exists("ErrorFolder")) + Config.Variables.Add("ErrorFolder", "./Data/Output/Errors/"); + + isInitialized = true; + logFolder = Config.Variables.GetValue("LogFolder"); + errFolder = Config.Variables.GetValue("ErrorFolder"); + isConsole = console; + } public delegate void LogEventHandler(string Message); @@ -13,16 +36,19 @@ namespace PluginManager public static void Log(string Message) { + if (!isInitialized) throw new Exception("Logger is not initialized"); LogEvent?.Invoke(Message); } public static void Log(string Message, params object[] Args) { + if (!isInitialized) throw new Exception("Logger is not initialized"); LogEvent?.Invoke(string.Format(Message, Args)); } public static void Log(IMessage message, bool newLine) { + if (!isInitialized) throw new Exception("Logger is not initialized"); LogEvent?.Invoke(message.Content); if (newLine) LogEvent?.Invoke("\n"); @@ -30,18 +56,21 @@ namespace PluginManager public static void WriteLine(string? message) { + if (!isInitialized) throw new Exception("Logger is not initialized"); if (message is not null) LogEvent?.Invoke(message + '\n'); } public static void LogError(System.Exception ex) { + if (!isInitialized) throw new Exception("Logger is not initialized"); string message = "[ERROR]" + ex.Message; LogEvent?.Invoke(message + '\n'); } public static void LogError(string? message) { + if (!isInitialized) throw new Exception("Logger is not initialized"); if (message is not null) LogEvent?.Invoke("[ERROR]" + message + '\n'); } @@ -49,17 +78,51 @@ namespace PluginManager public static void WriteLine() { + if (!isInitialized) throw new Exception("Logger is not initialized"); LogEvent?.Invoke("\n"); } public static void Write(string message) { + if (!isInitialized) throw new Exception("Logger is not initialized"); LogEvent?.Invoke(message); } public static void Write(char c) { + if (!isInitialized) throw new Exception("Logger is not initialized"); LogEvent?.Invoke($"{c}"); } + + /// + /// Write logs to file + /// + /// The message to be wrote + public static void WriteLogFile(string LogMessage) + { + if (!isInitialized) throw new Exception("Logger is not initialized"); + var logsPath = logFolder + $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Log.txt"; + Directory.CreateDirectory(logFolder); + File.AppendAllTextAsync(logsPath, LogMessage + " \n").Wait(); + } + + /// + /// Write error to file + /// + /// The message to be wrote + public static void WriteErrFile(string ErrMessage) + { + if (!isInitialized) throw new Exception("Logger is not initialized"); + var errPath = errFolder + + $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Error.txt"; + Directory.CreateDirectory(errFolder); + File.AppendAllText(errPath, ErrMessage + " \n"); + } + + public static void WriteErrFile(this Exception ex) + { + if (!isInitialized) throw new Exception("Logger is not initialized"); + WriteErrFile(ex.ToString()); + } } } diff --git a/PluginManager/Online/PluginsManager.cs b/PluginManager/Online/PluginsManager.cs index f509516..8b3f2da 100644 --- a/PluginManager/Online/PluginsManager.cs +++ b/PluginManager/Online/PluginsManager.cs @@ -85,7 +85,7 @@ public class PluginsManager catch (Exception exception) { Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); - Functions.WriteErrFile(exception.ToString()); + Logger.WriteErrFile(exception.ToString()); } } @@ -117,7 +117,7 @@ public class PluginsManager catch (Exception exception) { Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); - Functions.WriteErrFile(exception.ToString()); + Logger.WriteErrFile(exception.ToString()); } return new string[] { null!, null!, null! }; diff --git a/PluginManager/Others/ArchiveManager.cs b/PluginManager/Others/ArchiveManager.cs new file mode 100644 index 0000000..f6d092d --- /dev/null +++ b/PluginManager/Others/ArchiveManager.cs @@ -0,0 +1,139 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Threading.Tasks; + +namespace PluginManager.Others +{ + public static class ArchiveManager + { + public static bool isInitialized { get; private set; } + private static string archiveFolder; + + public static void Initialize() + { + if (isInitialized) throw new Exception("ArchiveManager is already initialized"); + + if (!Config.Variables.Exists("ArchiveFolder")) + Config.Variables.Add("ArchiveFolder", "./Data/PAKS/"); + + isInitialized = true; + archiveFolder = Config.Variables.GetValue("ArchiveFolder"); + + } + /// + /// Read data from a file that is inside an archive (ZIP format) + /// + /// The file name that is inside the archive or its full path + /// The archive location from the PAKs folder + /// A string that represents the content of the file or null if the file does not exists or it has no content + public static async Task ReadFromPakAsync(string FileName, string archFile) + { + if (!isInitialized) throw new Exception("ArchiveManager is not initialized"); + archFile = archiveFolder + archFile; + if (!File.Exists(archFile)) + throw new Exception("Failed to load file !"); + + try + { + string textValue = null; + using (var fs = new FileStream(archFile, FileMode.Open)) + using (var zip = new ZipArchive(fs, ZipArchiveMode.Read)) + { + foreach (var entry in zip.Entries) + if (entry.Name == FileName || entry.FullName == FileName) + using (var s = entry.Open()) + using (var reader = new StreamReader(s)) + { + textValue = await reader.ReadToEndAsync(); + reader.Close(); + s.Close(); + fs.Close(); + } + } + + return textValue; + } + catch + { + await Task.Delay(100); + return await ReadFromPakAsync(FileName, archFile); + } + } + + /// + /// Extract zip to location + /// + /// The zip location + /// The target location + /// 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, + UnzipProgressType type) + { + if (!isInitialized) throw new Exception("ArchiveManager is not initialized"); + Directory.CreateDirectory(folder); + using (var archive = ZipFile.OpenRead(zip)) + { + if (type == UnzipProgressType.PercentageFromNumberOfFiles) + { + var totalZIPFiles = archive.Entries.Count(); + var currentZIPFile = 0; + foreach (var entry in archive.Entries) + { + if (entry.FullName.EndsWith("/")) // it is a folder + Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); + + else + try + { + entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); + } + catch (Exception ex) + { + Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + } + + currentZIPFile++; + await Task.Delay(10); + if (progress != null) + progress.Report((float)currentZIPFile / totalZIPFiles * 100); + } + } + else if (type == UnzipProgressType.PercentageFromTotalSize) + { + ulong zipSize = 0; + + foreach (var entry in archive.Entries) + zipSize += (ulong)entry.CompressedLength; + + ulong currentSize = 0; + foreach (var entry in archive.Entries) + { + if (entry.FullName.EndsWith("/")) + { + Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); + continue; + } + + try + { + entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); + currentSize += (ulong)entry.CompressedLength; + } + catch (Exception ex) + { + Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + } + + await Task.Delay(10); + if (progress != null) + progress.Report((float)currentSize / zipSize * 100); + } + } + } + } + } +} diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index cac962e..903670c 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -1,10 +1,7 @@ using System; using System.Collections.Generic; using System.IO; -using System.IO.Compression; -using System.Linq; using System.Runtime.InteropServices; -using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; @@ -26,90 +23,6 @@ public static class Functions /// public static readonly string dataFolder = @"./Data/Resources/"; - /// - /// The location for all logs - /// - public static readonly string logFolder = @"./Data/Output/Logs/"; - - /// - /// The location for all errors - /// - public static readonly string errFolder = @"./Data/Output/Errors/"; - - /// - /// Archives folder - /// - public static readonly string pakFolder = @"./Data/PAKS/"; - - - /// - /// Read data from a file that is inside an archive (ZIP format) - /// - /// The file name that is inside the archive or its full path - /// The archive location from the PAKs folder - /// A string that represents the content of the file or null if the file does not exists or it has no content - public static async Task ReadFromPakAsync(string FileName, string archFile) - { - archFile = pakFolder + archFile; - if (!File.Exists(archFile)) - throw new Exception("Failed to load file !"); - - try - { - string textValue = null; - using (var fs = new FileStream(archFile, FileMode.Open)) - using (var zip = new ZipArchive(fs, ZipArchiveMode.Read)) - { - foreach (var entry in zip.Entries) - if (entry.Name == FileName || entry.FullName == FileName) - using (var s = entry.Open()) - using (var reader = new StreamReader(s)) - { - textValue = await reader.ReadToEndAsync(); - reader.Close(); - s.Close(); - fs.Close(); - } - } - - return textValue; - } - catch - { - await Task.Delay(100); - return await ReadFromPakAsync(FileName, archFile); - } - } - - - /// - /// Write logs to file - /// - /// The message to be wrote - public static void WriteLogFile(string LogMessage) - { - var logsPath = logFolder + $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Log.txt"; - Directory.CreateDirectory(logFolder); - File.AppendAllText(logsPath, LogMessage + " \n"); - } - - /// - /// Write error to file - /// - /// The message to be wrote - public static void WriteErrFile(string ErrMessage) - { - var errPath = errFolder + - $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Error.txt"; - Directory.CreateDirectory(errFolder); - File.AppendAllText(errPath, ErrMessage + " \n"); - } - - public static void WriteErrFile(this Exception ex) - { - WriteErrFile(ex.ToString()); - } - /// /// Get the Operating system you are runnin on /// @@ -162,79 +75,6 @@ public static class Functions } } - /// - /// Extract zip to location - /// - /// The zip location - /// The target location - /// 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, - UnzipProgressType type) - { - Directory.CreateDirectory(folder); - using (var archive = ZipFile.OpenRead(zip)) - { - if (type == UnzipProgressType.PercentageFromNumberOfFiles) - { - var totalZIPFiles = archive.Entries.Count(); - var currentZIPFile = 0; - foreach (var entry in archive.Entries) - { - if (entry.FullName.EndsWith("/")) // it is a folder - Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); - - else - try - { - entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); - } - catch (Exception ex) - { - Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); - } - - currentZIPFile++; - await Task.Delay(10); - if (progress != null) - progress.Report((float)currentZIPFile / totalZIPFiles * 100); - } - } - else if (type == UnzipProgressType.PercentageFromTotalSize) - { - ulong zipSize = 0; - - foreach (var entry in archive.Entries) - zipSize += (ulong)entry.CompressedLength; - - ulong currentSize = 0; - foreach (var entry in archive.Entries) - { - if (entry.FullName.EndsWith("/")) - { - Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); - continue; - } - - try - { - entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); - currentSize += (ulong)entry.CompressedLength; - } - catch (Exception ex) - { - Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); - } - - await Task.Delay(10); - if (progress != null) - progress.Report((float)currentSize / zipSize * 100); - } - } - } - } - /// /// Save to JSON file /// @@ -267,29 +107,4 @@ public static class Functions text.Close(); return (obj ?? default)!; } - - public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element) - { - Stream text; - if (File.Exists(input)) - text = File.OpenRead(input); - - else - text = new MemoryStream(Encoding.ASCII.GetBytes(input)); - - var jsonObject = JsonDocument.Parse(text); - - var data = jsonObject.RootElement.TryGetProperty(codeName, out element); - return data; - } - - public static string CreateMD5(string input) - { - using (var md5 = MD5.Create()) - { - var inputBytes = Encoding.ASCII.GetBytes(input); - var hashBytes = md5.ComputeHash(inputBytes); - return Convert.ToHexString(hashBytes); - } - } } \ No newline at end of file