Working on module/plugin system

This commit is contained in:
Masu Baumgartner
2024-11-14 22:30:02 +01:00
parent e5555c815b
commit 072adb5bb1
7 changed files with 94 additions and 156 deletions

View File

@@ -1,37 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Moonlight.ApiServer.Services;
using Moonlight.Shared.Http.Responses.ClientPlugins;
namespace Moonlight.ApiServer.Http.Controllers.ClientPlugins;
[ApiController]
[Route("api/clientPlugins")]
public class ClientPluginsController : Controller
{
private readonly ModuleService ModuleService;
public ClientPluginsController(ModuleService moduleService)
{
ModuleService = moduleService;
}
[HttpGet]
public async Task<ClientPluginsResponse> Get()
{
var dlls = ModuleService.Modules
.Where(x => x.Modules.ContainsKey("client"))
.SelectMany(x =>
x.Modules
.FirstOrDefault(c => c.Key == "client")
.Value
.Select(y => x.Name + "." + y)
)
.ToArray();
return new()
{
CacheKey = "unset",
Dlls = dlls
};
}
}

View File

@@ -1,12 +0,0 @@
namespace Moonlight.ApiServer.Models;
public class ModuleModel
{
public string Name { get; set; }
public string Author { get; set; }
public string Version { get; set; }
public string? DonateUrl { get; set; }
public string? UpdateUrl { get; set; }
public Dictionary<string, List<string>> Modules { get; set; } = new();
}

View File

@@ -0,0 +1,12 @@
namespace Moonlight.ApiServer.Models;
public class PluginMeta
{
public string Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string? DonationUrl { get; set; }
public string? UpdateUrl { get; set; }
public Dictionary<string, string[]> Binaries { get; set; } = new();
}

View File

@@ -38,6 +38,7 @@
<ItemGroup> <ItemGroup>
<Folder Include="Database\Migrations\" /> <Folder Include="Database\Migrations\" />
<Folder Include="storage\plugins\" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,74 +0,0 @@
using System.Text.Json;
using MoonCore.Helpers;
using Moonlight.ApiServer.Models;
namespace Moonlight.ApiServer.Services;
public class ModuleService
{
private readonly ILogger<ModuleService> Logger;
private readonly Dictionary<string, ModuleModel> ModuleMeta = new();
private static string ModulePath = PathBuilder.Dir("storage", "modules");
public ModuleModel[] Modules => ModuleMeta.Values.ToArray();
public ModuleService(ILogger<ModuleService> logger)
{
Logger = logger;
}
public void Load()
{
Logger.LogInformation("Loading modules");
Directory.CreateDirectory(ModulePath);
foreach (var moduleDirectory in Directory.EnumerateDirectories(ModulePath))
{
var metaPath = PathBuilder.File(moduleDirectory, "meta.json");
if (!File.Exists(metaPath))
{
Logger.LogWarning("No meta.json found in {folder}", moduleDirectory);
continue;
}
ModuleModel moduleModel;
try
{
var json = File.ReadAllText(metaPath);
moduleModel = JsonSerializer.Deserialize<ModuleModel>(json)!;
}
catch (Exception e)
{
Logger.LogError("An error occured while loading meta.json in {folder}: {e}", moduleDirectory, e);
continue;
}
ModuleMeta.Add(moduleDirectory, moduleModel);
}
Logger.LogInformation("Loaded {count} modules", ModuleMeta.Count);
}
public string[] GetModuleDlls(string moduleName, string section)
{
if (ModuleMeta.All(x => x.Value.Name != moduleName))
throw new ArgumentException($"No module with the name '{moduleName}' found");
var moduleKvp = ModuleMeta
.FirstOrDefault(x => x.Value.Name == moduleName);
var module = moduleKvp.Value;
if (!module.Modules.ContainsKey(section))
return [];
var modulePaths = module.Modules[section].Select(
dllName => PathBuilder.File(ModulePath, moduleKvp.Key, "bin", section, dllName)
).Where(File.Exists).ToArray();
return modulePaths;
}
}

View File

