106 lines
3.3 KiB
C#
106 lines
3.3 KiB
C#
|
|
using Cowain.Base.Models;
|
|
using Cowain.Base.Models.Menu;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using System;
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
|
|
namespace Cowain.Base.Abstractions.Plugin;
|
|
|
|
/// <summary>
|
|
/// 插件基类
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public abstract class PluginBase : IPlugin
|
|
{
|
|
|
|
private ILogger<PluginBase>? _logger;
|
|
/// <summary>
|
|
/// 插件名称
|
|
/// </summary>
|
|
public abstract string PluginName { get; }
|
|
public string? PluginPath { get; private set; }
|
|
|
|
/// <summary>
|
|
/// 配置插件菜单
|
|
/// </summary>
|
|
/// <param name="menuContext"></param>
|
|
public virtual void ConfigureMenu(MenuConfigurationContext? menuContext)
|
|
{
|
|
if (menuContext == null)
|
|
{
|
|
return;
|
|
}
|
|
if (string.IsNullOrEmpty(PluginPath))
|
|
{
|
|
return;
|
|
}
|
|
var menuFile = Path.Combine(PluginPath, PluginName, "Configs", "menus.json");
|
|
if (!File.Exists(menuFile))
|
|
{
|
|
return;
|
|
}
|
|
// 从插件 Configs 目录下读取插件菜单配置
|
|
var menus = JsonSerializer.Deserialize<List<MenuItem>>(File.ReadAllBytes(menuFile));
|
|
if (menus == null)
|
|
{
|
|
return;
|
|
}
|
|
foreach (var menu in menus.Where(x => x.Group == "Toolbar").ToList())
|
|
{
|
|
var item = menuContext.Menus.FirstOrDefault(x => x.Key == menu.Key);
|
|
if (item != null)
|
|
{
|
|
//一级菜单已经存在
|
|
if (menu.Items.Count > 0)
|
|
{
|
|
//有二级菜单,合并二级菜单
|
|
foreach (var menuItem in menu.Items)
|
|
{
|
|
var existingMenu = item.Items.FirstOrDefault(x => x.Key == menuItem.Key);
|
|
if (existingMenu == null)
|
|
{
|
|
item.Items.Add(menuItem);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
//无二级菜单,更新一级菜单属性
|
|
item.CommandType = menu.CommandType;
|
|
item.CommandParameter = menu.CommandParameter;
|
|
item.PageActions = menu.PageActions;
|
|
}
|
|
|
|
}
|
|
else
|
|
{
|
|
//新的一级菜单
|
|
menuContext.Menus.Add(menu);
|
|
}
|
|
}
|
|
|
|
}
|
|
public abstract R? Execute<T, R>(string methodName, T? parameters) where R : ResultModel<R>;
|
|
public abstract void RegisterServices(IServiceCollection services, List<Assembly>? _assemblies);
|
|
|
|
public virtual void Initialize(IServiceProvider serviceProvider)
|
|
{
|
|
var appSettings = serviceProvider.GetRequiredService<IOptions<AppSettings>>().Value;
|
|
var menuConfigurationContext = serviceProvider.GetRequiredService<MenuConfigurationContext>();
|
|
PluginPath = appSettings.PluginPath;
|
|
ConfigureMenu(menuConfigurationContext);
|
|
_logger = serviceProvider.GetRequiredService<ILogger<PluginBase>>();
|
|
_logger?.LogInformation($"插件 {PluginName} 初始化");
|
|
|
|
}
|
|
|
|
public virtual void Shutdown()
|
|
{
|
|
_logger?.LogInformation($"插件 {PluginName} 关闭");
|
|
}
|
|
}
|