Updated Dependency to accept DependencyName as parameter

This commit is contained in:
2024-06-07 21:01:10 +03:00
parent 1a5f0cbede
commit 9a8ddb5388
14 changed files with 152 additions and 83 deletions

View File

@@ -53,6 +53,9 @@ internal static class PluginMethods
return; return;
} }
// rename the plugin to the name of the plugin
pluginName = pluginData.Name;
var pluginLink = pluginData.DownLoadLink; var pluginLink = pluginData.DownLoadLink;
@@ -68,7 +71,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, $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginName}.dll", progress); await ServerCom.DownloadFileAsync(pluginLink, $"{Application.CurrentApplication.ApplicationEnvironmentVariables["PluginFolder"]}/{pluginData.Name}.dll", progress);
downloadTask.Increment(100); downloadTask.Increment(100);
@@ -84,7 +87,7 @@ internal static class PluginMethods
await manager.ExecutePluginInstallScripts(pluginData.ScriptDependencies); await manager.ExecutePluginInstallScripts(pluginData.ScriptDependencies);
} }
PluginInfo pluginInfo = new(pluginName, pluginData.Version, new List<string>()); PluginInfo pluginInfo = new(pluginName, pluginData.Version, []);
Console.WriteLine("Finished installing " + pluginName + " successfully"); Console.WriteLine("Finished installing " + pluginName + " successfully");
await manager.AppendPluginToDatabase(pluginInfo); await manager.AppendPluginToDatabase(pluginInfo);
await RefreshPlugins(false); await RefreshPlugins(false);
@@ -129,7 +132,8 @@ internal static class PluginMethods
await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) => await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) =>
{ {
tuple.Item1.IsIndeterminate = false; tuple.Item1.IsIndeterminate = false;
await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2); string downloadLocation = manager.GenerateDependencyLocation(pluginName, tuple.Item4);
await ServerCom.DownloadFileAsync(tuple.Item3, downloadLocation, tuple.Item2);
} }
); );
@@ -145,7 +149,7 @@ internal static class PluginMethods
await manager.ExecutePluginInstallScripts(pluginData.ScriptDependencies); await manager.ExecutePluginInstallScripts(pluginData.ScriptDependencies);
} }
await manager.AppendPluginToDatabase(new PluginInfo(pluginName, pluginData.Version, pluginData.Dependencies.Select(sep => sep.DownloadLocation).ToList())); await manager.AppendPluginToDatabase(PluginInfo.FromOnlineInfo(pluginData));
await RefreshPlugins(false); await RefreshPlugins(false);
} }

View File

@@ -21,7 +21,9 @@ public class Help: ICommandAction
public string Usage => "help <command?>"; public string Usage => "help <command?>";
public IEnumerable<InternalActionOption> ListOfOptions => []; public IEnumerable<InternalActionOption> ListOfOptions => [
new InternalActionOption("command", "The command to get help for")
];
public InternalActionRunType RunType => InternalActionRunType.ON_CALL; public InternalActionRunType RunType => InternalActionRunType.ON_CALL;

View File

@@ -69,9 +69,11 @@ public static class Entry
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{ {
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries"); string requestingAssembly = args.RequestingAssembly?.GetName().Name;
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, $"Libraries\\{requestingAssembly}");
var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll"); var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
if (!File.Exists(assemblyPath)) return null; if (!File.Exists(assemblyPath))
return null;
var assembly = Assembly.LoadFrom(assemblyPath); var assembly = Assembly.LoadFrom(assemblyPath);
return assembly; return assembly;

View File

@@ -19,4 +19,6 @@ public interface ICommandAction
public InternalActionRunType RunType { get; } public InternalActionRunType RunType { get; }
public Task Execute(string[]? args); public Task Execute(string[]? args);
public void ExecuteStartup() { }
} }

View File

