Renamed PluginManager to DiscordBotCore.

Revamped the Logger
This commit is contained in:
2024-05-12 20:10:52 +03:00
parent 413d465d7f
commit 17147d920d
66 changed files with 529 additions and 556 deletions

View File

@@ -2,9 +2,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
using PluginManager.Others.Actions; using DiscordBotCore.Others.Actions;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;

View File

@@ -1,10 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager; using DiscordBotCore;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
using PluginManager.Others.Actions; using DiscordBotCore.Others.Actions;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
@@ -24,8 +24,8 @@ public class Exit: ICommandAction
{ {
if (args is null || args.Length == 0) if (args is null || args.Length == 0)
{ {
Config.Logger.Log("Exiting...", typeof(ICommandAction), LogType.WARNING); Application.CurrentApplication.Logger.Log("Exiting...", typeof(ICommandAction), LogType.WARNING);
await Config.AppSettings.SaveToFile(); await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile();
Environment.Exit(0); Environment.Exit(0);
} }
else else
@@ -40,7 +40,7 @@ public class Exit: ICommandAction
case "-f": case "-f":
case "force": case "force":
Config.Logger.Log("Exiting (FORCE)...", typeof(ICommandAction), LogType.WARNING); Application.CurrentApplication.Logger.Log("Exiting (FORCE)...", typeof(ICommandAction), LogType.WARNING);
Environment.Exit(0); Environment.Exit(0);
break; break;

View File

@@ -6,11 +6,12 @@ using System.Threading.Tasks;
using DiscordBot.Utilities; using DiscordBot.Utilities;
using PluginManager; using DiscordBotCore;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Loaders; using DiscordBotCore.Loaders;
using PluginManager.Online; using DiscordBotCore.Online;
using PluginManager.Others; using DiscordBotCore.Others;
using DiscordBotCore.Plugin;
using Spectre.Console; using Spectre.Console;
@@ -18,7 +19,7 @@ namespace DiscordBot.Bot.Actions.Extra;
internal static class PluginMethods internal static class PluginMethods
{ {
internal static async Task List(PluginsManager manager) internal static async Task List(PluginManager manager)
{ {
var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetPluginsList(), "Reading remote database"); var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetPluginsList(), "Reading remote database");
@@ -38,11 +39,11 @@ internal static class PluginMethods
internal static async Task RefreshPlugins(bool quiet) internal static async Task RefreshPlugins(bool quiet)
{ {
await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty); await Application.CurrentApplication.InternalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty);
await Program.internalActionManager.Refresh(); await Application.CurrentApplication.InternalActionManager.Refresh();
} }
internal static async Task DownloadPlugin(PluginsManager manager, string pluginName) internal static async Task DownloadPlugin(PluginManager manager, string pluginName)
{ {
var pluginData = await manager.GetPluginDataByName(pluginName); var pluginData = await manager.GetPluginDataByName(pluginName);
if (pluginData is null) if (pluginData is null)
@@ -66,7 +67,7 @@ internal static class PluginMethods
IProgress<float> progress = new Progress<float>(p => { downloadTask.Value = p; }); IProgress<float> progress = new Progress<float>(p => { downloadTask.Value = p; });
await ServerCom.DownloadFileAsync(pluginLink, $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll", progress); await ServerCom.DownloadFileAsync(pluginLink, $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll", progress);
downloadTask.Increment(100); downloadTask.Increment(100);
@@ -76,7 +77,7 @@ internal static class PluginMethods
if (!pluginData.HasDependencies) if (!pluginData.HasDependencies)
{ {
await manager.AppendPluginToDatabase(new PluginManager.Plugin.PluginInfo(pluginName, pluginData.Version, [])); await manager.AppendPluginToDatabase(new PluginInfo(pluginName, pluginData.Version, []));
Console.WriteLine("Finished installing " + pluginName + " successfully"); Console.WriteLine("Finished installing " + pluginName + " successfully");
await RefreshPlugins(false); await RefreshPlugins(false);
return; return;
@@ -108,8 +109,8 @@ internal static class PluginMethods
int maxParallelDownloads = 5; int maxParallelDownloads = 5;
if (Config.AppSettings.ContainsKey("MaxParallelDownloads")) if (Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("MaxParallelDownloads"))
maxParallelDownloads = int.Parse(Config.AppSettings["MaxParallelDownloads"]); maxParallelDownloads = int.Parse(Application.CurrentApplication.ApplicationEnvironmentVariables["MaxParallelDownloads"]);
var options = new ParallelOptions() var options = new ParallelOptions()
{ {
@@ -129,13 +130,13 @@ internal static class PluginMethods
} }
); );
await manager.AppendPluginToDatabase(new PluginManager.Plugin.PluginInfo(pluginName, pluginData.Version, pluginData.Dependencies.Select(sep => sep.DownloadLocation).ToList())); await manager.AppendPluginToDatabase(new PluginInfo(pluginName, pluginData.Version, pluginData.Dependencies.Select(sep => sep.DownloadLocation).ToList()));
await RefreshPlugins(false); await RefreshPlugins(false);
} }
internal static async Task<bool> LoadPlugins(string[] args) internal static async Task<bool> LoadPlugins(string[] args)
{ {
var loader = new PluginLoader(Config.DiscordBot.Client); var loader = new PluginLoader(Application.CurrentApplication.DiscordBotClient.Client);
if (args.Length == 2 && args[1] == "-q") if (args.Length == 2 && args[1] == "-q")
{ {
await loader.LoadPlugins(); await loader.LoadPlugins();
@@ -147,14 +148,14 @@ internal static class PluginMethods
{ {
if (data.IsSuccess) if (data.IsSuccess)
{ {
Config.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction), Application.CurrentApplication.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction),
LogType.INFO LogType.INFO
); );
} }
else else
{ {
Config.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage, Application.CurrentApplication.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR typeof(ICommandAction), LogType.ERROR
); );
} }
@@ -165,13 +166,13 @@ internal static class PluginMethods
{ {
if (data.IsSuccess) if (data.IsSuccess)
{ {
Config.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction), Application.CurrentApplication.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction),
LogType.INFO LogType.INFO
); );
} }
else else
{ {
Config.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage, Application.CurrentApplication.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR typeof(ICommandAction), LogType.ERROR
); );
} }
@@ -183,13 +184,13 @@ internal static class PluginMethods
{ {
if (data.IsSuccess) if (data.IsSuccess)
{ {
Config.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction), Application.CurrentApplication.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction),
LogType.INFO LogType.INFO
); );
} }
else else
{ {
Config.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage, Application.CurrentApplication.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR typeof(ICommandAction), LogType.ERROR
); );
} }

View File

@@ -1,6 +1,5 @@
using System.Linq; using System.Linq;
using PluginManager; using DiscordBotCore;
using PluginManager.Loaders;
namespace DiscordBot.Bot.Actions.Extra; namespace DiscordBot.Bot.Actions.Extra;
@@ -13,21 +12,21 @@ internal static class SettingsConfigExtra
if (value is null) return; if (value is null) return;
if (!Config.AppSettings.ContainsKey(key)) if (!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey(key))
return; return;
Config.AppSettings[key] = string.Join(' ', value); Application.CurrentApplication.ApplicationEnvironmentVariables[key] = string.Join(' ', value);
// Config.AppSettings.SaveToFile().Wait(); // Config.Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile().Wait();
} }
internal static void RemoveSettings(string key) internal static void RemoveSettings(string key)
{ {
if (key is null) return; if (key is null) return;
if (!Config.AppSettings.ContainsKey(key)) if (!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey(key))
return; return;
Config.AppSettings.Remove(key); Application.CurrentApplication.ApplicationEnvironmentVariables.Remove(key);
} }
internal static void AddSettings(string key, params string[] value) internal static void AddSettings(string key, params string[] value)
@@ -36,10 +35,10 @@ internal static class SettingsConfigExtra
if (value is null) return; if (value is null) return;
if (Config.AppSettings.ContainsKey(key)) if (Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey(key))
return; return;
Config.AppSettings.Add(key, string.Join(' ', value)); Application.CurrentApplication.ApplicationEnvironmentVariables.Add(key, string.Join(' ', value));
// Config.AppSettings.SaveToFile().Wait(); // Config.Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile().Wait();
} }
} }

View File

