cleaning up PluginManager (phase 1)

This commit is contained in:
Tudor Andrei
2023-04-25 14:27:55 +03:00
parent b0be76c62b
commit 5edcf93371
17 changed files with 247 additions and 200 deletions

View File

@@ -40,7 +40,7 @@ internal class Help : DBCommand
/// The main body of the command /// The main body of the command
/// </summary> /// </summary>
/// <param name="context">The command context</param> /// <param name="context">The command context</param>
public void ExecuteServer(CmdArgs args) public void ExecuteServer(DBCommandExecutingArguments args)
{ {
if (args.arguments is not null) if (args.arguments is not null)
{ {

View File

@@ -8,12 +8,13 @@ using System.Threading.Tasks;
using PluginManager; using PluginManager;
using PluginManager.Bot; using PluginManager.Bot;
using PluginManager.Items;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.WindowManagement; using PluginManager.WindowManagement;
using DiscordBot.Utilities;
using OperatingSystem = PluginManager.Others.OperatingSystem; using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace DiscordBot; namespace DiscordBot;
@@ -89,15 +90,15 @@ public class Program
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}"); Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}");
Utilities.WriteColorText( Utilities.Utilities.WriteColorText(
"&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n");
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
if (Config.Data.ContainsKey("LaunchMessage")) if (Config.Data.ContainsKey("LaunchMessage"))
Utilities.WriteColorText(Config.Data["LaunchMessage"]); Utilities.Utilities.WriteColorText(Config.Data["LaunchMessage"]);
Utilities.WriteColorText( Utilities.Utilities.WriteColorText(
"Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)");
Logger.WriteLine(); Logger.WriteLine();
@@ -172,7 +173,7 @@ public class Program
Logger.WriteLine("Loading resources ..."); Logger.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END); var main = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start(); main.Start();
if (Config.Data.ContainsKey("DeleteLogsAtStartup")) if (Config.Data.ContainsKey("DeleteLogsAtStartup"))
@@ -257,7 +258,7 @@ public class Program
List<string> changeLog = await ServerCom.ReadTextFromURL( List<string> changeLog = await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot"); "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot");
foreach (var item in changeLog) foreach (var item in changeLog)
Utilities.WriteColorText(item); Utilities.Utilities.WriteColorText(item);
Logger.WriteLine("Do you want to update the bot ? (y/n)"); Logger.WriteLine("Do you want to update the bot ? (y/n)");
if (Console.ReadKey().Key == ConsoleKey.Y) if (Console.ReadKey().Key == ConsoleKey.Y)
{ {
@@ -311,11 +312,11 @@ public class Program
{ {
Console.Clear(); Console.Clear();
Logger.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !"); Logger.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !");
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync( await ServerCom.DownloadFileAsync(
"https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Launcher.exe", "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Launcher.exe",
$"./Launcher.exe"); $"./Launcher.exe", null);
//await ArchiveManager.ExtractArchive("./Updater.zip", "./", null, //await ArchiveManager.ExtractArchive("./Updater.zip", "./", null,
// UnzipProgressType.PercentageFromTotalSize); // UnzipProgressType.PercentageFromTotalSize);
Config.Data["LauncherVersion"] = updaternewversion; Config.Data["LauncherVersion"] = updaternewversion;

View File

@@ -3,7 +3,7 @@ using System.Collections.Generic;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Items; namespace DiscordBot.Utilities;
public class ConsoleCommand public class ConsoleCommand
{ {

View File

@@ -4,7 +4,7 @@ using System.Threading.Tasks;
using PluginManager; using PluginManager;
namespace PluginManager.Others; namespace DiscordBot.Utilities;
public static class Utilities public static class Utilities
{ {
@@ -48,38 +48,38 @@ public static class Utilities
foreach (var row in data) foreach (var row in data)
{ {
if (row[0][0] == tableLine) if (row[0][0] == tableLine)
PluginManager.Logger.Write(tableCross); Console.Write(tableCross);
else else
PluginManager.Logger.Write(tableWall); Console.Write(tableWall);
for (var l = 0; l < row.Length; l++) for (var l = 0; l < row.Length; l++)
{ {
if (row[l][0] == tableLine) if (row[l][0] == tableLine)
{ {
for (var i = 0; i < len[l] + 4; ++i) for (var i = 0; i < len[l] + 4; ++i)
PluginManager.Logger.Write(tableLine); Console.Write(tableLine);
} }
else if (row[l].Length == len[l]) else if (row[l].Length == len[l])
{ {
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write(row[l]); Console.Write(row[l]);
PluginManager.Logger.Write(" "); Console.Write(" ");
} }
else else
{ {
var lenHalf = row[l].Length / 2; var lenHalf = row[l].Length / 2;
for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i)
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write(row[l]); Console.Write(row[l]);
for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
PluginManager.Logger.Write(" "); Console.Write(" ");
if (row[l].Length % 2 == 0) if (row[l].Length % 2 == 0)
PluginManager.Logger.Write(" "); Console.Write(" ");
} }
PluginManager.Logger.Write(row[l][0] == tableLine ? tableCross : tableWall); Console.Write(row[l][0] == tableLine ? tableCross : tableWall);
} }
PluginManager.Logger.WriteLine(); //end line Console.WriteLine(); //end line
} }
return; return;
@@ -97,44 +97,44 @@ public static class Utilities
foreach (var row in data) foreach (var row in data)
{ {
PluginManager.Logger.Write("\t"); Console.Write("\t");
if (row[0] == "-") if (row[0] == "-")
PluginManager.Logger.Write("+"); Console.Write("+");
else else
PluginManager.Logger.Write("|"); Console.Write("|");
foreach (var s in row) foreach (var s in row)
{ {
if (s == "-") if (s == "-")
{ {
for (var i = 0; i < maxLen + 4; ++i) for (var i = 0; i < maxLen + 4; ++i)
PluginManager.Logger.Write("-"); Console.Write("-");
} }
else if (s.Length == maxLen) else if (s.Length == maxLen)
{ {
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write(s); Console.Write(s);
PluginManager.Logger.Write(" "); Console.Write(" ");
} }
else else
{ {
var lenHalf = s.Length / 2; var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i) for (var i = 0; i < div - lenHalf; ++i)
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write(s); Console.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
PluginManager.Logger.Write(" "); Console.Write(" ");
if (s.Length % 2 == 0) if (s.Length % 2 == 0)
PluginManager.Logger.Write(" "); Console.Write(" ");
} }
if (s == "-") if (s == "-")
PluginManager.Logger.Write("+"); Console.Write("+");
else else
PluginManager.Logger.Write("|"); Console.Write("|");
} }
PluginManager.Logger.WriteLine(); //end line Console.WriteLine(); //end line
} }
return; return;
@@ -155,12 +155,12 @@ public static class Utilities
{ {
if (data[i][j] == "-") if (data[i][j] == "-")
data[i][j] = " "; data[i][j] = " ";
PluginManager.Logger.Write(data[i][j]); Console.Write(data[i][j]);
for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
PluginManager.Logger.Write(" "); Console.Write(" ");
} }
PluginManager.Logger.WriteLine(); Console.WriteLine();
} }
return; return;
@@ -171,16 +171,6 @@ public static class Utilities
public static void WriteColorText(string text, bool appendNewLineAtEnd = true) public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{ {
if (!PluginManager.Logger.isConsole)
{
foreach (var item in Colors)
text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", "");
PluginManager.Logger.Write(text);
if (appendNewLineAtEnd)
PluginManager.Logger.WriteLine();
return;
}
var initialForeGround = Console.ForegroundColor; var initialForeGround = Console.ForegroundColor;
var input = text.ToCharArray(); var input = text.ToCharArray();
for (var i = 0; i < input.Length; i++) for (var i = 0; i < input.Length; i++)
@@ -202,12 +192,12 @@ public static class Utilities
} }
else else
{ {
PluginManager.Logger.Write(input[i]); Console.Write(input[i]);
} }
Console.ForegroundColor = initialForeGround; Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd) if (appendNewLineAtEnd)
PluginManager.Logger.WriteLine(); Console.WriteLine();
} }
@@ -224,8 +214,6 @@ public static class Utilities
public ProgressBar(ProgressBarType type) public ProgressBar(ProgressBarType type)
{ {
if (!PluginManager.Logger.isConsole)
throw new Exception("This class (or function) can be used with console only. For UI please use another approach.");
this.type = type; this.type = type;
} }
@@ -286,9 +274,9 @@ public static class Utilities
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
for (var i = 0; i < BarLength + message.Length + 1; i++) for (var i = 0; i < BarLength + message.Length + 1; i++)
PluginManager.Logger.Write(" "); Console.Write(" ");
Console.CursorLeft = 0; Console.CursorLeft = 0;
PluginManager.Logger.WriteLine(message); Console.WriteLine(message);
} }
} }
@@ -303,14 +291,14 @@ public static class Utilities
private void UpdateNoEnd(string message) private void UpdateNoEnd(string message)
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
PluginManager.Logger.Write("["); Console.Write("[");
for (var i = 1; i <= position; i++) for (var i = 1; i <= position; i++)
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write("<==()==>"); Console.Write("<==()==>");
position += positive ? 1 : -1; position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write("] " + message); Console.Write("] " + message);
if (position == BarLength - 1 || position == 1) if (position == BarLength - 1 || position == 1)
@@ -320,14 +308,14 @@ public static class Utilities
private void UpdateNoEnd() private void UpdateNoEnd()
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
PluginManager.Logger.Write("["); Console.Write("[");
for (var i = 1; i <= position; i++) for (var i = 1; i <= position; i++)
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write("<==()==>"); Console.Write("<==()==>");
position += positive ? 1 : -1; position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
PluginManager.Logger.Write(" "); Console.Write(" ");
PluginManager.Logger.Write("]"); Console.Write("]");
if (position == BarLength - 1 || position == 1) if (position == BarLength - 1 || position == 1)
@@ -337,9 +325,9 @@ public static class Utilities
private void UpdateNormal(float progress) private void UpdateNormal(float progress)
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
PluginManager.Logger.Write("["); Console.Write("[");
Console.CursorLeft = BarLength; Console.CursorLeft = BarLength;
PluginManager.Logger.Write("]"); Console.Write("]");
Console.CursorLeft = 1; Console.CursorLeft = 1;
var onechunk = 30.0f / Max; var onechunk = 30.0f / Max;
@@ -349,22 +337,22 @@ public static class Utilities
{ {
Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color;
Console.CursorLeft = position++; Console.CursorLeft = position++;
PluginManager.Logger.Write("#"); Console.Write("#");
} }
for (var i = position; i < BarLength; i++) for (var i = position; i < BarLength; i++)
{ {
Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.CursorLeft = position++; Console.CursorLeft = position++;
PluginManager.Logger.Write(" "); Console.Write(" ");
} }
Console.CursorLeft = BarLength + 4; Console.CursorLeft = BarLength + 4;
Console.BackgroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black;
if (progress.CanAproximateTo(Max)) if (progress.CanAproximateTo(Max))
PluginManager.Logger.Write(progress + " % ✓"); Console.Write(progress + " % ✓");
else else
PluginManager.Logger.Write(MathF.Round(progress, 2) + " % "); Console.Write(MathF.Round(progress, 2) + " % ");
} }
} }
} }