@@ -0,0 +1,75 @@
using System.Text.Json;
using MoonCore.Helpers;
using Moonlight.ApiServer.Models;
namespace Moonlight.ApiServer.Services;
public class PluginService
{
private readonly Dictionary<string, PluginMeta> Plugins = new();
private readonly ILogger<PluginService> Logger;
private static string PluginsPath = PathBuilder.Dir("storage", "plugins");
public PluginService(ILogger<PluginService> logger)
{
Logger = logger;
}
public async Task Load()
{
Logger.LogInformation("Loading plugins...");
foreach (var pluginPath in Directory.EnumerateDirectories(PluginsPath))
{
var metaPath = PathBuilder.File(PluginsPath, "meta.json");
if (!File.Exists(metaPath))
{
Logger.LogWarning("Ignoring folder '{name}'. No meta.json found", pluginPath);
continue;
}
var metaContent = await File.ReadAllTextAsync(metaPath);
PluginMeta meta;
try
{
meta = JsonSerializer.Deserialize<PluginMeta>(metaContent)
?? throw new JsonException();
}
catch (Exception e)
{
Logger.LogCritical("Unable to deserialize meta.json: {e}", e);
continue;
}
Plugins.Add(pluginPath, meta);
}
}
public Task<Dictionary<string, string[]>> GetBinariesBySection(string section)
{
var bins = Plugins
.Values
.Where(x => x.Binaries.ContainsKey(section))
.ToDictionary(x => x.Id, x => x.Binaries[section]);
return Task.FromResult(bins);
}
public Task<Stream?> GetBinaryStream(string plugin, string section, string fileName)
{
if (Plugins.All(x => x.Value.Id != plugin))
return Task.FromResult<Stream?>(null);
var pluginData = Plugins.First(x => x.Value.Id == plugin);
var binaryPath = PathBuilder.File(pluginData.Key, section, fileName);
if (!File.Exists(binaryPath))
return Task.FromResult<Stream?>(null);
var fs = File.OpenRead(binaryPath);
return Task.FromResult<Stream?>(fs);
}
}

View File

@@ -69,33 +69,7 @@ public static class Startup
var startupLogger = startupLoggerFactory.CreateLogger("Startup"); var startupLogger = startupLoggerFactory.CreateLogger("Startup");
// Load plugin/modules //TODO: Load plugin
var moduleService = new ModuleService(startupLoggerFactory.CreateLogger<ModuleService>());
moduleService.Load();
// Load api server module assemblies
var apiServerDlls = moduleService.Modules.SelectMany(
x => moduleService.GetModuleDlls(x.Name, "apiServer")
);
var apiServerModuleContext = new AssemblyLoadContext(null);
foreach (var apiServerDll in apiServerDlls)
{
try
{
apiServerModuleContext.LoadFromStream(File.OpenRead(
apiServerDll
));
}
catch (Exception e)
{
startupLogger.LogCritical("Unable to load dll {name} into context: {e}", apiServerDll, e);
throw;
}
}
var moduleAssemblies = apiServerModuleContext.Assemblies.ToArray();
// Configure startup interfaces // Configure startup interfaces
var startupServiceCollection = new ServiceCollection(); var startupServiceCollection = new ServiceCollection();
@@ -123,7 +97,7 @@ public static class Startup
if(additionalAssemblies != null) if(additionalAssemblies != null)
configuration.AddAssemblies(additionalAssemblies); configuration.AddAssemblies(additionalAssemblies);
configuration.AddAssemblies(moduleAssemblies); //configuration.AddAssemblies(moduleAssemblies);
}); });
@@ -164,10 +138,9 @@ public static class Startup
var controllerBuilder = builder.Services.AddControllers(); var controllerBuilder = builder.Services.AddControllers();
// Add current assemblies to the application part // Add current assemblies to the application part
foreach (var moduleAssembly in moduleAssemblies) //foreach (var moduleAssembly in moduleAssemblies)
controllerBuilder.AddApplicationPart(moduleAssembly); // controllerBuilder.AddApplicationPart(moduleAssembly);
builder.Services.AddSingleton(moduleService);
builder.Services.AddSingleton(config); builder.Services.AddSingleton(config);
builder.Services.AutoAddServices(typeof(Startup).Assembly); builder.Services.AutoAddServices(typeof(Startup).Assembly);
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
@@ -185,7 +158,7 @@ public static class Startup
if(additionalAssemblies != null) if(additionalAssemblies != null)
configuration.AddAssemblies(additionalAssemblies); configuration.AddAssemblies(additionalAssemblies);
configuration.AddAssemblies(moduleAssemblies); //configuration.AddAssemblies(moduleAssemblies);
}); });
var app = builder.Build(); var app = builder.Build();