@@ -3,9 +3,11 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBot.Utilities; using DiscordBot.Utilities;
using PluginManager.Interfaces;
using PluginManager.Others; using DiscordBotCore;
using PluginManager.Others.Actions; using DiscordBotCore.Interfaces;
using DiscordBotCore.Others;
using DiscordBotCore.Others.Actions;
using Spectre.Console; using Spectre.Console;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
@@ -30,7 +32,7 @@ public class Help: ICommandAction
tableData.Columns = ["Command", "Usage", "Description", "Options"]; tableData.Columns = ["Command", "Usage", "Description", "Options"];
foreach (var a in Program.internalActionManager.Actions) foreach (var a in Application.CurrentApplication.InternalActionManager.Actions)
{ {
Markup actionName = new Markup($"[bold]{a.Key}[/]"); Markup actionName = new Markup($"[bold]{a.Key}[/]");
Markup usage = new Markup($"[italic]{a.Value.Usage}[/]"); Markup usage = new Markup($"[italic]{a.Value.Usage}[/]");
@@ -68,13 +70,13 @@ public class Help: ICommandAction
return; return;
} }
if (!Program.internalActionManager.Actions.ContainsKey(args[0])) if (!Application.CurrentApplication.InternalActionManager.Actions.ContainsKey(args[0]))
{ {
Console.WriteLine("Command not found"); Console.WriteLine("Command not found");
return; return;
} }
var action = Program.internalActionManager.Actions[args[0]]; var action = Application.CurrentApplication.InternalActionManager.Actions[args[0]];
tableData.Columns = ["Command", "Usage", "Description"]; tableData.Columns = ["Command", "Usage", "Description"];
tableData.AddRow([action.ActionName, action.Usage, action.Description]); tableData.AddRow([action.ActionName, action.Usage, action.Description]);

View File

@@ -2,10 +2,10 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBot.Bot.Actions.Extra; using DiscordBot.Bot.Actions.Extra;
using PluginManager; using DiscordBotCore;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
using PluginManager.Others.Actions; using DiscordBotCore.Others.Actions;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
@@ -50,24 +50,24 @@ public class Plugin: ICommandAction
case "uninstall": case "uninstall":
string plugName = string.Join(' ', args, 1, args.Length-1); string plugName = string.Join(' ', args, 1, args.Length-1);
bool result = await Config.PluginsManager.MarkPluginToUninstall(plugName); bool result = await Application.CurrentApplication.PluginManager.MarkPluginToUninstall(plugName);
if(result) if(result)
Console.WriteLine($"Marked to uninstall plugin {plugName}. Please restart the bot"); Console.WriteLine($"Marked to uninstall plugin {plugName}. Please restart the bot");
break; break;
case "list": case "list":
await PluginMethods.List(Config.PluginsManager); await PluginMethods.List(Application.CurrentApplication.PluginManager);
break; break;
case "load": case "load":
if (pluginsLoaded) if (pluginsLoaded)
{ {
Config.Logger.Log("Plugins already loaded", typeof(ICommandAction), LogType.WARNING); Application.CurrentApplication.Logger.Log("Plugins already loaded", typeof(ICommandAction), LogType.WARNING);
break; break;
} }
if (Config.DiscordBot is null) if (Application.CurrentApplication.DiscordBotClient is null)
{ {
Config.Logger.Log("DiscordBot is null", typeof(ICommandAction), LogType.WARNING); Application.CurrentApplication.Logger.Log("DiscordBot is null", typeof(ICommandAction), LogType.WARNING);
break; break;
} }
@@ -88,7 +88,7 @@ public class Plugin: ICommandAction
} }
} }
await PluginMethods.DownloadPlugin(Config.PluginsManager, pluginName); await PluginMethods.DownloadPlugin(Application.CurrentApplication.PluginManager, pluginName);
break; break;
} }
} }

View File

@@ -2,10 +2,10 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBot.Bot.Actions.Extra; using DiscordBot.Bot.Actions.Extra;
using PluginManager; using DiscordBotCore;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
using PluginManager.Others.Actions; using DiscordBotCore.Others.Actions;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
@@ -26,7 +26,7 @@ public class SettingsConfig: ICommandAction
{ {
if (args is null) if (args is null)
{ {
foreach (var settings in Config.AppSettings) foreach (var settings in Application.CurrentApplication.ApplicationEnvironmentVariables)
Console.WriteLine(settings.Key + ": " + settings.Value); Console.WriteLine(settings.Key + ": " + settings.Value);
return Task.CompletedTask; return Task.CompletedTask;

View File

@@ -1,9 +1,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using Discord; using Discord;
using PluginManager; using DiscordBotCore;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Loaders; using DiscordBotCore.Loaders;
using PluginManager.Others; using DiscordBotCore.Others;
namespace DiscordBot.Bot.Commands; namespace DiscordBot.Bot.Commands;
@@ -79,7 +79,7 @@ internal class Help: DBCommand
); );
if (cmd == null) return null; if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); embedBuilder.AddField("Usage", Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"] + cmd.Usage);
embedBuilder.AddField("Description", cmd.Description); embedBuilder.AddField("Description", cmd.Description);
if (cmd.Aliases is null) if (cmd.Aliases is null)
return embedBuilder; return embedBuilder;

View File

@@ -2,9 +2,9 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Loaders; using DiscordBotCore.Loaders;
using PluginManager.Others; using DiscordBotCore.Others;
namespace DiscordBot.Bot.Commands.SlashCommands; namespace DiscordBot.Bot.Commands.SlashCommands;

View File

@@ -7,15 +7,15 @@
<StartupObject /> <StartupObject />
<SignAssembly>False</SignAssembly> <SignAssembly>False</SignAssembly>
<IsPublishable>True</IsPublishable> <IsPublishable>True</IsPublishable>
<AssemblyVersion>1.0.2.0</AssemblyVersion> <AssemblyVersion>1.0.4.0</AssemblyVersion>
<PublishAot>False</PublishAot> <PublishAot>False</PublishAot>
<FileVersion>1.0.2.0</FileVersion> <FileVersion>1.0.4.0</FileVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType> <DebugType>full</DebugType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType> <DebugType>full</DebugType>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Data\**" /> <Compile Remove="Data\**" />
@@ -38,6 +38,6 @@
<PackageReference Include="Spectre.Console" Version="0.49.1" /> <PackageReference Include="Spectre.Console" Version="0.49.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" /> <ProjectReference Include="..\DiscordBotCore\DiscordBotCore.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,5 +1,5 @@
using System; using System;
using PluginManager; using DiscordBotCore;
using System.Threading.Tasks; using System.Threading.Tasks;
using Spectre.Console; using Spectre.Console;
@@ -18,22 +18,22 @@ public static class Installer
Environment.Exit(-20); Environment.Exit(-20);
} }
Config.AppSettings.Add(key, value); Application.CurrentApplication.ApplicationEnvironmentVariables.Add(key, value);
} }
public static async Task GenerateStartupConfig() public static async Task GenerateStartupConfig()
{ {
if(!Config.AppSettings.ContainsKey("token")) if(!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("token"))
await AskForConfig("token", "Token:"); await AskForConfig("token", "Token:");
if(!Config.AppSettings.ContainsKey("prefix")) if(!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("prefix"))
await AskForConfig("prefix", "Prefix:"); await AskForConfig("prefix", "Prefix:");
if(!Config.AppSettings.ContainsKey("ServerID")) if(!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("ServerID"))
await AskForConfig("ServerID", "Server ID:"); await AskForConfig("ServerID", "Server ID:");
await Config.AppSettings.SaveToFile(); await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile();
Config.Logger.Log("Config Saved", typeof(Installer)); Application.CurrentApplication.Logger.Log("Config Saved", typeof(Installer));
} }
} }

View File