View File

@@ -9,13 +9,14 @@ using System.Threading.Tasks;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager;
using PluginManager.Loaders; using PluginManager.Loaders;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Others; using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem; using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Items; namespace DiscordBot.Utilities;
public class ConsoleCommandsHandler public class ConsoleCommandsHandler
{ {
@@ -31,12 +32,11 @@ public class ConsoleCommandsHandler
public ConsoleCommandsHandler(DiscordSocketClient client) public ConsoleCommandsHandler(DiscordSocketClient client)
{ {
if (!Logger.isConsole) throw new Exception("Can not use ConsoleCommandsHandler for Non console apps");
this.client = client; this.client = client;
InitializeBasicCommands(); InitializeBasicCommands();
//Logger.WriteLine("Initialized console command handler !"); //Console.WriteLine("Initialized console command handler !");
} }
private void InitializeBasicCommands() private void InitializeBasicCommands()
@@ -47,7 +47,7 @@ public class ConsoleCommandsHandler
{ {
if (args.Length <= 1) if (args.Length <= 1)
{ {
Logger.WriteLine("Available commands:"); Console.WriteLine("Available commands:");
var items = new List<string[]> var items = new List<string[]>
{ {
new[] { "-", "-", "-" }, new[] { "-", "-", "-" },
@@ -70,12 +70,12 @@ public class ConsoleCommandsHandler
foreach (var command in commandList) foreach (var command in commandList)
if (command.CommandName == args[1]) if (command.CommandName == args[1])
{ {
Logger.WriteLine("Command description: " + command.Description); Console.WriteLine("Command description: " + command.Description);
Logger.WriteLine("Command execution format:" + command.Usage); Console.WriteLine("Command execution format:" + command.Usage);
return; return;
} }
Logger.WriteLine("Command not found"); Console.WriteLine("Command not found");
} }
} }
); );
@@ -94,16 +94,16 @@ public class ConsoleCommandsHandler
if (success) if (success)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("[CMD] Successfully loaded command : " + name); Console.WriteLine("[CMD] Successfully loaded command : " + name);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
if (exception is null) if (exception is null)
Logger.WriteLine("An error occured while loading: " + name); Console.WriteLine("An error occured while loading: " + name);
else else
Logger.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
} }
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
@@ -116,12 +116,12 @@ public class ConsoleCommandsHandler
if (success) if (success)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("[EVENT] Successfully loaded event : " + name); Console.WriteLine("[EVENT] Successfully loaded event : " + name);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
} }
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
@@ -135,12 +135,12 @@ public class ConsoleCommandsHandler
if (success) if (success)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("[SLASH] Successfully loaded command : " + name); Console.WriteLine("[SLASH] Successfully loaded command : " + name);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); Console.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message);
} }
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
@@ -152,7 +152,23 @@ public class ConsoleCommandsHandler
} }
); );
AddCommand("listplugs", "list available plugins", () => { manager.ListAvailablePlugins().Wait(); }); AddCommand("listplugs", "list available plugins", async () => {
var data = await manager.GetAvailablePlugins();
var items = new List<string[]>
{
new[] { "-", "-", "-", "-" },
new[] { "Name", "Type", "Description", "Required" },
new[] { "-", "-", "-", "-" }
};
foreach (var plugin in data)
{
items.Add(new[] { plugin[0], plugin[1], plugin[2], plugin[3] });
}
items.Add(new[] { "-", "-", "-", "-" });
Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
});
AddCommand("dwplug", "download plugin", "dwplug [name]", async args => AddCommand("dwplug", "download plugin", "dwplug [name]", async args =>
{ {
@@ -160,7 +176,7 @@ public class ConsoleCommandsHandler
if (args.Length == 1) if (args.Length == 1)
{ {
isDownloading = false; isDownloading = false;
Logger.WriteLine("Please specify plugin name"); Console.WriteLine("Please specify plugin name");
return; return;
} }
@@ -192,24 +208,24 @@ public class ConsoleCommandsHandler
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{ {
await ServerCom.DownloadFileAsync(info[1], path); await ServerCom.DownloadFileAsync(info[1], path, null);
} }
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{ {
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync(info[1], path); await ServerCom.DownloadFileAsync(info[1], path, null);
bar.Stop("Plugin Downloaded !"); bar.Stop("Plugin Downloaded !");
} }
Logger.WriteLine("\n"); Console.WriteLine("\n");
// check requirements if any // check requirements if any
if (info.Length == 3 && info[2] != string.Empty && info[2] != null) if (info.Length == 3 && info[2] != string.Empty && info[2] != null)
{ {
Logger.WriteLine($"Downloading requirements for plugin : {name}"); Console.WriteLine($"Downloading requirements for plugin : {name}");
var lines = await ServerCom.ReadTextFromURL(info[2]); var lines = await ServerCom.ReadTextFromURL(info[2]);
@@ -218,40 +234,40 @@ public class ConsoleCommandsHandler
if (!(line.Length > 0 && line.Contains(","))) if (!(line.Length > 0 && line.Contains(",")))
continue; continue;
var split = line.Split(','); var split = line.Split(',');
Logger.WriteLine($"\nDownloading item: {split[1]}"); Console.WriteLine($"\nDownloading item: {split[1]}");
if (File.Exists("./" + split[1])) File.Delete("./" + split[1]); if (File.Exists("./" + split[1])) File.Delete("./" + split[1]);
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{ {
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]); await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null);
} }
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{ {
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]); await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null);
bar.Stop("Item downloaded !"); bar.Stop("Item downloaded !");
} }
Logger.WriteLine(); Console.WriteLine();
if (split[0].EndsWith(".pak")) if (split[0].EndsWith(".pak"))
{ {
File.Move("./" + split[1], "./Data/PAKS/" + split[1], true); File.Move("./" + split[1], "./Data/PAKS/" + split[1], true);
} }
else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg")) else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg"))
{ {
Logger.WriteLine($"Extracting {split[1]} ..."); Console.WriteLine($"Extracting {split[1]} ...");
var bar = new Utilities.ProgressBar( var bar = new Utilities.ProgressBar(
ProgressBarType.NO_END); ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ArchiveManager.ExtractArchive("./" + split[1], "./", null, await ArchiveManager.ExtractArchive("./" + split[1], "./", null,
UnzipProgressType.PercentageFromTotalSize); UnzipProgressType.PercentageFromTotalSize);
bar.Stop("Extracted"); bar.Stop("Extracted");
Logger.WriteLine("\n"); Console.WriteLine("\n");
File.Delete("./" + split[1]); File.Delete("./" + split[1]);
} }
} }
Logger.WriteLine(); Console.WriteLine();
} }
var ver = await ServerCom.GetVersionOfPackageFromWeb(name); var ver = await ServerCom.GetVersionOfPackageFromWeb(name);
@@ -273,7 +289,7 @@ public class ConsoleCommandsHandler
return; return;
var data = Config.Data[args[1]]; var data = Config.Data[args[1]];
Logger.WriteLine($"{args[1]} => {data}"); Console.WriteLine($"{args[1]} => {data}");
} }
); );
@@ -288,11 +304,11 @@ public class ConsoleCommandsHandler
try try
{ {
Config.Data[key] = value; Config.Data[key] = value;
Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.ToString()); Console.WriteLine(ex.ToString());
} }
} }
); );
@@ -341,7 +357,7 @@ public class ConsoleCommandsHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.Message); Console.WriteLine(ex.Message);
} }
}); });
@@ -357,8 +373,8 @@ public class ConsoleCommandsHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.Message); Console.WriteLine(ex.Message);
Logger.WriteErrFile(ex); Config.Logger.Log(ex.Message, this, TextType.ERROR);
} }
}); });
@@ -392,13 +408,13 @@ public class ConsoleCommandsHandler
if (!File.Exists(location)) if (!File.Exists(location))
{ {
Logger.WriteLine("The plugin does not exist"); Console.WriteLine("The plugin does not exist");
return; return;
} }
File.Delete(location); File.Delete(location);
Logger.WriteLine("Removed the plugin DLL. Checking for other files ..."); Console.WriteLine("Removed the plugin DLL. Checking for other files ...");
var info = await manager.GetPluginLinkByName(plugName); var info = await manager.GetPluginLinkByName(plugName);
if (info[2] != string.Empty) if (info[2] != string.Empty)
@@ -413,7 +429,7 @@ public class ConsoleCommandsHandler
File.Delete("./" + split[1]); File.Delete("./" + split[1]);
Logger.WriteLine("Removed: " + split[1]); Console.WriteLine("Removed: " + split[1]);
} }
if (Directory.Exists($"./Data/Plugins/{plugName}")) if (Directory.Exists($"./Data/Plugins/{plugName}"))
@@ -424,7 +440,7 @@ public class ConsoleCommandsHandler
} }
isDownloading = false; isDownloading = false;
Logger.WriteLine(plugName + " has been successfully deleted !"); Console.WriteLine(plugName + " has been successfully deleted !");
}); });
AddCommand("reload", "Reload the bot with all plugins", () => AddCommand("reload", "Reload the bot with all plugins", () =>
@@ -484,7 +500,7 @@ public class ConsoleCommandsHandler
foreach (var item in commandList) foreach (var item in commandList)
if (item.CommandName == args[0]) if (item.CommandName == args[0])
{ {
Logger.WriteLine(); Console.WriteLine();
item.Action(args); item.Action(args);
} }
@@ -492,8 +508,6 @@ public class ConsoleCommandsHandler
public static async Task ExecuteCommad(string command) 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(' '); var args = command.Split(' ');
foreach (var item in commandList.ToList()) foreach (var item in commandList.ToList())
if (item.CommandName == args[0]) if (item.CommandName == args[0])
@@ -505,8 +519,6 @@ public class ConsoleCommandsHandler
public bool HandleCommand(string command, bool removeCommandExecution = true) public bool HandleCommand(string command, bool removeCommandExecution = true)
{ {
if (!Logger.isConsole)
throw new Exception("Can not use console based commands on non console based application !");
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
var args = command.Split(' '); var args = command.Split(' ');
foreach (var item in commandList.ToList()) foreach (var item in commandList.ToList())
@@ -515,22 +527,20 @@ public class ConsoleCommandsHandler
if (args[0].StartsWith("_")) if (args[0].StartsWith("_"))
throw new Exception("This command is reserved for internal worker and can not be executed manually !"); throw new Exception("This command is reserved for internal worker and can not be executed manually !");
if (Logger.isConsole)
if (removeCommandExecution) if (removeCommandExecution)
{ {
Console.SetCursorPosition(0, Console.CursorTop - 1); Console.SetCursorPosition(0, Console.CursorTop - 1);
for (var i = 0; i < command.Length + 30; i++) for (var i = 0; i < command.Length + 30; i++)
Logger.Write(" "); Console.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop); Console.SetCursorPosition(0, Console.CursorTop);
} }
Logger.WriteLine(); Console.WriteLine();
item.Action(args); item.Action(args);
return true; return true;
} }
return false; return false;
//Logger.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
} }
} }

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiscordBot.Utilities
{
public enum TableFormat
{
CENTER_EACH_COLUMN_BASED,
CENTER_OVERALL_LENGTH,
DEFAULT
}
public enum ProgressBarType
{
NORMAL,
NO_END
}
}

