plugin list command now shows if the plugin is already installed.

This commit is contained in:
2024-03-26 23:54:44 +02:00
parent b6675af9cb
commit 5d4fa6fba7
14 changed files with 99 additions and 115 deletions

View File

@@ -13,27 +13,27 @@ public class Boot
/// <summary>
/// The bot prefix
/// </summary>
public readonly string botPrefix;
public readonly string BotPrefix;
/// <summary>
/// The bot token
/// </summary>
public readonly string botToken;
public readonly string BotToken;
/// <summary>
/// The bot client
/// </summary>
public DiscordSocketClient client;
public DiscordSocketClient Client;
/// <summary>
/// The bot command handler
/// </summary>
private CommandHandler commandServiceHandler;
private CommandHandler _commandServiceHandler;
/// <summary>
/// The command service
/// </summary>
private CommandService service;
private CommandService _service;
/// <summary>
/// The main Boot constructor
@@ -42,8 +42,8 @@ public class Boot
/// <param name="botPrefix">The bot prefix</param>
public Boot(string botToken, string botPrefix)
{
this.botPrefix = botPrefix;
this.botToken = botToken;
this.BotPrefix = botPrefix;
this.BotToken = botToken;
}
@@ -51,7 +51,7 @@ public class Boot
/// Checks if the bot is ready
/// </summary>
/// <value> true if the bot is ready, otherwise false </value>
public bool isReady { get; private set; }
public bool IsReady { get; private set; }
/// <summary>
/// The start method for the bot. This method is used to load the bot
@@ -73,33 +73,33 @@ public class Boot
GatewayIntents = GatewayIntents.All
};
client = new DiscordSocketClient(config);
service = new CommandService();
Client = new DiscordSocketClient(config);
_service = new CommandService();
CommonTasks();
await client.LoginAsync(TokenType.Bot, botToken);
await Client.LoginAsync(TokenType.Bot, BotToken);
await client.StartAsync();
await Client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix);
_commandServiceHandler = new CommandHandler(Client, _service, BotPrefix);
await commandServiceHandler.InstallCommandsAsync();
await _commandServiceHandler.InstallCommandsAsync();
Config.DiscordBotClient = this;
while (!isReady) ;
while (!IsReady) ;
}
private void CommonTasks()
{
if (client == null) return;
client.LoggedOut += Client_LoggedOut;
client.Log += Log;
client.LoggedIn += LoggedIn;
client.Ready += Ready;
client.Disconnected += Client_Disconnected;
if (Client == null) return;
Client.LoggedOut += Client_LoggedOut;
Client.Log += Log;
Client.LoggedIn += LoggedIn;
Client.Ready += Ready;
Client.Disconnected += Client_Disconnected;
}
private async Task Client_Disconnected(Exception arg)
@@ -122,7 +122,7 @@ public class Boot
private Task Ready()
{
isReady = true;
IsReady = true;
// UxHandler.ShowNotification("SethBot", "Seth Discord Bot is now up and running !").Wait();
return Task.CompletedTask;
}

View File

@@ -130,7 +130,7 @@ internal class CommandHandler
if (plugin is null)
return;
if (plugin.requireAdmin && !context.Message.Author.isAdmin())
if (plugin.requireAdmin && !context.Message.Author.IsAdmin())
return;
var split = cleanMessage.Split(' ');

View File

@@ -12,6 +12,16 @@ namespace PluginManager;
public class Config
{
private static readonly string _DefaultBranchForPlugins = "releases";
private static readonly string _ConfigFile = "./Data/Resources/config.json";
private static readonly string _PluginsDatabaseFile = "./Data/Resources/plugins.json";
private static readonly string _ResourcesFolder = "./Data/Resources";
private static readonly string _PluginsFolder = "./Data/Plugins";
private static readonly string _ArchivesFolder = "./Data/Archives";
private static readonly string _LogsFolder = "./Data/Logs";
private static bool _isLoaded;
public static Logger Logger;
public static SettingsDictionary<string, string> AppSettings;
@@ -26,38 +36,33 @@ public class Config
{
if (_isLoaded) return;
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/Archives");
Directory.CreateDirectory("./Data/Logs");
Directory.CreateDirectory(_ResourcesFolder);
Directory.CreateDirectory(_PluginsFolder);
Directory.CreateDirectory(_ArchivesFolder);
Directory.CreateDirectory(_LogsFolder);
AppSettings = new SettingsDictionary<string, string>("./Data/Resources/config.json");
AppSettings = new SettingsDictionary<string, string>(_ConfigFile);
bool response = await AppSettings.LoadFromFile();
if (!response)
throw new Exception("Invalid config file");
AppSettings["LogFolder"] = "./Data/Logs";
AppSettings["PluginFolder"] = "./Data/Plugins";
AppSettings["ArchiveFolder"] = "./Data/Archives";
AppSettings["PluginDatabase"] = "./Data/Resources/plugins.json";
AppSettings["LogFolder"] = _LogsFolder;
AppSettings["PluginFolder"] = _PluginsFolder;
AppSettings["ArchiveFolder"] = _ArchivesFolder;
ArchiveManager.Initialize();
AppSettings["PluginDatabase"] = _PluginsDatabaseFile;
if (!File.Exists(AppSettings["PluginDatabase"]))
if (!File.Exists(_PluginsDatabaseFile))
{
List<PluginInfo> plugins = new();
await JsonManager.SaveToJsonFile(AppSettings["PluginDatabase"], plugins);
await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins);
}
Logger = new Logger(false, true, AppSettings["LogFolder"] + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log");
Logger = new Logger(false, true, _LogsFolder + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log");
PluginsManager = new PluginsManager("releases");
PluginsManager = new PluginsManager(_DefaultBranchForPlugins);
await PluginsManager.UninstallMarkedPlugins();

View File

@@ -13,22 +13,22 @@ public class ActionsLoader
{
public delegate void ActionLoaded(string name, string typeName, bool success, Exception? e = null);
private readonly string actionExtension = "dll";
private readonly string _actionExtension = "dll";
private readonly string actionFolder = @"./Data/Plugins/";
private readonly string _actionFolder = @"./Data/Plugins/";
public ActionsLoader(string path, string extension)
{
actionFolder = path;
actionExtension = extension;
_actionFolder = path;
_actionExtension = extension;
}
public event ActionLoaded? ActionLoadedEvent;
public async Task<List<ICommandAction>?> Load()
{
Directory.CreateDirectory(actionFolder);
var files = Directory.GetFiles(actionFolder, $"*.{actionExtension}", SearchOption.AllDirectories);
Directory.CreateDirectory(_actionFolder);
var files = Directory.GetFiles(_actionFolder, $"*.{_actionExtension}", SearchOption.AllDirectories);
var actions = new List<ICommandAction>();

View File

@@ -1,6 +0,0 @@
namespace PluginManager.Loaders;
public class PluginHandler
{
}

View File

@@ -1,10 +1,8 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.Online.Helpers;
using PluginManager.Others;
using PluginManager.Plugin;
using PluginManager.Updater.Plugins;
@@ -83,6 +81,13 @@ public class PluginsManager
return await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Config.AppSettings["PluginDatabase"]));
}
public async Task<bool> IsPluginInstalled(string pluginName)
{
List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Config.AppSettings["PluginDatabase"]));
return installedPlugins.Any(plugin => plugin.PluginName == pluginName);
}
public async Task CheckForUpdates()
{
var pluginUpdater = new PluginUpdater(this);

View File

@@ -9,19 +9,19 @@ namespace PluginManager.Others.Actions;
public class InternalActionManager
{
public Dictionary<string, ICommandAction> Actions = new();
public ActionsLoader loader;
private readonly ActionsLoader _loader;
public InternalActionManager(string path, string extension)
{
loader = new ActionsLoader(path, extension);
_loader = new ActionsLoader(path, extension);
}
public async Task Initialize()
{
var m_actions = await loader.Load();
if (m_actions == null)
var loadedActions = await _loader.Load();
if (loadedActions == null)
return;
foreach (var action in m_actions)
foreach (var action in loadedActions)
Actions.TryAdd(action.ActionName, action);
}

View File

@@ -8,27 +8,9 @@ namespace PluginManager.Others;
public static class ArchiveManager
{
private static string? _ArchiveFolder;
private static bool IsInitialized { get; set; }
public static void Initialize()
public static void CreateFromFile(string file, string folder)
{
if (IsInitialized)
throw new Exception("ArchiveManager is already initialized");
if (!Config.AppSettings.ContainsKey("ArchiveFolder"))
Config.AppSettings["ArchiveFolder"] = "./Data/Archives/";
_ArchiveFolder = Config.AppSettings["ArchiveFolder"];
IsInitialized = true;
}
public static async Task CreateFromFile(string file, string folder)
{
if(!IsInitialized) throw new Exception("ArchiveManager is not initialized");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
@@ -50,9 +32,8 @@ public static class ArchiveManager
/// <returns>An array of bytes that represents the Stream value from the file that was read inside the archive</returns>
public static async Task<byte[]?> ReadStreamFromPakAsync(string fileName, string archName)
{
if (!IsInitialized) throw new Exception("ArchiveManager is not initialized");
archName = _ArchiveFolder + archName;
archName = Config.AppSettings["ArchiveFolder"] + archName;
if (!File.Exists(archName))
throw new Exception("Failed to load file !");
@@ -80,8 +61,7 @@ public static class ArchiveManager
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<string?> ReadFromPakAsync(string fileName, string archFile)
{
if (!IsInitialized) throw new Exception("ArchiveManager is not initialized");
archFile = _ArchiveFolder + archFile;
archFile = Config.AppSettings["ArchiveFolder"] + archFile;
if (!File.Exists(archFile))
throw new Exception("Failed to load file !");
@@ -125,7 +105,6 @@ public static class ArchiveManager
string zip, string folder, IProgress<float> progress,
UnzipProgressType type)
{
if (!IsInitialized) throw new Exception("ArchiveManager is not initialized");
Directory.CreateDirectory(folder);
using var archive = ZipFile.OpenRead(zip);
var totalZipFiles = archive.Entries.Count();

View File

@@ -6,6 +6,13 @@ namespace PluginManager.Others;
public class DbCommandExecutingArguments
{
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
public ISocketMessageChannel Channel => context.Channel;
public DbCommandExecutingArguments(
SocketCommandContext context, string cleanContent, string commandUsed, string[]? arguments)
{
@@ -26,7 +33,7 @@ public class DbCommandExecutingArguments
}
else
{
cleanContent = message.Content.Substring(Config.DiscordBot.botPrefix.Length);
cleanContent = message.Content.Substring(Config.DiscordBot.BotPrefix.Length);
}
var split = cleanContent.Split(' ');
@@ -38,10 +45,4 @@ public class DbCommandExecutingArguments
commandUsed = split[0];
arguments = argsClean;
}
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
public ISocketMessageChannel Channel => context.Channel;
}

View File

@@ -19,12 +19,6 @@ public enum UnzipProgressType
PERCENTAGE_FROM_TOTAL_SIZE
}
public enum SaveType
{
TXT,
JSON
}
public enum InternalActionRunType
{
ON_STARTUP,

View File

@@ -26,7 +26,7 @@ public static class DiscordPermissions
/// <param name="user">The user</param>
/// <param name="role">The role</param>
/// <returns></returns>
public static bool hasRole(this SocketGuildUser user, IRole role)
public static bool HasRole(this SocketGuildUser user, IRole role)
{
return user.Roles.Contains(role);
}
@@ -37,7 +37,7 @@ public static class DiscordPermissions
/// <param name="user">The user</param>
/// <param name="permission">The permission</param>
/// <returns></returns>
public static bool hasPermission(this SocketGuildUser user, GuildPermission permission)
public static bool HasPermission(this SocketGuildUser user, GuildPermission permission)
{
return user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user;
}
@@ -47,9 +47,9 @@ public static class DiscordPermissions
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketGuildUser user)
public static bool IsAdmin(this SocketGuildUser user)
{
return user.hasPermission(GuildPermission.Administrator);
return user.HasPermission(GuildPermission.Administrator);
}
/// <summary>
@@ -57,8 +57,8 @@ public static class DiscordPermissions
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketUser user)
public static bool IsAdmin(this SocketUser user)
{
return isAdmin((SocketGuildUser)user);
return IsAdmin((SocketGuildUser)user);
}
}

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.Online;
using PluginManager.Plugin;
@@ -10,16 +9,16 @@ namespace PluginManager.Updater.Plugins;
public class PluginUpdater
{
private readonly PluginsManager _PluginManager;
private readonly PluginsManager _PluginsManager;
public PluginUpdater(PluginsManager pluginManager)
{
_PluginManager = pluginManager;
_PluginsManager = pluginManager;
}
public async Task<PluginOnlineInfo> GetPluginInfo(string pluginName)
{
var result = await _PluginManager.GetPluginDataByName(pluginName);
var result = await _PluginsManager.GetPluginDataByName(pluginName);
return result;
}
@@ -41,8 +40,8 @@ public class PluginUpdater
foreach(OnlineDependencyInfo dependency in pluginInfo.Dependencies)
await ServerCom.DownloadFileAsync(dependency.DownloadLocation, dependency.DownloadLocation, progressMeter);
await _PluginManager.RemovePluginFromDatabase(pluginName);
await _PluginManager.AppendPluginToDatabase(PluginInfo.FromOnlineInfo(pluginInfo));
await _PluginsManager.RemovePluginFromDatabase(pluginName);
await _PluginsManager.AppendPluginToDatabase(PluginInfo.FromOnlineInfo(pluginInfo));
}
public async Task<bool> HasUpdate(string pluginName)