@@ -3,19 +3,19 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBot.Utilities;
using PluginManager.Bot; using DiscordBotCore;
using PluginManager.Others; using DiscordBotCore.Bot;
using PluginManager.Others.Actions; using DiscordBotCore.Others;
using DiscordBotCore.Others.Actions;
using DiscordBotCore.Updater.Application;
using Spectre.Console; using Spectre.Console;
using static PluginManager.Config;
namespace DiscordBot; namespace DiscordBot;
public class Program public class Program
{ {
public static InternalActionManager internalActionManager;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
@@ -23,9 +23,14 @@ public class Program
{ {
PreLoadComponents(args).Wait(); PreLoadComponents(args).Wait();
if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix")) if (!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("ServerID") ||
!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("token") ||
!Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("prefix")
)
Installer.GenerateStartupConfig().Wait(); Installer.GenerateStartupConfig().Wait();
HandleInput().Wait(); HandleInput().Wait();
} }
@@ -34,9 +39,7 @@ public class Program
/// </summary> /// </summary>
private static void NoGUI() private static void NoGUI()
{ {
internalActionManager.Initialize().Wait(); Application.CurrentApplication.InternalActionManager.Execute("plugin", "load").Wait();
internalActionManager.Execute("plugin", "load").Wait();
internalActionManager.Refresh().Wait();
while (true) while (true)
{ {
@@ -47,7 +50,7 @@ public class Program
if (args.Length == 0) if (args.Length == 0)
args = null; args = null;
internalActionManager.Execute(command, args).Wait(); // Execute the command Application.CurrentApplication.InternalActionManager.Execute(command, args).Wait();
} }
} }
@@ -58,7 +61,7 @@ public class Program
private static async Task StartNoGui() private static async Task StartNoGui()
{ {
AnsiConsole.MarkupLine($"[yellow]Running on version: {AppSettings["Version"]}[/]"); AnsiConsole.MarkupLine($"[yellow]Running on version: {Application.CurrentApplication.ApplicationEnvironmentVariables["Version"]}[/]");
AnsiConsole.MarkupLine("[yellow]Git SethBot: https://github.com/andreitdr/SethDiscordBot [/]"); AnsiConsole.MarkupLine("[yellow]Git SethBot: https://github.com/andreitdr/SethDiscordBot [/]");
AnsiConsole.MarkupLine("[yellow]Git Plugins: https://github.com/andreitdr/SethPlugins [/]"); AnsiConsole.MarkupLine("[yellow]Git Plugins: https://github.com/andreitdr/SethPlugins [/]");
@@ -69,14 +72,14 @@ public class Program
try try
{ {
var token = AppSettings["token"]; var token = Application.CurrentApplication.ApplicationEnvironmentVariables["token"];
var prefix = AppSettings["prefix"]; var prefix = Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"];
var discordbooter = new Boot(token, prefix); var discordbooter = new Boot(token, prefix);
await discordbooter.Awake(); await discordbooter.Awake();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Log(ex.ToString(), typeof(Program), LogType.CRITICAL); Application.CurrentApplication.Logger.Log(ex.ToString(), typeof(Program), LogType.CRITICAL);
} }
} }
@@ -88,14 +91,13 @@ public class Program
await StartNoGui(); await StartNoGui();
try try
{ {
internalActionManager = new InternalActionManager(AppSettings["PluginFolder"], "*.dll");
NoGUI(); NoGUI();
} }
catch (IOException ex) catch (IOException ex)
{ {
if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{ {
Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" + Application.CurrentApplication.Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", "There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !",
typeof(Program), LogType.ERROR typeof(Program), LogType.ERROR
); );
@@ -105,14 +107,14 @@ public class Program
private static async Task PreLoadComponents(string[] args) private static async Task PreLoadComponents(string[] args)
{ {
await Initialize(); await Application.CreateApplication();
AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); Application.CurrentApplication.ApplicationEnvironmentVariables["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
PluginManager.Updater.Application.AppUpdater updater = new(); AppUpdater updater = new();
var update = await updater.CheckForUpdates(); var update = await updater.CheckForUpdates();
if (update != PluginManager.Updater.Application.Update.None) if (update != Update.None)
{ {
Console.WriteLine($"New update available: {update.UpdateVersion}"); Console.WriteLine($"New update available: {update.UpdateVersion}");
Console.WriteLine($"Download link: {update.UpdateUrl}"); Console.WriteLine($"Download link: {update.UpdateUrl}");
@@ -122,15 +124,16 @@ public class Program
await Task.Delay(5000); await Task.Delay(5000);
} }
Logger.OnLog += (sender, logMessage) => Application.CurrentApplication.Logger.OnFormattedLog += async (sender, logMessage) =>
{ {
await File.AppendAllTextAsync(Application.CurrentApplication.LogFile, logMessage.Message + "\n");
var messageColor = logMessage.Type switch var messageColor = logMessage.Type switch
{ {
LogType.INFO => "[green]", LogType.INFO => "[green]",
LogType.WARNING => "[yellow]", LogType.WARNING => "[yellow]",
LogType.ERROR => "[red]", LogType.ERROR => "[red]",
LogType.CRITICAL => "[red]", LogType.CRITICAL => "[red]",
_ => "[white]" _ => "[white]"
}; };
if (logMessage.Message.Contains('[')) if (logMessage.Message.Contains('['))
@@ -139,7 +142,8 @@ public class Program
return; return;
} }
AnsiConsole.MarkupLine($"{messageColor}{logMessage.ThrowTime} {logMessage.Message} [/]"); string messageToPrint = $"{messageColor}{logMessage.Message}[/]";
AnsiConsole.MarkupLine(messageToPrint);
}; };
} }
} }

View File

@@ -4,7 +4,7 @@ using System.Linq;
using System.Runtime.InteropServices.ComTypes; using System.Runtime.InteropServices.ComTypes;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others; using DiscordBotCore.Others;
using Spectre.Console; using Spectre.Console;
using Spectre.Console.Rendering; using Spectre.Console.Rendering;

View File

@@ -0,0 +1,99 @@
using DiscordBotCore.Online;
using DiscordBotCore.Others;
using DiscordBotCore.Others.Actions;
using DiscordBotCore.Others.Logger;
using DiscordBotCore.Plugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace DiscordBotCore
{
public class Application
{
public static Application CurrentApplication { get; private set; } = null;
private static readonly string _DefaultLogMessageFormat = "{SenderName} {Message}";
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 readonly string _MaxParallelDownloads = "3";
public string ServerID => ApplicationEnvironmentVariables["ServerID"];
public string PluginDatabase => ApplicationEnvironmentVariables["PluginDatabase"];
public string LogFile => $"{ApplicationEnvironmentVariables["LogFolder"]}/{DateTime.Now.ToLongDateString().Replace(" / ", "")}.log";
public SettingsDictionary<string, string> ApplicationEnvironmentVariables { get; private set; }
public InternalActionManager InternalActionManager { get; private set; }
public PluginManager PluginManager { get; private set; }
public Logger Logger { get; private set; }
public Bot.Boot DiscordBotClient { get; internal set; }
public static async Task CreateApplication()
{
if (CurrentApplication is not null)
return;
CurrentApplication = new Application();
Directory.CreateDirectory(_ResourcesFolder);
Directory.CreateDirectory(_PluginsFolder);
Directory.CreateDirectory(_ArchivesFolder);
Directory.CreateDirectory(_LogsFolder);
CurrentApplication.ApplicationEnvironmentVariables = new SettingsDictionary<string, string>(_ConfigFile);
bool result = await CurrentApplication.ApplicationEnvironmentVariables.LoadFromFile();
if(!result)
{
PopulateEnvWithDefault();
File.Delete(_ConfigFile);
await CurrentApplication.ApplicationEnvironmentVariables.SaveToFile();
}
CurrentApplication.Logger = CurrentApplication.ApplicationEnvironmentVariables.ContainsKey("LogMessageFormat") ?
new Logger(CurrentApplication.ApplicationEnvironmentVariables["LogMessageFormat"]) :
new Logger(_DefaultLogMessageFormat);
if (!File.Exists(_PluginsDatabaseFile))
{
List<PluginInfo> plugins = new();
await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins);
}
CurrentApplication.PluginManager = new PluginManager();
await CurrentApplication.PluginManager.UninstallMarkedPlugins();
await CurrentApplication.PluginManager.CheckForUpdates();
CurrentApplication.InternalActionManager = new InternalActionManager(CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"], "*.dll");
await CurrentApplication.InternalActionManager.Initialize();
}
private static void PopulateEnvWithDefault()
{
if (CurrentApplication is null)
return;
if (CurrentApplication.ApplicationEnvironmentVariables is null)
return;
CurrentApplication.ApplicationEnvironmentVariables["LogFolder"] = _LogsFolder;
CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"] = _PluginsFolder;
CurrentApplication.ApplicationEnvironmentVariables["ArchiveFolder"] = _ArchivesFolder;
CurrentApplication.ApplicationEnvironmentVariables["PluginDatabase"] = _PluginsDatabaseFile;
CurrentApplication.ApplicationEnvironmentVariables["LogMessageFormat"] = _DefaultLogMessageFormat;
CurrentApplication.ApplicationEnvironmentVariables["MaxParallelDownloads"] = _MaxParallelDownloads;
}
}
}

View File