View File

@@ -40,7 +40,7 @@ internal class Help : DBCommand
/// The main body of the command /// The main body of the command
/// </summary> /// </summary>
/// <param name="context">The command context</param> /// <param name="context">The command context</param>
public void ExecuteServer(CmdArgs args) public void ExecuteServer(DBCommandExecutingArguments args)
{ {
if (args.arguments is not null) if (args.arguments is not null)
{ {

View File

@@ -138,7 +138,7 @@ internal class CommandHandler
if(split.Length > 1) if(split.Length > 1)
argsClean = string.Join(' ', split, 1, split.Length-1).Split(' '); argsClean = string.Join(' ', split, 1, split.Length-1).Split(' ');
CmdArgs cmd = new(context, cleanMessage, split[0], argsClean); DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean);
if (context.Channel is SocketDMChannel) if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(cmd); plugin.ExecuteDM(cmd);

View File

@@ -1,6 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using Discord.Commands;
using PluginManager.Others; using PluginManager.Others;
namespace PluginManager.Interfaces; namespace PluginManager.Interfaces;
@@ -37,16 +35,16 @@ public interface DBCommand
/// <summary> /// <summary>
/// The main body of the command. This is what is executed when user calls the command in Server /// The main body of the command. This is what is executed when user calls the command in Server
/// </summary> /// </summary>
/// <param name="context">The disocrd Context</param> /// <param name="args">The disocrd Context</param>
void ExecuteServer(CmdArgs args) void ExecuteServer(DBCommandExecutingArguments args)
{ {
} }
/// <summary> /// <summary>
/// The main body of the command. This is what is executed when user calls the command in DM /// The main body of the command. This is what is executed when user calls the command in DM
/// </summary> /// </summary>
/// <param name="context">The disocrd Context</param> /// <param name="args">The disocrd Context</param>
void ExecuteDM(CmdArgs args) void ExecuteDM(DBCommandExecutingArguments args)
{ {
} }
} }

View File

@@ -29,7 +29,7 @@ public class PluginsManager
/// The method to load all plugins /// The method to load all plugins
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task<List<string[]>> ListAvailablePlugins() public async Task<List<string[]>> GetAvailablePlugins()
{ {
try try
{ {
@@ -40,16 +40,12 @@ public class PluginsManager
var op = Functions.GetOperatingSystem(); var op = Functions.GetOperatingSystem();
var len = lines.Length; var len = lines.Length;
string[] titles = { "Name", "Description", "Type", "Version" };
data.Add(new[] { "-", "-", "-", "-" });
data.Add(titles);
data.Add(new[] { "-", "-", "-", "-" });
for (var i = 0; i < len; i++) for (var i = 0; i < len; i++)
{ {
if (lines[i].Length <= 2) if (lines[i].Length <= 2)
continue; continue;
var content = lines[i].Split(','); var content = lines[i].Split(',');
var display = new string[titles.Length]; var display = new string[4]; // 4 columns
if (op == OperatingSystem.WINDOWS) if (op == OperatingSystem.WINDOWS)
{ {
if (content[4].Contains("Windows")) if (content[4].Contains("Windows"))
@@ -80,14 +76,11 @@ public class PluginsManager
data.Add(new[] { "-", "-", "-", "-" }); data.Add(new[] { "-", "-", "-", "-" });
Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED);
return data; return data;
} }
catch (Exception exception) catch (Exception exception)
{ {
Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Config.Logger.Log("Failed to execute command: listplugs\nReason: " + exception.Message, this, TextType.ERROR);
Logger.WriteErrFile(exception.ToString());
} }
return null; return null;
@@ -120,8 +113,7 @@ public class PluginsManager
} }
catch (Exception exception) catch (Exception exception)
{ {
Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Config.Logger.Log("Failed to execute command: listplugs\nReason: " + exception.Message, this, TextType.ERROR);
Logger.WriteErrFile(exception.ToString());
} }
return new string[] { null!, null!, null! }; return new string[] { null!, null!, null! };

View File

@@ -33,7 +33,7 @@ public static class ServerCom
/// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param> /// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param>
/// <returns></returns> /// <returns></returns>
public static async Task DownloadFileAsync(string URL, string location, IProgress<float> progress, public static async Task DownloadFileAsync(string URL, string location, IProgress<float> progress,
IProgress<long>? downloadedBytes = null) IProgress<long>? downloadedBytes)
{ {
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
@@ -46,47 +46,9 @@ public static class ServerCom
} }
} }
/// <summary> public static async Task DownloadFileAsync(string URl, string location, IProgress<float> progress)
/// Download file from url
/// </summary>
/// <param name="URL">The url to the file</param>
/// <param name="location">The location where to store the downloaded data</param>
/// <returns></returns>
public static async Task DownloadFileAsync(string URL, string location)
{ {
var isDownloading = true; await DownloadFileAsync(URl, location, progress, null);
float c_progress = 0;
var pbar = new Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true };
IProgress<float> progress = new Progress<float>(percent => { c_progress = percent; });
var updateProgressBarTask = new Task(() =>
{
while (isDownloading)
{
pbar.Update(c_progress);
if (c_progress == 100f)
break;
Thread.Sleep(500);
}
}
);
new Thread(updateProgressBarTask.Start).Start();
await DownloadFileAsync(URL, location, progress);
c_progress = pbar.Max;
pbar.Update(100f);
isDownloading = false;
}
public static async Task DownloadFileNoProgressAsync(string URL, string location)
{
IProgress<float> progress = new Progress<float>();
await DownloadFileAsync(URL, location, progress);
} }
public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName) public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName)

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PluginManager.Others.Actions
{
public class ActionManager
{
public List<InternalAction> Actions { get; private set; }
private bool _isInitialized = false;
public ActionManager()
{
if(_isInitialized) return;
Actions = new List<InternalAction>();
_isInitialized = true;
}
public bool ActionExists(string name)
{
if(!_isInitialized) throw new Exception("ActionManager is not initialized");
return Actions.Any(x => x.Name == name);
}
public void AddAction(InternalAction action)
{
if(!_isInitialized) throw new Exception("ActionManager is not initialized");
Actions.Add(action);
}
public void ExecuteAction(string name, string[] args)
{
if(!_isInitialized) throw new Exception("ActionManager is not initialized");
var action = Actions.FirstOrDefault(x => x.Name == name);
if(action == null) throw new Exception($"Action {name} not found");
action.Invoke(args);
}
public async Task ExecuteActionAsync(string name, string[] args)
{
if(!_isInitialized) throw new Exception("ActionManager is not initialized");
var action = Actions.FirstOrDefault(x => x.Name == name);
if(action == null) throw new Exception($"Action {name} not found");
await action.InvokeAsync(args);
}
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others.Actions
{
public class InternalAction
{
public string? Name { get; init; }
public Action<string[]> Action { get; init; }
public InternalAction(string name, Action<string[]> action)
{
Name = name;
Action = action;
}
public InternalAction(string name, Action action)
{
Name = name;
Action = (o) =>
{
action();
return;
};
}
public void Invoke(string[] args)
{
Action(args);
}
public async Task InvokeAsync(string[] args)
{
await Task.Run(() => Action(args));
}
}
}

View File

@@ -58,7 +58,7 @@ namespace PluginManager.Others
} }
catch (Exception ex) catch (Exception ex)
{ {
ex.WriteErrFile(); // Write the error to a file Config.Logger.Log(ex.Message, "Archive Manager", TextType.ERROR); // Write the error to a file
await Task.Delay(100); await Task.Delay(100);
return await ReadFromPakAsync(FileName, archFile); return await ReadFromPakAsync(FileName, archFile);
} }