@@ -56,8 +56,8 @@ public class ActionsLoader
continue; continue;
} }
if (action.RunType == InternalActionRunType.ON_STARTUP) if (action.RunType != InternalActionRunType.ON_CALL)
await action.Execute(null); action.ExecuteStartup();
ActionLoadedEvent?.Invoke(action.ActionName, type.Name, true); ActionLoadedEvent?.Invoke(action.ActionName, type.Name, true);
actions.Add(action); actions.Add(action);

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBotCore.Others; using DiscordBotCore.Others;
using DiscordBotCore.Plugin; using DiscordBotCore.Plugin;
@@ -58,7 +59,13 @@ public class PluginManager
public async Task<PluginOnlineInfo?> GetPluginDataByName(string pluginName) public async Task<PluginOnlineInfo?> GetPluginDataByName(string pluginName)
{ {
List<PluginOnlineInfo>? plugins = await GetPluginsList(); List<PluginOnlineInfo>? plugins = await GetPluginsList();
var result = plugins?.Find(p => p.Name == pluginName);
if(plugins == null)
return null;
// try to get the best matching plugin using the pluginName as a search query
PluginOnlineInfo? result = plugins.Find(pl => pl.Name.ToLower().Contains(pluginName.ToLower()));
if(result == null) return null;
return result; return result;
} }
@@ -145,12 +152,45 @@ public class PluginManager
{ {
File.Delete(pluginInfo.FilePath); File.Delete(pluginInfo.FilePath);
foreach(string dependency in pluginInfo.ListOfDependancies) foreach (var dependency in pluginInfo.ListOfDependancies)
File.Delete(dependency); File.Delete(dependency.Value);
await RemovePluginFromDatabase(pluginInfo.PluginName); await RemovePluginFromDatabase(pluginInfo.PluginName);
} }
public async Task<string> GetDependencyLocation(string dependencyName)
{
List<PluginInfo> installedPlugins = await GetInstalledPlugins();
foreach (var plugin in installedPlugins)
{
if (plugin.ListOfDependancies.ContainsKey(dependencyName))
return plugin.ListOfDependancies[dependencyName];
}
throw new Exception("Dependency not found");
}
public async Task<string> GetDependencyLocation(string pluginName, string dependencyName)
{
PluginOnlineInfo? pluginData = await GetPluginDataByName(pluginName);
if(pluginData == null)
throw new Exception("Plugin not found");
var dependency = pluginData.Dependencies.Find(dep => dep.DependencyName == dependencyName);
if(dependency == null)
throw new Exception("Dependency not found");
return dependency.DownloadLocation;
}
public string GenerateDependencyLocation(string pluginName, string dependencyName)
{
return Path.Combine(Environment.CurrentDirectory, $"Libraries/{pluginName}/{dependencyName}");
}
public async Task InstallPlugin(PluginOnlineInfo pluginData, IProgress<float>? installProgress) public async Task InstallPlugin(PluginOnlineInfo pluginData, IProgress<float>? installProgress)
{ {
installProgress?.Report(0f); installProgress?.Report(0f);
@@ -171,7 +211,9 @@ public class PluginManager
if (pluginData.HasFileDependencies) if (pluginData.HasFileDependencies)
foreach (var dependency in pluginData.Dependencies) foreach (var dependency in pluginData.Dependencies)
{ {
await ServerCom.DownloadFileAsync(dependency.DownloadLink, dependency.DownloadLocation, progress); string dependencyLocation = GenerateDependencyLocation(pluginData.Name, dependency.DownloadLocation);
await ServerCom.DownloadFileAsync(dependency.DownloadLink, dependencyLocation, progress);
currentProgress += stepProgress; currentProgress += stepProgress;
} }
@@ -186,12 +228,7 @@ public class PluginManager
currentProgress += stepProgress; currentProgress += stepProgress;
} }
PluginInfo pluginInfo = new PluginInfo( PluginInfo pluginInfo = PluginInfo.FromOnlineInfo(pluginData);
pluginData.Name,
pluginData.Version,
pluginData.Dependencies.Select(dep => dep.DownloadLocation)
.ToList()
);
await AppendPluginToDatabase(pluginInfo); await AppendPluginToDatabase(pluginInfo);
} }

View File