@@ -3,10 +3,10 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Bot; namespace DiscordBotCore.Bot;
public class Boot public class Boot
{ {
@@ -86,7 +86,7 @@ public class Boot
await _commandServiceHandler.InstallCommandsAsync(); await _commandServiceHandler.InstallCommandsAsync();
Config.DiscordBotClient = this; Application.CurrentApplication.DiscordBotClient = this;
while (!IsReady) ; while (!IsReady) ;
} }
@@ -106,16 +106,16 @@ public class Boot
{ {
if (arg.Message.Contains("401")) if (arg.Message.Contains("401"))
{ {
Config.AppSettings.Remove("token"); Application.CurrentApplication.ApplicationEnvironmentVariables.Remove("token");
Config.Logger.Log("The token is invalid. Please restart the bot and follow the instructions", typeof(Boot), LogType.CRITICAL); Application.CurrentApplication.Logger.Log("The token is invalid. Please restart the bot and follow the instructions", typeof(Boot), LogType.CRITICAL);
await Config.AppSettings.SaveToFile(); await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile();
Environment.Exit(0); Environment.Exit(0);
} }
} }
private async Task Client_LoggedOut() private async Task Client_LoggedOut()
{ {
Config.Logger.Log("Successfully Logged Out", typeof(Boot)); Application.CurrentApplication.Logger.Log("Successfully Logged Out", typeof(Boot));
await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
} }
@@ -127,7 +127,7 @@ public class Boot
private Task LoggedIn() private Task LoggedIn()
{ {
Config.Logger.Log("Successfully Logged In", typeof(Boot)); Application.CurrentApplication.Logger.Log("Successfully Logged In", typeof(Boot));
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -137,12 +137,12 @@ public class Boot
{ {
case LogSeverity.Error: case LogSeverity.Error:
case LogSeverity.Critical: case LogSeverity.Critical:
Config.Logger.Log(message.Message, typeof(Boot), LogType.ERROR); Application.CurrentApplication.Logger.Log(message.Message, typeof(Boot), LogType.ERROR);
break; break;
case LogSeverity.Info: case LogSeverity.Info:
case LogSeverity.Debug: case LogSeverity.Debug:
Config.Logger.Log(message.Message, typeof(Boot), LogType.INFO); Application.CurrentApplication.Logger.Log(message.Message, typeof(Boot), LogType.INFO);
break; break;

View File

@@ -4,13 +4,12 @@ using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Loaders; using DiscordBotCore.Loaders;
using PluginManager.Online; using DiscordBotCore.Others;
using PluginManager.Others; using DiscordBotCore.Others.Permissions;
using PluginManager.Others.Permissions;
namespace PluginManager.Bot; namespace DiscordBotCore.Bot;
internal class CommandHandler internal class CommandHandler
{ {
@@ -57,7 +56,7 @@ internal class CommandHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, type: LogType.ERROR, source: typeof(CommandHandler)); Application.CurrentApplication.Logger.LogException(ex, this);
} }
return Task.CompletedTask; return Task.CompletedTask;
@@ -141,7 +140,7 @@ internal class CommandHandler
DbCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean); DbCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean);
Config.Logger.Log( Application.CurrentApplication.Logger.Log(
$"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"", $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"",
typeof(CommandHandler), typeof(CommandHandler),
LogType.INFO LogType.INFO
@@ -153,7 +152,7 @@ internal class CommandHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, type: LogType.ERROR, source: typeof(CommandHandler)); Application.CurrentApplication.Logger.LogException(ex, this);
} }
} }
} }

View File