View File

@@ -8,14 +8,14 @@ using System.Threading.Tasks;
namespace PluginManager.Others namespace PluginManager.Others
{ {
public class CmdArgs public class DBCommandExecutingArguments
{ {
public SocketCommandContext context { get; init; } public SocketCommandContext context { get; init; }
public string cleanContent { get; init; } public string cleanContent { get; init; }
public string commandUsed { get;init; } public string commandUsed { get;init; }
public string[] arguments { get;init; } public string[] arguments { get;init; }
public CmdArgs(SocketCommandContext context, string cleanContent, string commandUsed, string[] arguments) public DBCommandExecutingArguments(SocketCommandContext context, string cleanContent, string commandUsed, string[] arguments)
{ {
this.context = context; this.context = context;
this.cleanContent = cleanContent; this.cleanContent = cleanContent;

View File

@@ -42,25 +42,12 @@ public enum UnzipProgressType
PercentageFromTotalSize PercentageFromTotalSize
} }
public enum TableFormat
{
CENTER_EACH_COLUMN_BASED,
CENTER_OVERALL_LENGTH,
DEFAULT
}
public enum SaveType public enum SaveType
{ {
NORMAL, NORMAL,
BACKUP BACKUP
} }
public enum ProgressBarType
{
NORMAL,
NO_END
}
public enum TextType public enum TextType
{ {
NORMAL, NORMAL,

View File

@@ -15,7 +15,4 @@
<PackageReference Include="Discord.Net" Version="3.8.1" /> <PackageReference Include="Discord.Net" Version="3.8.1" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" /> <PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Others\Actions\" />
</ItemGroup>
</Project> </Project>