@@ -48,7 +48,10 @@ public static class ServerCom
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
client.Timeout = TimeSpan.FromMinutes(5); client.Timeout = TimeSpan.FromMinutes(5);
if(Directory.Exists(Path.GetDirectoryName(location)) == false)
{
Directory.CreateDirectory(Path.GetDirectoryName(location));
}
using (var file = new FileStream(location, FileMode.Create, FileAccess.Write, FileShare.None)) using (var file = new FileStream(location, FileMode.Create, FileAccess.Write, FileShare.None))
{ {
await client.DownloadFileAsync(URL, file, progress, downloadedBytes); await client.DownloadFileAsync(URL, file, progress, downloadedBytes);

View File

@@ -45,6 +45,12 @@ public class InternalActionManager
try try
{ {
if (Actions[actionName].RunType == InternalActionRunType.ON_STARTUP)
{
Application.CurrentApplication.Logger.Log($"Action {actionName} is not executable", this, LogType.ERROR);
return false;
}
await Actions[actionName].Execute(args); await Actions[actionName].Execute(args);
return true; return true;
} }

View File

@@ -22,7 +22,8 @@ public enum UnzipProgressType
public enum InternalActionRunType public enum InternalActionRunType
{ {
ON_STARTUP, ON_STARTUP,
ON_CALL ON_CALL,
BOTH
} }
[Flags] [Flags]

View File

@@ -1,12 +1,18 @@
using System.Text.Json.Serialization;
namespace DiscordBotCore.Plugin; namespace DiscordBotCore.Plugin;
public class OnlineDependencyInfo public class OnlineDependencyInfo
{ {
public string DependencyName { get; private set; }
public string DownloadLink { get; private set; } public string DownloadLink { get; private set; }
public string DownloadLocation { get; private set; } public string DownloadLocation { get; private set; }
public OnlineDependencyInfo(string downloadLink, string downloadLocation) [JsonConstructor]
public OnlineDependencyInfo(string dependencyName, string downloadLink, string downloadLocation)
{ {
DependencyName = dependencyName;
DownloadLink = downloadLink; DownloadLink = downloadLink;
DownloadLocation = downloadLocation; DownloadLocation = downloadLocation;
} }

View File

@@ -11,11 +11,11 @@ public class PluginInfo
public string PluginName { get; private set; } public string PluginName { get; private set; }
public PluginVersion PluginVersion { get; private set; } public PluginVersion PluginVersion { get; private set; }
public string FilePath { get; private set; } public string FilePath { get; private set; }
public List<string> ListOfDependancies {get; private set;} public Dictionary<string, string> ListOfDependancies {get; private set;}
public bool IsMarkedToUninstall {get; internal set;} public bool IsMarkedToUninstall {get; internal set;}
[JsonConstructor] [JsonConstructor]
public PluginInfo(string pluginName, PluginVersion pluginVersion, List<string> listOfDependancies, bool isMarkedToUninstall) public PluginInfo(string pluginName, PluginVersion pluginVersion, Dictionary<string, string> listOfDependancies, bool isMarkedToUninstall)
{ {
PluginName = pluginName; PluginName = pluginName;
PluginVersion = pluginVersion; PluginVersion = pluginVersion;
@@ -24,7 +24,7 @@ public class PluginInfo
FilePath = $"{Application.CurrentApplication.ApplicationEnvironmentVariables["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, Dictionary<string, string> listOfDependancies)
{ {
PluginName = pluginName; PluginName = pluginName;
PluginVersion = pluginVersion; PluginVersion = pluginVersion;
@@ -35,6 +35,6 @@ public class PluginInfo
public static PluginInfo FromOnlineInfo(PluginOnlineInfo onlineInfo) public static PluginInfo FromOnlineInfo(PluginOnlineInfo onlineInfo)
{ {
return new PluginInfo(onlineInfo.Name, onlineInfo.Version, onlineInfo.Dependencies.Select(dep => dep.DownloadLocation).ToList()); return new PluginInfo(onlineInfo.Name, onlineInfo.Version, onlineInfo.Dependencies.Select(dep => new KeyValuePair<string, string>(dep.DependencyName, dep.DownloadLocation)).ToDictionary());
} }
} }

View File

@@ -6,6 +6,7 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<StartupObject></StartupObject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@@ -9,38 +9,7 @@ using DiscordBotUI_Windows.WindowsForms;
namespace DiscordBotUI namespace DiscordBotUI
{ {
public class DiscordUICommand : ICommandAction
public class DiscordEventUI : DBEvent
{
public string Name => "DiscordUI";
public bool RequireOtherThread => true;
public string Description => "Discord UI desc";
public async void Start(DiscordSocketClient client)
{
await Config.ApplicationSettings.LoadFromFile();
await Config.ThemeManager.LoadThemesFromThemesFolder();
if (Config.ApplicationSettings.ContainsKey("AppTheme"))
{
Config.ThemeManager.SetTheme(Config.ApplicationSettings["AppTheme"]);
} else Config.ApplicationSettings.Add("AppTheme", "Default");
Thread thread = new Thread(() =>
{
MainWindow mainWindow = new MainWindow();
Config.ThemeManager.SetFormTheme(Config.ThemeManager.CurrentTheme, mainWindow);
Application.Run(mainWindow);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
}
public class ConsoleStartAction : ICommandAction
{ {
public string ActionName => "ui"; public string ActionName => "ui";
@@ -52,7 +21,13 @@ namespace DiscordBotUI
new InternalActionOption("start", "Starts the UI") new InternalActionOption("start", "Starts the UI")
]; ];
public InternalActionRunType RunType => InternalActionRunType.ON_CALL; public InternalActionRunType RunType => InternalActionRunType.BOTH;
public async void ExecuteStartup()
{
Directory.CreateDirectory(Path.Combine(DiscordBotCore.Application.CurrentApplication.DataFolder, "DiscordBotUI"));
await Execute(["start"]);
}
public async Task Execute(string[]? args) public async Task Execute(string[]? args)
{ {
@@ -62,8 +37,6 @@ namespace DiscordBotUI
return; return;
} }
if (args[0] == "theme") if (args[0] == "theme")
{ {
if (args.Length == 1) if (args.Length == 1)
@@ -107,6 +80,13 @@ namespace DiscordBotUI
} }
if (args[0] == "start") if (args[0] == "start")
{
await StartUI();
}
}
private async Task StartUI()
{ {
await Config.ApplicationSettings.LoadFromFile(); await Config.ApplicationSettings.LoadFromFile();
@@ -116,16 +96,30 @@ namespace DiscordBotUI
{ {
Config.ThemeManager.SetTheme(Config.ApplicationSettings["AppTheme"]); Config.ThemeManager.SetTheme(Config.ApplicationSettings["AppTheme"]);
} }
else Config.ApplicationSettings.Add("AppTheme", "Default");
await Config.ApplicationSettings.SaveToFile();
Thread thread = new Thread(() => Thread thread = new Thread(() =>
{ {
MainWindow mainWindow = new MainWindow(); MainWindow mainWindow = new MainWindow();
Config.ThemeManager.SetFormTheme(Config.ThemeManager.CurrentTheme, mainWindow); Config.ThemeManager.SetFormTheme(Config.ThemeManager.CurrentTheme, mainWindow);
Application.Run(mainWindow); Application.Run(mainWindow);
}); });
thread.SetApartmentState(ApartmentState.STA); thread.SetApartmentState(ApartmentState.STA);
thread.Start(); thread.Start();
} }
}
public class DiscordEventUI2 : DBEvent
{
public string Name => "DiscordUI";
public bool RequireOtherThread => true;
public string Description => "Discord UI desc";
public async void Start(DiscordSocketClient client)
{
} }
} }

View File

@@ -8,6 +8,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotCore", "DiscordBo
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI_Windows", "DiscordBotUI\DiscordBotUI_Windows.csproj", "{95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI_Windows", "DiscordBotUI\DiscordBotUI_Windows.csproj", "{95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Plugins", "Plugins", "{8FAEFF5E-F749-435C-BB7B-D57C0F8B17FC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicPlayer", "..\SethPlugins\MusicPlayer\MusicPlayer.csproj", "{F094D29D-6F1A-46BC-8B1F-88F3D98FCA84}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -26,10 +30,17 @@ Global
{95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}.Debug|Any CPU.Build.0 = Debug|Any CPU {95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}.Debug|Any CPU.Build.0 = Debug|Any CPU
{95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}.Release|Any CPU.ActiveCfg = Release|Any CPU {95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}.Release|Any CPU.ActiveCfg = Release|Any CPU
{95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}.Release|Any CPU.Build.0 = Release|Any CPU {95AD2D0C-D1EB-47B9-8DB4-F11CBAF15704}.Release|Any CPU.Build.0 = Release|Any CPU
{F094D29D-6F1A-46BC-8B1F-88F3D98FCA84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F094D29D-6F1A-46BC-8B1F-88F3D98FCA84}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F094D29D-6F1A-46BC-8B1F-88F3D98FCA84}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F094D29D-6F1A-46BC-8B1F-88F3D98FCA84}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{F094D29D-6F1A-46BC-8B1F-88F3D98FCA84} = {8FAEFF5E-F749-435C-BB7B-D57C0F8B17FC}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF} SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF}
EndGlobalSection EndGlobalSection