@@ -5,7 +5,7 @@ using System.Data.SQLite;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace PluginManager.Database; namespace DiscordBotCore.Database;
public class SqlDatabase public class SqlDatabase
{ {

View File

@@ -5,9 +5,12 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<DebugType>none</DebugType> <DebugType>portable</DebugType>
<DebugSymbols>false</DebugSymbols> <DebugSymbols>false</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Config.cs" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="BlankWindow1.xaml" /> <None Remove="BlankWindow1.xaml" />
</ItemGroup> </ItemGroup>

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Interfaces; namespace DiscordBotCore.Interfaces;
public interface DBCommand public interface DBCommand
{ {

View File

@@ -1,6 +1,6 @@
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Interfaces; namespace DiscordBotCore.Interfaces;
public interface DBEvent public interface DBEvent
{ {

View File

@@ -4,7 +4,7 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Interfaces; namespace DiscordBotCore.Interfaces;
public interface DBSlashCommand public interface DBSlashCommand
{ {

View File

@@ -1,10 +1,10 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others; using DiscordBotCore.Others;
using PluginManager.Others.Actions; using DiscordBotCore.Others.Actions;
namespace PluginManager.Interfaces; namespace DiscordBotCore.Interfaces;
public interface ICommandAction public interface ICommandAction
{ {

View File

@@ -0,0 +1,15 @@
using DiscordBotCore.Others;
using System;
namespace DiscordBotCore.Interfaces.Logger
{
public interface ILogMessage
{
public string Message { get; protected set; }
public DateTime ThrowTime { get; protected set; }
public string SenderName { get; protected set; }
public LogType LogMessageType { get; protected set; }
}
}

View File

@@ -0,0 +1,19 @@
using DiscordBotCore.Others;
using System;
using System.Collections.Generic;
namespace DiscordBotCore.Interfaces.Logger
{
public interface ILogger
{
public struct FormattedMessage { public string Message; public LogType Type; }
public string LogMessageFormat { get; set; }
public void Log(ILogMessage message);
public void LogException(Exception exception, object Sender);
public event EventHandler<FormattedMessage> OnFormattedLog;
public event EventHandler<ILogMessage> OnRawLog;
}
}

View File

@@ -1,10 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Interfaces.Updater namespace DiscordBotCore.Interfaces.Updater
{ {
public class AppVersion : IVersion public class AppVersion : IVersion
{ {
@@ -16,7 +12,7 @@ namespace PluginManager.Interfaces.Updater
public int PatchVersion { get; set; } public int PatchVersion { get; set; }
public static readonly AppVersion CurrentAppVersion = new AppVersion(Config.AppSettings["Version"]); public static readonly AppVersion CurrentAppVersion = new AppVersion(Application.CurrentApplication.ApplicationEnvironmentVariables["Version"]);
private readonly char _Separator = '.'; private readonly char _Separator = '.';

View File

@@ -1,4 +1,4 @@
namespace PluginManager.Interfaces.Updater; namespace DiscordBotCore.Interfaces.Updater;
public interface IVersion public interface IVersion
{ {

View File

@@ -1,6 +1,6 @@
using System; using System;
namespace PluginManager.Interfaces.Updater; namespace DiscordBotCore.Interfaces.Updater;
public abstract class Version: IVersion public abstract class Version: IVersion
{ {

View File

@@ -4,10 +4,10 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Loaders; namespace DiscordBotCore.Loaders;
public class ActionsLoader public class ActionsLoader
{ {

View File

@@ -1,4 +1,4 @@
namespace PluginManager.Loaders; namespace DiscordBotCore.Loaders;
public class FileLoaderResult public class FileLoaderResult
{ {

View File

@@ -3,10 +3,10 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Loaders; namespace DiscordBotCore.Loaders;
internal class Loader internal class Loader
{ {

View File

@@ -1,6 +1,6 @@
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Loaders; namespace DiscordBotCore.Loaders;
public class PluginLoadResultData public class PluginLoadResultData
{ {

View File

@@ -1,11 +1,11 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Loaders; namespace DiscordBotCore.Loaders;
public class PluginLoader public class PluginLoader
{ {
@@ -32,9 +32,9 @@ public class PluginLoader
public async Task LoadPlugins() public async Task LoadPlugins()
{ {
Config.Logger.Log("Loading plugins...", typeof(PluginLoader)); Application.CurrentApplication.Logger.Log("Loading plugins...", typeof(PluginLoader));
var loader = new Loader(Config.AppSettings["PluginFolder"], "dll"); var loader = new Loader(Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"], "dll");
//await this.ResetSlashCommands(); //await this.ResetSlashCommands();
@@ -46,7 +46,7 @@ public class PluginLoader
private void FileLoadedException(FileLoaderResult result) private void FileLoadedException(FileLoaderResult result)
{ {
Config.Logger.Log(result.ErrorMessage, typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log(result.ErrorMessage, typeof(PluginLoader), LogType.ERROR);
} }
private async void OnPluginLoaded(PluginLoadResultData result) private async void OnPluginLoaded(PluginLoadResultData result)
@@ -74,11 +74,11 @@ public class PluginLoader
OnSlashCommandLoaded?.Invoke(result); OnSlashCommandLoaded?.Invoke(result);
} }
else else
Config.Logger.Log($"Failed to start slash command {result.PluginName}", typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log($"Failed to start slash command {result.PluginName}", typeof(PluginLoader), LogType.ERROR);
break; break;
case PluginType.UNKNOWN: case PluginType.UNKNOWN:
default: default:
Config.Logger.Log("Unknown plugin type", typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log("Unknown plugin type", typeof(PluginLoader), LogType.ERROR);
break; break;
} }
} }

View File

@@ -5,10 +5,10 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Loaders; namespace DiscordBotCore.Loaders;
internal static class PluginLoaderExtensions internal static class PluginLoaderExtensions
{ {
@@ -27,7 +27,7 @@ internal static class PluginLoaderExtensions
} }
catch (Exception e) catch (Exception e)
{ {
Config.Logger.Log($"Error starting event {dbEvent.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log($"Error starting event {dbEvent.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR);
return false; return false;
} }
} }
@@ -37,22 +37,22 @@ internal static class PluginLoaderExtensions
await pluginLoader._Client.Rest.DeleteAllGlobalCommandsAsync(); await pluginLoader._Client.Rest.DeleteAllGlobalCommandsAsync();
if(pluginLoader._Client.Guilds.Count == 0) return; if(pluginLoader._Client.Guilds.Count == 0) return;
if (!ulong.TryParse(Config.ServerID, out _)) if (!ulong.TryParse(Application.CurrentApplication.ServerID, out _))
{ {
Config.Logger.Log("Invalid ServerID in config file. Can not reset specific guild commands", typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log("Invalid ServerID in config file. Can not reset specific guild commands", typeof(PluginLoader), LogType.ERROR);
return; return;
} }
SocketGuild? guild = pluginLoader._Client.GetGuild(ulong.Parse(Config.ServerID)); SocketGuild? guild = pluginLoader._Client.GetGuild(ulong.Parse(Application.CurrentApplication.ServerID));
if(guild is null) if(guild is null)
{ {
Config.Logger.Log("Failed to get guild with ID " + Config.ServerID, typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log("Failed to get guild with ID " + Application.CurrentApplication.ServerID, typeof(PluginLoader), LogType.ERROR);
return; return;
} }
await guild.DeleteApplicationCommandsAsync(); await guild.DeleteApplicationCommandsAsync();
Config.Logger.Log($"Cleared all slash commands from guild {guild.Id}", typeof(PluginLoader)); Application.CurrentApplication.Logger.Log($"Cleared all slash commands from guild {guild.Id}", typeof(PluginLoader));
} }
internal static async Task<bool> TryStartSlashCommand(this PluginLoader pluginLoader, DBSlashCommand? dbSlashCommand) internal static async Task<bool> TryStartSlashCommand(this PluginLoader pluginLoader, DBSlashCommand? dbSlashCommand)
@@ -74,12 +74,12 @@ internal static class PluginLoaderExtensions
builder.WithDMPermission(dbSlashCommand.canUseDM); builder.WithDMPermission(dbSlashCommand.canUseDM);
builder.Options = dbSlashCommand.Options; builder.Options = dbSlashCommand.Options;
if (uint.TryParse(Config.ServerID, out uint result)) if (uint.TryParse(Application.CurrentApplication.ServerID, out uint result))
{ {
SocketGuild? guild = pluginLoader._Client.GetGuild(result); SocketGuild? guild = pluginLoader._Client.GetGuild(result);
if (guild is null) if (guild is null)
{ {
Config.Logger.Log("Failed to get guild with ID " + Config.ServerID, typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log("Failed to get guild with ID " + Application.CurrentApplication.ServerID, typeof(PluginLoader), LogType.ERROR);
return false; return false;
} }
@@ -90,7 +90,7 @@ internal static class PluginLoaderExtensions
} }
catch (Exception e) catch (Exception e)
{ {
Config.Logger.Log($"Error starting slash command {dbSlashCommand.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR); Application.CurrentApplication.Logger.Log($"Error starting slash command {dbSlashCommand.Name}: {e.Message}", typeof(PluginLoader), LogType.ERROR);
return false; return false;
} }
} }

View File

@@ -3,9 +3,9 @@ using System.IO;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Online.Helpers; namespace DiscordBotCore.Online.Helpers;
internal static class OnlineFunctions internal static class OnlineFunctions
{ {

View File

@@ -1,7 +1,7 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using PluginManager.Interfaces.Updater; using DiscordBotCore.Interfaces.Updater;
namespace PluginManager.Online.Helpers; namespace DiscordBotCore.Online.Helpers;
public class PluginVersion: Version public class PluginVersion: Version
{ {

View File

@@ -3,13 +3,13 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others; using DiscordBotCore.Others;
using PluginManager.Plugin; using DiscordBotCore.Plugin;
using PluginManager.Updater.Plugins; using DiscordBotCore.Updater.Plugins;
namespace PluginManager.Online; namespace DiscordBotCore.Online;
public class PluginsManager public class PluginManager
{ {
private static readonly string _DefaultBranch = "releases"; private static readonly string _DefaultBranch = "releases";
private static readonly string _DefaultBaseUrl = "https://raw.githubusercontent.com/andreitdr/SethPlugins"; private static readonly string _DefaultBaseUrl = "https://raw.githubusercontent.com/andreitdr/SethPlugins";
@@ -23,19 +23,19 @@ public class PluginsManager
private string PluginsLink => $"{BaseUrl}/{Branch}/{_DefaultPluginsLink}"; private string PluginsLink => $"{BaseUrl}/{Branch}/{_DefaultPluginsLink}";
public PluginsManager(Uri baseUrl, string branch) public PluginManager(Uri baseUrl, string branch)
{ {
BaseUrl = baseUrl.ToString(); BaseUrl = baseUrl.ToString();
Branch = branch; Branch = branch;
} }
public PluginsManager(string branch) public PluginManager(string branch)
{ {
BaseUrl = _DefaultBaseUrl; BaseUrl = _DefaultBaseUrl;
Branch = branch; Branch = branch;
} }
public PluginsManager() public PluginManager()
{ {
BaseUrl = _DefaultBaseUrl; BaseUrl = _DefaultBaseUrl;
Branch = _DefaultBranch; Branch = _DefaultBranch;
@@ -65,28 +65,28 @@ public class PluginsManager
public async Task RemovePluginFromDatabase(string pluginName) public async Task RemovePluginFromDatabase(string pluginName)
{ {
List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Config.PluginDatabase)); List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase));
installedPlugins.RemoveAll(p => p.PluginName == pluginName); installedPlugins.RemoveAll(p => p.PluginName == pluginName);
await JsonManager.SaveToJsonFile( Config.PluginDatabase,installedPlugins); await JsonManager.SaveToJsonFile(Application.CurrentApplication.PluginDatabase,installedPlugins);
} }
public async Task AppendPluginToDatabase(PluginInfo pluginData) public async Task AppendPluginToDatabase(PluginInfo pluginData)
{ {
List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Config.PluginDatabase)); List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase));
installedPlugins.Add(pluginData); installedPlugins.Add(pluginData);
await JsonManager.SaveToJsonFile( Config.PluginDatabase, installedPlugins); await JsonManager.SaveToJsonFile(Application.CurrentApplication.PluginDatabase, installedPlugins);
} }
public async Task<List<PluginInfo>> GetInstalledPlugins() public async Task<List<PluginInfo>> GetInstalledPlugins()
{ {
return await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Config.PluginDatabase)); return await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase));
} }
public async Task<bool> IsPluginInstalled(string pluginName) public async Task<bool> IsPluginInstalled(string pluginName)
{ {
List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Config.PluginDatabase)); List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(await File.ReadAllTextAsync(Application.CurrentApplication.PluginDatabase));
return installedPlugins.Any(plugin => plugin.PluginName == pluginName); return installedPlugins.Any(plugin => plugin.PluginName == pluginName);
} }
@@ -101,7 +101,7 @@ public class PluginsManager
{ {
if (await pluginUpdater.HasUpdate(plugin.PluginName)) if (await pluginUpdater.HasUpdate(plugin.PluginName))
{ {
Config.Logger.Log("Updating plugin: " + plugin.PluginName, typeof(PluginsManager), LogType.INFO); Application.CurrentApplication.Logger.Log("Updating plugin: " + plugin.PluginName, typeof(PluginManager), LogType.INFO);
await pluginUpdater.UpdatePlugin(plugin.PluginName); await pluginUpdater.UpdatePlugin(plugin.PluginName);
} }
} }
@@ -158,7 +158,7 @@ public class PluginsManager
installProgress?.Report(currentProgress + stepProgress * p); installProgress?.Report(currentProgress + stepProgress * p);
}); });
await ServerCom.DownloadFileAsync(pluginData.DownLoadLink, $"{Config.AppSettings["PluginFolder"]}/{pluginData.Name}.dll", progress); await ServerCom.DownloadFileAsync(pluginData.DownLoadLink, $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginData.Name}.dll", progress);
foreach (var dependency in pluginData.Dependencies) foreach (var dependency in pluginData.Dependencies)
{ {

View File

@@ -4,9 +4,9 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Online.Helpers; using DiscordBotCore.Online.Helpers;
namespace PluginManager.Online; namespace DiscordBotCore.Online;
public static class ServerCom public static class ServerCom
{ {

View File

@@ -1,10 +1,4 @@
using System; namespace DiscordBotCore.Others.Actions
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others.Actions
{ {
public class InternalActionOption public class InternalActionOption
{ {

View File

@@ -1,10 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Interfaces; using DiscordBotCore.Interfaces;
using PluginManager.Loaders; using DiscordBotCore.Loaders;
namespace PluginManager.Others.Actions; namespace DiscordBotCore.Others.Actions;
public class InternalActionManager public class InternalActionManager
{ {
@@ -36,7 +36,7 @@ public class InternalActionManager
{ {
if (!Actions.ContainsKey(actionName)) if (!Actions.ContainsKey(actionName))
{ {
Config.Logger.Log($"Action {actionName} not found", type: LogType.ERROR, source: typeof(InternalActionManager)); Application.CurrentApplication.Logger.Log($"Action {actionName} not found", this, LogType.ERROR);
return false; return false;
} }
@@ -47,7 +47,7 @@ public class InternalActionManager
} }
catch (Exception e) catch (Exception e)
{ {
Config.Logger.Log(e.Message, type: LogType.ERROR, source: typeof(InternalActionManager)); Application.CurrentApplication.Logger.Log(e.Message, type: LogType.ERROR, Sender: this);
return false; return false;
} }
} }

View File

@@ -4,7 +4,7 @@ using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace PluginManager.Others; namespace DiscordBotCore.Others;
public static class ArchiveManager public static class ArchiveManager
{ {
@@ -33,7 +33,7 @@ public static class ArchiveManager
public static async Task<byte[]?> ReadStreamFromPakAsync(string fileName, string archName) public static async Task<byte[]?> ReadStreamFromPakAsync(string fileName, string archName)
{ {
archName = Config.AppSettings["ArchiveFolder"] + archName; archName = Application.CurrentApplication.ApplicationEnvironmentVariables["ArchiveFolder"] + archName;
if (!File.Exists(archName)) if (!File.Exists(archName))
throw new Exception("Failed to load file !"); throw new Exception("Failed to load file !");
@@ -61,7 +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> /// <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) public static async Task<string?> ReadFromPakAsync(string fileName, string archFile)
{ {
archFile = Config.AppSettings["ArchiveFolder"] + archFile; archFile = Application.CurrentApplication.ApplicationEnvironmentVariables["ArchiveFolder"] + archFile;
if (!File.Exists(archFile)) if (!File.Exists(archFile))
throw new Exception("Failed to load file !"); throw new Exception("Failed to load file !");
@@ -87,7 +87,7 @@ public static class ArchiveManager
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); // Write the error to a file Application.CurrentApplication.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.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);
} }
@@ -123,7 +123,7 @@ public static class ArchiveManager
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); Application.CurrentApplication.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR);
} }
currentZipFile++; currentZipFile++;
@@ -155,7 +155,7 @@ public static class ArchiveManager
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR); Application.CurrentApplication.Logger.Log(ex.Message, typeof(ArchiveManager), LogType.ERROR);
} }
await Task.Delay(10); await Task.Delay(10);

View File

@@ -2,7 +2,7 @@
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Others; namespace DiscordBotCore.Others;
public class DbCommandExecutingArguments public class DbCommandExecutingArguments
{ {
@@ -33,7 +33,7 @@ public class DbCommandExecutingArguments
} }
else else
{ {
cleanContent = message.Content.Substring(Config.DiscordBot.BotPrefix.Length); cleanContent = message.Content.Substring(Application.CurrentApplication.DiscordBotClient.BotPrefix.Length);
} }
var split = cleanContent.Split(' '); var split = cleanContent.Split(' ');

View File

@@ -1,6 +1,6 @@
using System; using System;
namespace PluginManager.Others; namespace DiscordBotCore.Others;
/// <summary> /// <summary>
/// The output log type /// The output log type

View File

@@ -1,13 +1,10 @@
using System; using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
namespace PluginManager.Others; namespace DiscordBotCore.Others;
/// <summary> /// <summary>
/// A special class with functions /// A special class with functions

View File

@@ -4,7 +4,7 @@ using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace PluginManager; namespace DiscordBotCore.Others;
public class JsonManager public class JsonManager
{ {

View File

@@ -0,0 +1,71 @@
using DiscordBotCore.Interfaces.Logger;
using System;
namespace DiscordBotCore.Others.Logger
{
internal sealed class LogMessage : ILogMessage
{
public string Message { get; set; }
public DateTime ThrowTime { get; set; }
public string SenderName { get; set; }
public LogType LogMessageType { get; set; }
public LogMessage(string message, object sender)
{
Message = message;
SenderName = sender.GetType().FullName ?? sender.GetType().Name;
ThrowTime = DateTime.Now;
LogMessageType = LogType.INFO;
}
public LogMessage(string message, object sender, DateTime throwTime)
{
Message = message;
SenderName = sender.GetType().FullName ?? sender.GetType().Name;
ThrowTime = throwTime;
LogMessageType = LogType.INFO;
}
public LogMessage(string message, object sender, LogType logMessageType)
{
Message = message;
SenderName = sender.GetType().FullName ?? sender.GetType().Name;
ThrowTime = DateTime.Now;
LogMessageType = logMessageType;
}
public LogMessage(string message, DateTime throwTime, object sender, LogType logMessageType)
{
Message = message;
ThrowTime = throwTime;
SenderName = sender.GetType().FullName ?? sender.GetType().Name;
LogMessageType = logMessageType;
}
public LogMessage WithMessage(string message)
{
this.Message = message;
return this;
}
public LogMessage WithCurrentThrowTime()
{
this.ThrowTime = DateTime.Now;
return this;
}
public LogMessage WithMessageType(LogType logType)
{
this.LogMessageType = logType;
return this;
}
public static LogMessage CreateFromException(Exception exception, object Sender)
{
LogMessage message = new LogMessage(exception.Message, Sender, LogType.ERROR);
return message;
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using DiscordBotCore.Interfaces.Logger;
namespace DiscordBotCore.Others.Logger;
public sealed class Logger : ILogger
{
public List<string> LogMessageProperties = typeof(ILogMessage).GetProperties().Select(p => p.Name).ToList();
public string LogMessageFormat { get ; set; }
public event EventHandler<ILogger.FormattedMessage> OnFormattedLog;
public event EventHandler<ILogMessage> OnRawLog;
public Logger(string logMessageFormat)
{
this.LogMessageFormat = logMessageFormat;
}
/// <summary>
/// Generate a formatted string based on the default parameters of the ILogMessage and a string defined as model
/// </summary>
/// <param name="message">The message</param>
/// <returns>A formatted string with the message values</returns>
private string GenerateLogMessage(ILogMessage message)
{
string messageAsString = new string(LogMessageFormat);
foreach (var prop in LogMessageProperties)
{
Type messageType = typeof(ILogMessage);
messageAsString = messageAsString.Replace("{" + prop + "}", messageType?.GetProperty(prop)?.GetValue(message)?.ToString());
}
return messageAsString;
}
public void Log(ILogMessage message)
{
OnRawLog?.Invoke(this, message);
string messageAsString = GenerateLogMessage(message);
OnFormattedLog?.Invoke(this, new ILogger.FormattedMessage() { Message = messageAsString, Type = message.LogMessageType }) ;
}
public void Log(string message, object Sender) => Log(new LogMessage(message, Sender));
public void Log(string message, object Sender, LogType type) => Log(new LogMessage(message, Sender, type));
public void LogException(Exception exception, object Sender) => Log(LogMessage.CreateFromException(exception, Sender));
}

View File

@@ -1,10 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others namespace DiscordBotCore.Others
{ {
public class OneOf<T0, T1> public class OneOf<T0, T1>
{ {

View File

@@ -2,7 +2,7 @@
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Others.Permissions; namespace DiscordBotCore.Others.Permissions;
/// <summary> /// <summary>
/// A class whith all discord permissions /// A class whith all discord permissions

View File

@@ -1,10 +1,9 @@
using System.Collections; using System.Collections.Generic;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace PluginManager.Others; namespace DiscordBotCore.Others;
public class SettingsDictionary<TKey, TValue> public class SettingsDictionary<TKey, TValue>
{ {
@@ -36,14 +35,14 @@ public class SettingsDictionary<TKey, TValue>
if(!File.Exists(_File)) if(!File.Exists(_File))
{ {
_Dictionary = new Dictionary<TKey, TValue>(); _Dictionary = new Dictionary<TKey, TValue>();
return true; return false;
} }
string fileAsText = await File.ReadAllTextAsync(_File); string fileAsText = await File.ReadAllTextAsync(_File);
if(string.IsNullOrEmpty(fileAsText) || string.IsNullOrWhiteSpace(fileAsText)) if(string.IsNullOrEmpty(fileAsText) || string.IsNullOrWhiteSpace(fileAsText))
{ {
_Dictionary = new Dictionary<TKey, TValue>(); _Dictionary = new Dictionary<TKey, TValue>();
return true; return false;
} }
_Dictionary = await JsonManager.ConvertFromJson<IDictionary<TKey,TValue>>(fileAsText); _Dictionary = await JsonManager.ConvertFromJson<IDictionary<TKey,TValue>>(fileAsText);
@@ -76,7 +75,7 @@ public class SettingsDictionary<TKey, TValue>
get get
{ {
if(!_Dictionary.ContainsKey(key)) if(!_Dictionary.ContainsKey(key))
throw new System.Exception($"The key {key} ({typeof(TKey)}) was not present in the dictionary"); throw new System.Exception($"The key {key} ({typeof(TKey)}) (file: {this._File}) was not present in the dictionary");
if(_Dictionary[key] is not TValue) if(_Dictionary[key] is not TValue)
throw new System.Exception("The dictionary is corrupted. This error is critical !"); throw new System.Exception("The dictionary is corrupted. This error is critical !");

View File

@@ -1,4 +1,4 @@
namespace PluginManager.Plugin; namespace DiscordBotCore.Plugin;
public class OnlineDependencyInfo public class OnlineDependencyInfo
{ {

View File

@@ -1,9 +1,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using PluginManager.Online.Helpers; using DiscordBotCore.Online.Helpers;
namespace PluginManager.Plugin; namespace DiscordBotCore.Plugin;
public class PluginInfo public class PluginInfo
{ {
@@ -20,7 +20,7 @@ public class PluginInfo
PluginVersion = pluginVersion; PluginVersion = pluginVersion;
ListOfDependancies = listOfDependancies; ListOfDependancies = listOfDependancies;
IsMarkedToUninstall = isMarkedToUninstall; IsMarkedToUninstall = isMarkedToUninstall;
FilePath = $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll"; FilePath = $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll";
} }
public PluginInfo(string pluginName, PluginVersion pluginVersion, List<string> listOfDependancies) public PluginInfo(string pluginName, PluginVersion pluginVersion, List<string> listOfDependancies)
@@ -29,7 +29,7 @@ public class PluginInfo
PluginVersion = pluginVersion; PluginVersion = pluginVersion;
ListOfDependancies = listOfDependancies; ListOfDependancies = listOfDependancies;
IsMarkedToUninstall = false; IsMarkedToUninstall = false;
FilePath = $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll"; FilePath = $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll";
} }
public static PluginInfo FromOnlineInfo(PluginOnlineInfo onlineInfo) public static PluginInfo FromOnlineInfo(PluginOnlineInfo onlineInfo)

View File

@@ -1,10 +1,10 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Online.Helpers; using DiscordBotCore.Online.Helpers;
using PluginManager.Others; using DiscordBotCore.Others;
namespace PluginManager.Plugin; namespace DiscordBotCore.Plugin;
public class PluginOnlineInfo public class PluginOnlineInfo
{ {

View File

@@ -6,9 +6,9 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Interfaces.Updater; using DiscordBotCore.Interfaces.Updater;
namespace PluginManager.Updater.Application namespace DiscordBotCore.Updater.Application
{ {
public class AppUpdater public class AppUpdater
{ {

View File

@@ -1,14 +1,7 @@
using System; 
using System.Collections.Generic; using DiscordBotCore.Interfaces.Updater;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands; namespace DiscordBotCore.Updater.Application
using PluginManager.Interfaces.Updater;
namespace PluginManager.Updater.Application
{ {
public class Update public class Update
{ {

View File

@@ -2,16 +2,17 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Online; using DiscordBotCore.Online;
using PluginManager.Plugin; using DiscordBotCore.Others;
using DiscordBotCore.Plugin;
namespace PluginManager.Updater.Plugins; namespace DiscordBotCore.Updater.Plugins;
public class PluginUpdater public class PluginUpdater
{ {
private readonly PluginsManager _PluginsManager; private readonly PluginManager _PluginsManager;
public PluginUpdater(PluginsManager pluginManager) public PluginUpdater(PluginManager pluginManager)
{ {
_PluginsManager = pluginManager; _PluginsManager = pluginManager;
} }
@@ -24,7 +25,7 @@ public class PluginUpdater
public async Task<PluginInfo> GetLocalPluginInfo(string pluginName) public async Task<PluginInfo> GetLocalPluginInfo(string pluginName)
{ {
string pluginsDatabase = File.ReadAllText(Config.AppSettings["PluginDatabase"]); string pluginsDatabase = File.ReadAllText(DiscordBotCore.Application.CurrentApplication.PluginDatabase);
List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(pluginsDatabase); List<PluginInfo> installedPlugins = await JsonManager.ConvertFromJson<List<PluginInfo>>(pluginsDatabase);
var result = installedPlugins.Find(p => p.PluginName == pluginName); var result = installedPlugins.Find(p => p.PluginName == pluginName);
@@ -35,7 +36,7 @@ public class PluginUpdater
public async Task UpdatePlugin(string pluginName, IProgress<float>? progressMeter = null) public async Task UpdatePlugin(string pluginName, IProgress<float>? progressMeter = null)
{ {
PluginOnlineInfo pluginInfo = await GetPluginInfo(pluginName); PluginOnlineInfo pluginInfo = await GetPluginInfo(pluginName);
await ServerCom.DownloadFileAsync(pluginInfo.DownLoadLink, $"{Config.AppSettings["PluginFolder"]}/{pluginName}.dll", progressMeter); await ServerCom.DownloadFileAsync(pluginInfo.DownLoadLink, $"{DiscordBotCore.Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll", progressMeter);
foreach(OnlineDependencyInfo dependency in pluginInfo.Dependencies) foreach(OnlineDependencyInfo dependency in pluginInfo.Dependencies)
await ServerCom.DownloadFileAsync(dependency.DownloadLocation, dependency.DownloadLocation, progressMeter); await ServerCom.DownloadFileAsync(dependency.DownloadLocation, dependency.DownloadLocation, progressMeter);

View File

@@ -79,7 +79,7 @@ internal class Help: DBCommand
); );
if (cmd == null) return null; if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); embedBuilder.AddField("Usage", Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"] + cmd.Usage);
embedBuilder.AddField("Description", cmd.Description); embedBuilder.AddField("Description", cmd.Description);
if (cmd.Aliases is null) if (cmd.Aliases is null)
return embedBuilder; return embedBuilder;

View File

@@ -18,8 +18,8 @@ namespace DiscordBotUI.Bot
public async Task InitializeBot() public async Task InitializeBot()
{ {
string token = Config.AppSettings["token"]; string token = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["token"];
string prefix = Config.AppSettings["prefix"]; string prefix = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"];
PluginManager.Bot.Boot discordBooter = new PluginManager.Bot.Boot(token, prefix); PluginManager.Bot.Boot discordBooter = new PluginManager.Bot.Boot(token, prefix);
await discordBooter.Awake(); await discordBooter.Awake();
} }
@@ -32,14 +32,14 @@ namespace DiscordBotUI.Bot
{ {
if (data.IsSuccess) if (data.IsSuccess)
{ {
Config.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction), Application.CurrentApplication.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction),
LogType.INFO LogType.INFO
); );
} }
else else
{ {
Config.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage, Application.CurrentApplication.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR typeof(ICommandAction), LogType.ERROR
); );
} }
@@ -48,13 +48,13 @@ namespace DiscordBotUI.Bot
{ {
if (data.IsSuccess) if (data.IsSuccess)
{ {
Config.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction), Application.CurrentApplication.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction),
LogType.INFO LogType.INFO
); );
} }
else else
{ {
Config.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage, Application.CurrentApplication.Logger.Log("Failed to load event : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR typeof(ICommandAction), LogType.ERROR
); );
} }
@@ -64,13 +64,13 @@ namespace DiscordBotUI.Bot
{ {
if (data.IsSuccess) if (data.IsSuccess)
{ {
Config.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction), Application.CurrentApplication.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction),
LogType.INFO LogType.INFO
); );
} }
else else
{ {
Config.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage, Application.CurrentApplication.Logger.Log("Failed to load slash command : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR typeof(ICommandAction), LogType.ERROR
); );
} }

View File

@@ -20,6 +20,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\PluginManager\PluginManager.csproj" /> <ProjectReference Include="..\..\PluginManager\DiscordBotCore.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -28,18 +28,18 @@ public partial class HomePage : Window
{ {
await Config.Initialize(); await Config.Initialize();
if(!Config.AppSettings.ContainsAllKeys("token", "prefix")) if(!Config.Application.CurrentApplication.ApplicationEnvironmentVariables.ContainsAllKeys("token", "prefix"))
{ {
await new SettingsPage().ShowDialog(this); await new SettingsPage().ShowDialog(this);
if (string.IsNullOrWhiteSpace(Config.AppSettings["token"]) || string.IsNullOrWhiteSpace(Config.AppSettings["prefix"])) if (string.IsNullOrWhiteSpace(Config.Application.CurrentApplication.ApplicationEnvironmentVariables["token"]) || string.IsNullOrWhiteSpace(Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"]))
Environment.Exit(-1); Environment.Exit(-1);
} }
textBoxToken.Text = Config.AppSettings["token"]; textBoxToken.Text = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["token"];
textBoxPrefix.Text = Config.AppSettings["prefix"]; textBoxPrefix.Text = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["prefix"];
textBoxServerId.Text = Config.AppSettings["ServerID"]; textBoxServerId.Text = Config.Application.CurrentApplication.ApplicationEnvironmentVariables["ServerID"];
} }
private void SetTextToTB(Log logMessage) private void SetTextToTB(Log logMessage)
@@ -50,7 +50,7 @@ public partial class HomePage : Window
private async void ButtonStartBotClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) private async void ButtonStartBotClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{ {
Config.Logger.OnLog += async (sender, logMessage) => Application.CurrentApplication.Logger.OnLog += async (sender, logMessage) =>
{ {
await Dispatcher.UIThread.InvokeAsync(() => SetTextToTB(logMessage), DispatcherPriority.Background); await Dispatcher.UIThread.InvokeAsync(() => SetTextToTB(logMessage), DispatcherPriority.Background);
}; };

View File

@@ -30,13 +30,13 @@ public partial class SettingsPage : Window
return; return;
} }
Config.AppSettings.Add("token", token); Config.Application.CurrentApplication.ApplicationEnvironmentVariables.Add("token", token);
Config.AppSettings.Add("prefix", botPrefix); Config.Application.CurrentApplication.ApplicationEnvironmentVariables.Add("prefix", botPrefix);
Config.AppSettings.Add("ServerID", serverId); Config.Application.CurrentApplication.ApplicationEnvironmentVariables.Add("ServerID", serverId);
await Config.AppSettings.SaveToFile(); await Config.Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile();
Config.Logger.Log("Config Saved"); Application.CurrentApplication.Logger.Log("Config Saved");
Close(); Close();

View File

@@ -1,84 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using PluginManager.Bot;
using PluginManager.Interfaces.Updater;
using PluginManager.Online;
using PluginManager.Others;
using PluginManager.Others.Actions;
using PluginManager.Others.Logger;
using PluginManager.Plugin;
using PluginManager.Updater.Application;
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;
internal static string PluginDatabase => AppSettings["PluginDatabase"];
internal static string ServerID => AppSettings["ServerID"];
public static InternalActionManager InternalActionManager;
public static PluginsManager PluginsManager;
internal static Boot? DiscordBotClient;
public static Boot? DiscordBot => DiscordBotClient;
public static async Task Initialize()
{
if (_isLoaded) return;
Directory.CreateDirectory(_ResourcesFolder);
Directory.CreateDirectory(_PluginsFolder);
Directory.CreateDirectory(_ArchivesFolder);
Directory.CreateDirectory(_LogsFolder);
AppSettings = new SettingsDictionary<string, string>(_ConfigFile);
bool response = await AppSettings.LoadFromFile();
if (!response)
throw new Exception("Invalid config file");
AppSettings["LogFolder"] = _LogsFolder;
AppSettings["PluginFolder"] = _PluginsFolder;
AppSettings["ArchiveFolder"] = _ArchivesFolder;
AppSettings["PluginDatabase"] = _PluginsDatabaseFile;
if (!File.Exists(_PluginsDatabaseFile))
{
List<PluginInfo> plugins = new();
await JsonManager.SaveToJsonFile(_PluginsDatabaseFile, plugins);
}
Logger = new Logger(false, true, _LogsFolder + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log");
PluginsManager = new PluginsManager(_DefaultBranchForPlugins);
await PluginsManager.UninstallMarkedPlugins();
await PluginsManager.CheckForUpdates();
_isLoaded = true;
Logger.Log("Config initialized", typeof(Config));
}
}

View File

@@ -1,14 +0,0 @@
using System;
using PluginManager.Others;
namespace PluginManager.Interfaces.Logger;
internal interface ILog
{
string Message { get; set; }
Type? Source { get; set; }
LogType Type { get; set; }
DateTime ThrowTime { get; set; }
}

View File

@@ -1,19 +0,0 @@
using System;
using System.Threading.Tasks;
using PluginManager.Others;
using PluginManager.Others.Logger;
namespace PluginManager.Interfaces.Logger;
internal interface ILogger
{
bool IsEnabled { get; init; }
bool OutputToFile { get; init; }
string OutputFile { get; init; }
event EventHandler<Log> OnLog;
void Log(
string message = "", Type? source = default, LogType type = LogType.INFO,
DateTime throwTime = default);
}

View File

@@ -1,70 +0,0 @@
using System;
using System.Linq;
using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger;
public class Log: ILog
{
public string Message { get; set; }
public Type? Source { get; set; }
public LogType Type { get; set; }
public DateTime ThrowTime { get; set; }
public Log(string message, Type? source, LogType type, DateTime throwTime)
{
Message = message;
Source = source;
Type = type;
ThrowTime = throwTime;
}
public Log(string message, Type? source, LogType type)
{
Message = message;
Source = source;
Type = type;
ThrowTime = DateTime.Now;
}
public Log(string message, Type? source)
{
Message = message;
Source = source;
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public Log(string message)
{
Message = message;
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public static implicit operator Log(string message)
{
return new Log(message);
}
public static implicit operator string(Log log)
{
return $"[{log.ThrowTime}] {log.Message}";
}
public string AsLongString()
{
return $"[{ThrowTime}] [{Source}] [{Type}] {Message}";
}
public string AsShortString()
{
return this;
}
public string FormatedLongString()
{
return $"[{ThrowTime}]\t[{Source}]\t\t\t[{Type}]\t{Message}";
}
}

View File

@@ -1,79 +0,0 @@
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger;
public sealed class Logger: ILogger
{
public bool IsEnabled { get; init; }
public bool OutputToFile { get; init; }
public string? OutputFile { get; init; }
private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, string outputFile, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = outputToFile;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = outputFile;
}
public Logger(bool useShortVersion, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = false;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = null;
}
public event EventHandler<Log>? OnLog;
private async Task Log(Log logMessage)
{
if (!IsEnabled) return;
OnLog?.Invoke(this, logMessage);
if (logMessage.Type < LowestLogLevel) return;
if (OutputToFile)
await File.AppendAllTextAsync(
OutputFile!,
(UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n"
);
}
public async void Log(string message = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default)
{
if (!IsEnabled) return;
if (type < LowestLogLevel) return;
if (string.IsNullOrEmpty(message)) return;
if (throwTime == default) throwTime = DateTime.Now;
if (source == default) source = typeof(Log);
await Log(new Log(message, source, type, throwTime));
}
public async void Log(Exception exception, LogType logType = LogType.ERROR, Type? source = null)
{
if (!IsEnabled) return;
if (logType < LowestLogLevel) return;
await Log(new Log(exception.Message, source, logType, DateTime.Now));
}
}

View File

@@ -4,14 +4,14 @@ VisualStudioVersion = 17.1.32421.90
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\DiscordBot.csproj", "{087E64F4-1E1C-4899-8223-295356C9894A}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\DiscordBot.csproj", "{087E64F4-1E1C-4899-8223-295356C9894A}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SethPlugins", "SethPlugins", "{78B6D390-F61A-453F-B38D-E4C054321615}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SethPlugins", "SethPlugins", "{78B6D390-F61A-453F-B38D-E4C054321615}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI", "DiscordBotUI\DiscordBotUI\DiscordBotUI.csproj", "{71293BF7-79D0-4707-AB4B-FDD16800FA81}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI", "DiscordBotUI\DiscordBotUI\DiscordBotUI.csproj", "{71293BF7-79D0-4707-AB4B-FDD16800FA81}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI.Desktop", "DiscordBotUI\DiscordBotUI.Desktop\DiscordBotUI.Desktop.csproj", "{F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI.Desktop", "DiscordBotUI\DiscordBotUI.Desktop\DiscordBotUI.Desktop.csproj", "{F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotCore", "DiscordBotCore\DiscordBotCore.csproj", "{5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -22,10 +22,6 @@ Global
{087E64F4-1E1C-4899-8223-295356C9894A}.Debug|Any CPU.Build.0 = Debug|Any CPU {087E64F4-1E1C-4899-8223-295356C9894A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{087E64F4-1E1C-4899-8223-295356C9894A}.Release|Any CPU.ActiveCfg = Release|Any CPU {087E64F4-1E1C-4899-8223-295356C9894A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{087E64F4-1E1C-4899-8223-295356C9894A}.Release|Any CPU.Build.0 = Release|Any CPU {087E64F4-1E1C-4899-8223-295356C9894A}.Release|Any CPU.Build.0 = Release|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
{71293BF7-79D0-4707-AB4B-FDD16800FA81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {71293BF7-79D0-4707-AB4B-FDD16800FA81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{71293BF7-79D0-4707-AB4B-FDD16800FA81}.Debug|Any CPU.Build.0 = Debug|Any CPU {71293BF7-79D0-4707-AB4B-FDD16800FA81}.Debug|Any CPU.Build.0 = Debug|Any CPU
{71293BF7-79D0-4707-AB4B-FDD16800FA81}.Release|Any CPU.ActiveCfg = Release|Any CPU {71293BF7-79D0-4707-AB4B-FDD16800FA81}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -34,6 +30,10 @@ Global
{F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Release|Any CPU.Build.0 = Release|Any CPU {F23CF852-2042-4BDE-ABFE-D4F5BD9B991D}.Release|Any CPU.Build.0 = Release|Any CPU
{5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5A99BFC3-EB39-4AEF-8D61-3CE22D013B02}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE