Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
001fe01ace | ||
|
|
0aa0c44634 | ||
|
|
93126e514e | ||
|
|
1ae10ae0c6 | ||
|
|
4b693bf6e2 | ||
|
|
574c257591 | ||
|
|
d680328762 | ||
|
|
d711cdecaf | ||
|
|
c5f1792009 | ||
|
|
a5e705e6a4 | ||
|
|
007f1db339 | ||
|
|
008fb39f8f |
No files matched your search
@@ -2,7 +2,7 @@
|
||||
[使用文档](https://napneko.github.io/)
|
||||
|
||||
## Windows 一键包
|
||||
我们为提供了的轻量化一键部署方案
|
||||
我们提供了轻量化的一键部署方案
|
||||
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
|
||||
|
||||
你可以下载
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
[使用文档](https://napneko.github.io/)
|
||||
|
||||
## Windows 一键包
|
||||
我们为提供了的轻量化一键部署方案
|
||||
我们提供了轻量化的一键部署方案
|
||||
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
|
||||
|
||||
你可以下载
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
- name: Copy OpenAPI Schema
|
||||
run: |
|
||||
mkdir -p napcat-docs/src/api/${{ env.version }}
|
||||
cp packages/napcat-schema/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
|
||||
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
|
||||
echo "OpenAPI schema copied to napcat-docs/src/api/${{ env.version }}/openapi.json"
|
||||
|
||||
- name: Commit and Push
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "napcat-types",
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"types": "./napcat-types/index.d.ts",
|
||||
"files": [
|
||||
"**/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/node": "^22.10.7",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/ws": "^8.5.12",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/multer": "^1.4.12",
|
||||
"@types/winston": "^2.4.4",
|
||||
"@types/yaml": "^1.9.7",
|
||||
"@types/ip": "^1.1.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
|
||||
override actionName = ActionName.CreateFlashTask;
|
||||
override payloadSchema = CreateFlashTaskPayloadSchema;
|
||||
override returnSchema = Type.Any({ description: '任务创建结果' });
|
||||
override actionSummary = '创建闪照任务';
|
||||
override actionSummary = '创建闪传任务';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
files: 'C:\\test.jpg',
|
||||
|
||||
@@ -12,7 +12,7 @@ export class GetFlashFileList extends OneBotAction<GetFlashFileListPayload, any>
|
||||
override actionName = ActionName.GetFlashFileList;
|
||||
override payloadSchema = GetFlashFileListPayloadSchema;
|
||||
override returnSchema = Type.Any({ description: '文件列表' });
|
||||
override actionSummary = '获取闪照文件列表';
|
||||
override actionSummary = '获取闪传文件列表';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
fileset_id: 'set_123'
|
||||
|
||||
@@ -14,7 +14,7 @@ export class GetFlashFileUrl extends OneBotAction<GetFlashFileUrlPayload, any> {
|
||||
override actionName = ActionName.GetFlashFileUrl;
|
||||
override payloadSchema = GetFlashFileUrlPayloadSchema;
|
||||
override returnSchema = Type.Any({ description: '文件下载链接' });
|
||||
override actionSummary = '获取闪照文件链接';
|
||||
override actionSummary = '获取闪传文件链接';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
fileset_id: 'set_123'
|
||||
|
||||
@@ -15,7 +15,7 @@ export class SendFlashMsg extends OneBotAction<SendFlashMsgPayload, any> {
|
||||
override actionName = ActionName.SendFlashMsg;
|
||||
override payloadSchema = SendFlashMsgPayloadSchema;
|
||||
override returnSchema = Type.Any({ description: '发送结果' });
|
||||
override actionSummary = '发送闪照消息';
|
||||
override actionSummary = '发送闪传消息';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
fileset_id: 'set_123',
|
||||
|
||||
@@ -15,44 +15,104 @@ export interface PluginPackageJson {
|
||||
author?: string;
|
||||
}
|
||||
|
||||
export interface PluginConfigItem {
|
||||
key: string;
|
||||
type: 'string' | 'number' | 'boolean' | 'select' | 'multi-select' | 'html' | 'text';
|
||||
label: string;
|
||||
description?: string;
|
||||
default?: any;
|
||||
options?: { label: string; value: string | number; }[];
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export class NapCatConfig {
|
||||
static text (key: string, label: string, defaultValue?: string, description?: string): PluginConfigItem {
|
||||
return { key, type: 'string', label, default: defaultValue, description };
|
||||
}
|
||||
static number (key: string, label: string, defaultValue?: number, description?: string): PluginConfigItem {
|
||||
return { key, type: 'number', label, default: defaultValue, description };
|
||||
}
|
||||
static boolean (key: string, label: string, defaultValue?: boolean, description?: string): PluginConfigItem {
|
||||
return { key, type: 'boolean', label, default: defaultValue, description };
|
||||
}
|
||||
static select (key: string, label: string, options: { label: string; value: string | number; }[], defaultValue?: string | number, description?: string): PluginConfigItem {
|
||||
return { key, type: 'select', label, options, default: defaultValue, description };
|
||||
}
|
||||
static multiSelect (key: string, label: string, options: { label: string; value: string | number; }[], defaultValue?: (string | number)[], description?: string): PluginConfigItem {
|
||||
return { key, type: 'multi-select', label, options, default: defaultValue, description };
|
||||
}
|
||||
static html (content: string): PluginConfigItem {
|
||||
return { key: `_html_${Math.random().toString(36).slice(2)}`, type: 'html', label: '', default: content };
|
||||
}
|
||||
static plainText (content: string): PluginConfigItem {
|
||||
return { key: `_text_${Math.random().toString(36).slice(2)}`, type: 'text', label: '', default: content };
|
||||
}
|
||||
static combine (...items: PluginConfigItem[]): PluginConfigSchema {
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
export type PluginConfigSchema = PluginConfigItem[];
|
||||
|
||||
/**
|
||||
* 插件日志接口 - 简化的日志 API
|
||||
*/
|
||||
export interface PluginLogger {
|
||||
/** 普通日志 */
|
||||
log (...args: any[]): void;
|
||||
/** 调试日志 */
|
||||
debug (...args: any[]): void;
|
||||
/** 信息日志 */
|
||||
info (...args: any[]): void;
|
||||
/** 警告日志 */
|
||||
warn (...args: any[]): void;
|
||||
/** 错误日志 */
|
||||
error (...args: any[]): void;
|
||||
}
|
||||
|
||||
export interface NapCatPluginContext {
|
||||
core: NapCatCore;
|
||||
oneBot: NapCatOneBot11Adapter;
|
||||
actions: ActionMap;
|
||||
pluginName: string;
|
||||
pluginPath: string;
|
||||
configPath: string;
|
||||
dataPath: string;
|
||||
NapCatConfig: typeof NapCatConfig;
|
||||
adapterName: string;
|
||||
pluginManager: OB11PluginMangerAdapter;
|
||||
/** 插件日志器 - 自动添加插件名称前缀 */
|
||||
logger: PluginLogger;
|
||||
}
|
||||
|
||||
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
|
||||
plugin_init: (
|
||||
core: NapCatCore,
|
||||
obContext: NapCatOneBot11Adapter,
|
||||
actions: ActionMap,
|
||||
instance: OB11PluginMangerAdapter
|
||||
) => void | Promise<void>;
|
||||
plugin_init: (ctx: NapCatPluginContext) => void | Promise<void>;
|
||||
plugin_onmessage?: (
|
||||
adapter: string,
|
||||
core: NapCatCore,
|
||||
obCtx: NapCatOneBot11Adapter,
|
||||
ctx: NapCatPluginContext,
|
||||
event: OB11Message,
|
||||
actions: ActionMap,
|
||||
instance: OB11PluginMangerAdapter
|
||||
) => void | Promise<void>;
|
||||
plugin_onevent?: (
|
||||
adapter: string,
|
||||
core: NapCatCore,
|
||||
obCtx: NapCatOneBot11Adapter,
|
||||
ctx: NapCatPluginContext,
|
||||
event: T,
|
||||
actions: ActionMap,
|
||||
instance: OB11PluginMangerAdapter
|
||||
) => void | Promise<void>;
|
||||
plugin_cleanup?: (
|
||||
core: NapCatCore,
|
||||
obContext: NapCatOneBot11Adapter,
|
||||
actions: ActionMap,
|
||||
instance: OB11PluginMangerAdapter
|
||||
ctx: NapCatPluginContext
|
||||
) => void | Promise<void>;
|
||||
plugin_config_schema?: PluginConfigSchema;
|
||||
plugin_config_ui?: PluginConfigSchema;
|
||||
plugin_get_config?: (ctx: NapCatPluginContext) => any | Promise<any>;
|
||||
plugin_set_config?: (ctx: NapCatPluginContext, config: any) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface LoadedPlugin {
|
||||
name: string;
|
||||
dirname: string; // Actual directory name for path resolution
|
||||
version?: string;
|
||||
pluginPath: string;
|
||||
entryPath: string;
|
||||
packageJson?: PluginPackageJson;
|
||||
module: PluginModule;
|
||||
context: NapCatPluginContext; // Store context
|
||||
}
|
||||
|
||||
export interface PluginStatusConfig {
|
||||
@@ -63,7 +123,10 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
private readonly pluginPath: string;
|
||||
private readonly configPath: string;
|
||||
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
|
||||
// Track failed plugins: ID -> Error Message
|
||||
private failedPlugins: Map<string, string> = new Map();
|
||||
declare config: PluginConfig;
|
||||
public NapCatConfig = NapCatConfig;
|
||||
|
||||
override get isActive (): boolean {
|
||||
return this.isEnable && this.loadedPlugins.size > 0;
|
||||
@@ -123,28 +186,22 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
|
||||
const pluginConfig = this.loadPluginConfig();
|
||||
|
||||
// 扫描文件和目录
|
||||
// 扫描文件和目录 (Only support directories as plugins now)
|
||||
for (const item of items) {
|
||||
let pluginName = '';
|
||||
if (item.isFile()) {
|
||||
pluginName = path.parse(item.name).name;
|
||||
} else if (item.isDirectory()) {
|
||||
pluginName = item.name;
|
||||
}
|
||||
|
||||
// Check if plugin is disabled in config
|
||||
if (pluginConfig[pluginName] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} is disabled in config, skipping`);
|
||||
if (!item.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.isFile()) {
|
||||
// 处理单文件插件
|
||||
await this.loadFilePlugin(item.name);
|
||||
} else if (item.isDirectory()) {
|
||||
// 处理目录插件
|
||||
await this.loadDirectoryPlugin(item.name);
|
||||
const pluginId = item.name;
|
||||
|
||||
// Check if plugin is disabled in config
|
||||
if (pluginConfig[pluginId] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled in config, skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 处理目录插件
|
||||
await this.loadDirectoryPlugin(item.name);
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
@@ -155,49 +212,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载单文件插件 (.mjs, .js)
|
||||
*/
|
||||
public async loadFilePlugin (filename: string): Promise<void> {
|
||||
// 只处理支持的文件类型
|
||||
if (!this.isSupportedFile(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(this.pluginPath, filename);
|
||||
const pluginName = path.parse(filename).name;
|
||||
const pluginConfig = this.loadPluginConfig();
|
||||
|
||||
// Check if plugin is disabled in config
|
||||
if (pluginConfig[pluginName] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} is disabled by user`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const module = await this.importModule(filePath);
|
||||
if (!this.isValidPluginModule(module)) {
|
||||
this.logger.logWarn(
|
||||
`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
name: pluginName,
|
||||
pluginPath: this.pluginPath,
|
||||
entryPath: filePath,
|
||||
module,
|
||||
};
|
||||
|
||||
await this.registerPlugin(plugin);
|
||||
} catch (error) {
|
||||
this.logger.logError(
|
||||
`[Plugin Adapter] Error loading file plugin ${filename}:`,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
// loadFilePlugin removed
|
||||
|
||||
/**
|
||||
* 加载目录插件
|
||||
@@ -205,16 +220,10 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
public async loadDirectoryPlugin (dirname: string): Promise<void> {
|
||||
const pluginDir = path.join(this.pluginPath, dirname);
|
||||
const pluginConfig = this.loadPluginConfig();
|
||||
const pluginId = dirname; // Use directory name as unique ID
|
||||
|
||||
// Ideally we'd get the name from package.json first, but we can use dirname as a fallback identifier initially.
|
||||
// However, the list scan uses item.name (dirname) as the key. Let's stick to using dirname/filename as the config key for simplicity and consistency.
|
||||
// Wait, package.json name might override. But for management, consistent ID is better.
|
||||
// Let's check config after parsing package.json?
|
||||
// User expects to disable 'plugin-name'. But if multiple folders have same name? Not handled.
|
||||
// Let's use dirname as the key for config to be consistent with file system.
|
||||
|
||||
if (pluginConfig[dirname] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${dirname} is disabled by user`);
|
||||
if (pluginConfig[pluginId] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled by user`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -235,9 +244,6 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if disabled by package name IF package.json exists?
|
||||
// No, file system name is more reliable ID for resource management here.
|
||||
|
||||
// 确定入口文件
|
||||
const entryFile = this.findEntryFile(pluginDir, packageJson);
|
||||
if (!entryFile) {
|
||||
@@ -258,12 +264,14 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
name: packageJson?.name || dirname,
|
||||
name: packageJson?.name || pluginId, // Use package.json name for API lookups, fallback to dir name
|
||||
dirname: pluginId, // Keep track of actual directory name for path resolution
|
||||
version: packageJson?.version,
|
||||
pluginPath: pluginDir,
|
||||
entryPath,
|
||||
packageJson,
|
||||
module,
|
||||
context: {} as NapCatPluginContext // Will be populated in registerPlugin
|
||||
};
|
||||
|
||||
await this.registerPlugin(plugin);
|
||||
@@ -301,13 +309,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为支持的文件类型
|
||||
*/
|
||||
private isSupportedFile (filename: string): boolean {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
return ['.mjs', '.js'].includes(ext);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 动态导入模块
|
||||
@@ -327,6 +329,9 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return module && typeof module.plugin_init === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册插件
|
||||
*/
|
||||
/**
|
||||
* 注册插件
|
||||
*/
|
||||
@@ -339,6 +344,38 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create Context
|
||||
// Use dirname for path resolution, name for identification
|
||||
const dataPath = path.join(this.pluginPath, plugin.dirname, 'data');
|
||||
const configPath = path.join(dataPath, 'config.json');
|
||||
|
||||
// Create plugin-specific logger with prefix
|
||||
const pluginPrefix = `[Plugin: ${plugin.name}]`;
|
||||
const coreLogger = this.logger;
|
||||
const pluginLogger: PluginLogger = {
|
||||
log: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
|
||||
debug: (...args: any[]) => coreLogger.logDebug(pluginPrefix, ...args),
|
||||
info: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
|
||||
warn: (...args: any[]) => coreLogger.logWarn(pluginPrefix, ...args),
|
||||
error: (...args: any[]) => coreLogger.logError(pluginPrefix, ...args),
|
||||
};
|
||||
|
||||
const context: NapCatPluginContext = {
|
||||
core: this.core,
|
||||
oneBot: this.obContext,
|
||||
actions: this.actions,
|
||||
pluginName: plugin.name, // Use package name for identification
|
||||
pluginPath: plugin.pluginPath,
|
||||
dataPath: dataPath,
|
||||
configPath: configPath,
|
||||
NapCatConfig: NapCatConfig,
|
||||
adapterName: this.name,
|
||||
pluginManager: this,
|
||||
logger: pluginLogger
|
||||
};
|
||||
|
||||
plugin.context = context; // Store context on plugin object
|
||||
|
||||
this.loadedPlugins.set(plugin.name, plugin);
|
||||
this.logger.log(
|
||||
`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''
|
||||
@@ -347,18 +384,16 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
|
||||
// 调用插件初始化方法(必须存在)
|
||||
try {
|
||||
await plugin.module.plugin_init(
|
||||
this.core,
|
||||
this.obContext,
|
||||
this.actions,
|
||||
this
|
||||
);
|
||||
await plugin.module.plugin_init(context);
|
||||
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
this.logger.logError(
|
||||
`[Plugin Adapter] Error initializing plugin ${plugin.name}:`,
|
||||
error
|
||||
);
|
||||
// Mark as failed
|
||||
this.failedPlugins.set(plugin.name, error.message || 'Initialization failed');
|
||||
this.loadedPlugins.delete(plugin.name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,12 +409,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
// 调用插件清理方法
|
||||
if (typeof plugin.module.plugin_cleanup === 'function') {
|
||||
try {
|
||||
await plugin.module.plugin_cleanup(
|
||||
this.core,
|
||||
this.obContext,
|
||||
this.actions,
|
||||
this
|
||||
);
|
||||
await plugin.module.plugin_cleanup(plugin.context);
|
||||
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(
|
||||
@@ -406,54 +436,19 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
|
||||
public setPluginStatus (pluginName: string, enable: boolean): void {
|
||||
// Try to find plugin by package name first
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
// Use dirname for config storage (if plugin is loaded), otherwise assume pluginName is dirname
|
||||
const configKey = plugin?.dirname || pluginName;
|
||||
|
||||
const config = this.loadPluginConfig();
|
||||
config[pluginName] = enable;
|
||||
config[configKey] = enable;
|
||||
this.savePluginConfig(config);
|
||||
|
||||
// If disabling, unload immediately if loaded
|
||||
if (!enable) {
|
||||
// Note: pluginName passed here might be the package name or the filename/dirname
|
||||
// But our registerPlugin uses plugin.name which comes from package.json or dirname.
|
||||
// This mismatch is tricky.
|
||||
// Ideally, we should use a consistent ID.
|
||||
// Let's assume pluginName passed here effectively matches the ID used in loadedPlugins.
|
||||
// But wait, loadDirectoryPlugin logic: name = packageJson.name || dirname.
|
||||
// config key = dirname.
|
||||
// If packageJson.name != dirname, we have a problem.
|
||||
// To fix this properly:
|
||||
// 1. We need to know which LoadedPlugin corresponds to the enabled/disabled item.
|
||||
// 2. Or we iterate loadedPlugins and find match.
|
||||
|
||||
for (const [_, loaded] of this.loadedPlugins.entries()) {
|
||||
const dirOrFile = path.basename(loaded.pluginPath === this.pluginPath ? loaded.entryPath : loaded.pluginPath);
|
||||
const ext = path.extname(dirOrFile);
|
||||
const simpleName = ext ? path.parse(dirOrFile).name : dirOrFile; // filename without ext
|
||||
|
||||
// But wait, config key is the FILENAME (with ext for files?).
|
||||
// In Scan loop:
|
||||
// pluginName = path.parse(item.name).name (for file)
|
||||
// pluginName = item.name (for dir)
|
||||
// config[pluginName] check.
|
||||
|
||||
// So if file is "test.js", pluginName is "test". Config key "test".
|
||||
// If dir is "test-plugin", pluginName is "test-plugin". Config key "test-plugin".
|
||||
|
||||
// loadedPlugin.name might be distinct.
|
||||
// So we need to match loadedPlugin back to its fs source to unload it?
|
||||
|
||||
// loadedPlugin.entryPath or pluginPath helps.
|
||||
// If it's a file plugin: loaded.entryPath ends with pluginName + ext.
|
||||
// If it's a dir plugin: loaded.pluginPath ends with pluginName.
|
||||
|
||||
if (pluginName === simpleName) {
|
||||
this.unloadPlugin(loaded.name).catch(e => this.logger.logError('Error unloading', e));
|
||||
}
|
||||
}
|
||||
if (!enable && plugin) {
|
||||
// Unload by plugin.name (package name, which is the key in loadedPlugins)
|
||||
this.unloadPlugin(plugin.name).catch(e => this.logger.logError('Error unloading', e));
|
||||
}
|
||||
// If enabling, we need to load it.
|
||||
// But we can just rely on the API handler to call loadFile/DirectoryPlugin which now checks config.
|
||||
// Wait, if I call loadFilePlugin("test.js") and config says enable=true, it loads.
|
||||
// API handler needs to change to pass filename/dirname.
|
||||
}
|
||||
|
||||
async onEvent<T extends OB11EmitEventContent> (event: T) {
|
||||
@@ -461,7 +456,6 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return;
|
||||
}
|
||||
|
||||
// 遍历所有已加载的插件,调用它们的事件处理方法
|
||||
try {
|
||||
await Promise.allSettled(
|
||||
Array.from(this.loadedPlugins.values()).map((plugin) =>
|
||||
@@ -484,12 +478,8 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
// 优先使用 plugin_onevent 方法
|
||||
if (typeof plugin.module.plugin_onevent === 'function') {
|
||||
await plugin.module.plugin_onevent(
|
||||
this.name,
|
||||
this.core,
|
||||
this.obContext,
|
||||
event,
|
||||
this.actions,
|
||||
this
|
||||
plugin.context,
|
||||
event
|
||||
);
|
||||
}
|
||||
|
||||
@@ -499,12 +489,8 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
typeof plugin.module.plugin_onmessage === 'function'
|
||||
) {
|
||||
await plugin.module.plugin_onmessage(
|
||||
this.name,
|
||||
this.core,
|
||||
this.obContext,
|
||||
event as OB11Message,
|
||||
this.actions,
|
||||
this
|
||||
plugin.context,
|
||||
event as OB11Message
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -583,23 +569,14 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return false;
|
||||
}
|
||||
|
||||
const dirname = plugin.dirname;
|
||||
|
||||
try {
|
||||
// 卸载插件
|
||||
await this.unloadPlugin(pluginName);
|
||||
|
||||
// 重新加载插件
|
||||
// Use logic to re-determine if it is directory or file based on original paths
|
||||
// Note: we can't fully trust fs status if it's gone.
|
||||
const isDirectory =
|
||||
plugin.pluginPath !== this.pluginPath; // Simple check: if path is nested, it's a dir plugin
|
||||
|
||||
if (isDirectory) {
|
||||
const dirname = path.basename(plugin.pluginPath);
|
||||
await this.loadDirectoryPlugin(dirname);
|
||||
} else {
|
||||
const filename = path.basename(plugin.entryPath);
|
||||
await this.loadFilePlugin(filename);
|
||||
}
|
||||
// 重新加载插件 - use dirname for directory loading
|
||||
await this.loadDirectoryPlugin(dirname);
|
||||
|
||||
this.logger.log(
|
||||
`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`
|
||||
@@ -613,4 +590,14 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public getPluginDataPath (pluginName: string): string {
|
||||
// Lookup plugin by name (package name) and use dirname for path
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
const dirname = plugin?.dirname || pluginName; // fallback to pluginName if not found
|
||||
return path.join(this.pluginPath, dirname, 'data');
|
||||
}
|
||||
|
||||
public getPluginConfigPath (pluginName: string): string {
|
||||
return path.join(this.getPluginDataPath(pluginName), 'config.json');
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
|
||||
let isClosedByError = false;
|
||||
|
||||
this.connection = new WebSocket(this.config.url, {
|
||||
maxPayload: 1024 * 1024 * 1024,
|
||||
maxPayload: 50 * 1024 * 1024, // 50 MB
|
||||
handshakeTimeout: 2000,
|
||||
perMessageDeflate: false,
|
||||
headers: {
|
||||
|
||||
@@ -32,7 +32,7 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
|
||||
this.wsServer = new WebSocketServer({
|
||||
port: this.config.port,
|
||||
host: this.config.host === '0.0.0.0' ? '' : this.config.host,
|
||||
maxPayload: 1024 * 1024 * 1024,
|
||||
maxPayload: 50 * 1024 * 1024, // 50 MB
|
||||
});
|
||||
this.createServer(this.wsServer);
|
||||
}
|
||||
@@ -237,7 +237,7 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
|
||||
this.wsServer = new WebSocketServer({
|
||||
port: newConfig.port,
|
||||
host: newConfig.host === '0.0.0.0' ? '' : newConfig.host,
|
||||
maxPayload: 1024 * 1024 * 1024,
|
||||
maxPayload: 50 * 1024 * 1024, // 50 MB
|
||||
});
|
||||
this.createServer(this.wsServer);
|
||||
if (newConfig.enable) {
|
||||
|
||||
@@ -1,45 +1,108 @@
|
||||
import type { ActionMap } from 'napcat-types/napcat-onebot/action/index';
|
||||
import { EventType } from 'napcat-types/napcat-onebot/event/index';
|
||||
import type { PluginModule } from 'napcat-types/napcat-onebot/network/plugin-manger';
|
||||
import type { PluginModule, PluginLogger, PluginConfigSchema } from 'napcat-types/napcat-onebot/network/plugin-manger';
|
||||
import type { OB11Message, OB11PostSendMsg } from 'napcat-types/napcat-onebot/types/index';
|
||||
|
||||
let actions: ActionMap | undefined = undefined;
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { NetworkAdapterConfig } from 'napcat-types/napcat-onebot/config/config';
|
||||
let startTime: number = Date.now();
|
||||
let logger: PluginLogger | null = null;
|
||||
|
||||
/**
|
||||
* 插件初始化
|
||||
*/
|
||||
const plugin_init: PluginModule['plugin_init'] = async (_core, _obContext, _actions, _instance) => {
|
||||
console.log('[Plugin: builtin] NapCat 内置插件已初始化');
|
||||
actions = _actions;
|
||||
interface BuiltinPluginConfig {
|
||||
prefix: string;
|
||||
enableReply: boolean;
|
||||
description: string;
|
||||
theme?: string;
|
||||
features?: string[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
let currentConfig: BuiltinPluginConfig = {
|
||||
prefix: '#napcat',
|
||||
enableReply: true,
|
||||
description: '这是一个内置插件的配置示例'
|
||||
};
|
||||
|
||||
/**
|
||||
* 消息处理
|
||||
* 当收到包含 #napcat 的消息时,回复版本信息
|
||||
*/
|
||||
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (adapter, _core, _obCtx, event, _actions, instance) => {
|
||||
if (event.post_type !== EventType.MESSAGE || !event.raw_message.startsWith('#napcat')) {
|
||||
|
||||
export let plugin_config_ui: PluginConfigSchema = [];
|
||||
|
||||
const plugin_init: PluginModule['plugin_init'] = async (ctx) => {
|
||||
logger = ctx.logger;
|
||||
logger.info('NapCat 内置插件已初始化');
|
||||
plugin_config_ui = ctx.NapCatConfig.combine(
|
||||
ctx.NapCatConfig.html('<div style="padding: 10px; background: rgba(0,0,0,0.05); border-radius: 8px;"><h3>👋 Welcome to NapCat Builtin Plugin</h3><p>This is a demonstration of the plugin configuration interface.</p></div>'),
|
||||
ctx.NapCatConfig.text('prefix', 'Command Prefix', '#napcat', 'The prefix to trigger the version info command'),
|
||||
ctx.NapCatConfig.boolean('enableReply', 'Enable Reply', true, 'Switch to enable or disable the reply functionality'),
|
||||
ctx.NapCatConfig.select('theme', 'Theme Selection', [
|
||||
{ label: 'Light Mode', value: 'light' },
|
||||
{ label: 'Dark Mode', value: 'dark' },
|
||||
{ label: 'Auto', value: 'auto' }
|
||||
], 'light', 'Select a theme for the response (Demo purpose only)'),
|
||||
ctx.NapCatConfig.multiSelect('features', 'Enabled Features', [
|
||||
{ label: 'Version Info', value: 'version' },
|
||||
{ label: 'Status Report', value: 'status' },
|
||||
{ label: 'Debug Log', value: 'debug' }
|
||||
], ['version'], 'Select features to enable'),
|
||||
ctx.NapCatConfig.text('description', 'Description', '这是一个内置插件的配置示例', 'A multi-line text area for notes')
|
||||
);
|
||||
|
||||
// Try to load config
|
||||
try {
|
||||
// Use ctx.configPath
|
||||
if (fs.existsSync(ctx.configPath)) {
|
||||
const savedConfig = JSON.parse(fs.readFileSync(ctx.configPath, 'utf-8'));
|
||||
Object.assign(currentConfig, savedConfig);
|
||||
}
|
||||
} catch (e) {
|
||||
logger?.warn('Failed to load config', e);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
export const plugin_get_config = async () => {
|
||||
return currentConfig;
|
||||
};
|
||||
|
||||
export const plugin_set_config = async (ctx: any, config: BuiltinPluginConfig) => {
|
||||
currentConfig = config;
|
||||
if (ctx && ctx.configPath) {
|
||||
try {
|
||||
const configPath = ctx.configPath;
|
||||
const configDir = path.dirname(configPath);
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||
} catch (e) {
|
||||
logger?.error('Failed to save config', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (_ctx, event) => {
|
||||
if (currentConfig.enableReply === false) {
|
||||
return;
|
||||
}
|
||||
const prefix = currentConfig.prefix || '#napcat';
|
||||
if (event.post_type !== EventType.MESSAGE || !event.raw_message.startsWith(prefix)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const versionInfo = await getVersionInfo(adapter, instance.config);
|
||||
const versionInfo = await getVersionInfo(_ctx.actions, _ctx.adapterName, _ctx.pluginManager.config);
|
||||
if (!versionInfo) return;
|
||||
|
||||
const message = formatVersionMessage(versionInfo);
|
||||
await sendMessage(event, message, adapter, instance.config);
|
||||
await sendMessage(_ctx.actions, event, message, _ctx.adapterName, _ctx.pluginManager.config);
|
||||
|
||||
console.log('[Plugin: builtin] 已回复版本信息');
|
||||
logger?.info('已回复版本信息');
|
||||
} catch (error) {
|
||||
console.error('[Plugin: builtin] 处理消息时发生错误:', error);
|
||||
logger?.error('处理消息时发生错误:', error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取版本信息(完美的类型推导,无需 as 断言)
|
||||
*/
|
||||
async function getVersionInfo (adapter: string, config: any) {
|
||||
async function getVersionInfo (actions: ActionMap, adapter: string, config: NetworkAdapterConfig) {
|
||||
if (!actions) return null;
|
||||
|
||||
try {
|
||||
@@ -50,14 +113,11 @@ async function getVersionInfo (adapter: string, config: any) {
|
||||
protocolVersion: data.protocol_version,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[Plugin: builtin] 获取版本信息失败:', error);
|
||||
logger?.error('获取版本信息失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化运行时间
|
||||
*/
|
||||
function formatUptime (ms: number): string {
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
@@ -75,20 +135,12 @@ function formatUptime (ms: number): string {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化版本信息消息
|
||||
*/
|
||||
function formatVersionMessage (info: { appName: string; appVersion: string; protocolVersion: string; }) {
|
||||
const uptime = Date.now() - startTime;
|
||||
return `NapCat 信息\n版本: ${info.appVersion}\n平台: ${process.platform}${process.arch === 'x64' ? ' (64-bit)' : ''}\n运行时间: ${formatUptime(uptime)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息(完美的类型推导)
|
||||
*/
|
||||
async function sendMessage (event: OB11Message, message: string, adapter: string, config: any) {
|
||||
if (!actions) return;
|
||||
|
||||
async function sendMessage (actions: ActionMap, event: OB11Message, message: string, adapter: string, config: NetworkAdapterConfig) {
|
||||
const params: OB11PostSendMsg = {
|
||||
message,
|
||||
message_type: event.message_type,
|
||||
@@ -99,7 +151,7 @@ async function sendMessage (event: OB11Message, message: string, adapter: string
|
||||
try {
|
||||
await actions.call('send_msg', params, adapter, config);
|
||||
} catch (error) {
|
||||
console.error('[Plugin: builtin] 发送消息失败:', error);
|
||||
logger?.error('发送消息失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"description": "NapCat 内置插件",
|
||||
"author": "NapNeko",
|
||||
"dependencies": {
|
||||
"napcat-types": "0.0.3"
|
||||
"napcat-types": "0.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# Example Plugin
|
||||
## Install
|
||||
安装只需要将dist产物 `index.mjs` 目录放入 napcat根目录下`plugins/example`,如果没有这个目录请创建。
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { createActionMap } from 'napcat-types/dist/napcat-onebot/action/index.js';
|
||||
import { EventType } from 'napcat-types/dist/napcat-onebot/event/index.js';
|
||||
import type { PluginModule } from 'napcat-types/dist/napcat-onebot/network/plugin-manger';
|
||||
|
||||
/**
|
||||
* 导入 napcat 包时候不使用 @/napcat...,直接使用 napcat...
|
||||
* 因为 @/napcat... 会导致打包时包含整个 napcat 包,而不是只包含需要的部分
|
||||
*/
|
||||
|
||||
// action 作为参数传递时请用这个
|
||||
let actionMap: ReturnType<typeof createActionMap> | undefined = undefined;
|
||||
|
||||
const plugin_init: PluginModule['plugin_init'] = async (_core, _obContext, _actions, _instance) => {
|
||||
console.log('[Plugin: example] 插件已初始化');
|
||||
actionMap = _actions;
|
||||
};
|
||||
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (adapter, _core, _obCtx, event, actions, instance) => {
|
||||
if (event.post_type === EventType.MESSAGE && event.raw_message.includes('ping')) {
|
||||
await actions.get('send_group_msg')?.handle({ group_id: String(event.group_id), message: 'pong' }, adapter, instance.config);
|
||||
}
|
||||
};
|
||||
export { plugin_init, plugin_onmessage, actionMap };
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"name": "napcat-plugin",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
"description": "一个高级的 NapCat 插件示例",
|
||||
"dependencies": {
|
||||
"napcat-types": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "vite build"
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { resolve } from 'path';
|
||||
import nodeResolve from '@rollup/plugin-node-resolve';
|
||||
import { builtinModules } from 'module';
|
||||
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
conditions: ['node', 'default'],
|
||||
alias: {
|
||||
'@/napcat-core': resolve(__dirname, '../napcat-core'),
|
||||
'@': resolve(__dirname, '../'),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
sourcemap: false,
|
||||
target: 'esnext',
|
||||
minify: false,
|
||||
lib: {
|
||||
entry: 'index.ts',
|
||||
formats: ['es'],
|
||||
fileName: () => 'index.mjs',
|
||||
},
|
||||
rollupOptions: {
|
||||
external: [...nodeModules],
|
||||
},
|
||||
},
|
||||
plugins: [nodeResolve()],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "napcat-types",
|
||||
"version": "0.0.4",
|
||||
"version": "0.0.9",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"types": "./napcat-types/index.d.ts",
|
||||
|
||||
@@ -33,21 +33,20 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
|
||||
// 1. 整理已加载的插件
|
||||
for (const p of loadedPlugins) {
|
||||
// 计算 ID:需要回溯到加载时的入口信息
|
||||
// 对于已加载的插件,我们通过判断 pluginPath 是否等于根 pluginPath 来判断它是单文件还是目录
|
||||
const isFilePlugin = p.pluginPath === pluginManager.getPluginPath();
|
||||
const fsName = isFilePlugin ? path.basename(p.entryPath) : path.basename(p.pluginPath);
|
||||
const id = getPluginId(fsName, isFilePlugin);
|
||||
// Use dirname for map key (matches filesystem scan)
|
||||
const id = p.dirname;
|
||||
const fsName = p.dirname; // dirname is the actual filesystem directory name
|
||||
|
||||
loadedPluginMap.set(id, {
|
||||
name: p.packageJson?.name || p.name, // 优先使用 package.json 的 name
|
||||
name: p.name, // This is now package name (from packageJson.name || dirname)
|
||||
id: id,
|
||||
version: p.version || '0.0.0',
|
||||
description: p.packageJson?.description || '',
|
||||
author: p.packageJson?.author || '',
|
||||
status: 'active',
|
||||
filename: fsName, // 真实文件/目录名
|
||||
loadedName: p.name // 运行时注册的名称,用于重载/卸载
|
||||
loadedName: p.name, // 运行时注册的名称,用于重载/卸载 (package name)
|
||||
hasConfig: !!(p.module.plugin_config_schema || p.module.plugin_config_ui)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,67 +116,43 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
return sendSuccess(res, { plugins: allPlugins, pluginManagerNotFound: false });
|
||||
};
|
||||
|
||||
export const ReloadPluginHandler: RequestHandler = async (req, res) => {
|
||||
const { name } = req.body;
|
||||
// Note: we should probably accept ID or Name. But ReloadPlugin uses valid loaded name.
|
||||
// Let's stick to name for now, but be aware of ambiguity.
|
||||
if (!name) return sendError(res, 'Plugin Name is required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) {
|
||||
return sendError(res, '插件管理器未加载,请检查 plugins 目录是否存在');
|
||||
}
|
||||
|
||||
const success = await pluginManager.reloadPlugin(name);
|
||||
if (success) {
|
||||
return sendSuccess(res, { message: 'Reloaded successfully' });
|
||||
} else {
|
||||
return sendError(res, 'Failed to reload plugin');
|
||||
}
|
||||
};
|
||||
// ReloadPluginHandler removed
|
||||
|
||||
export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
|
||||
const { enable, filename } = req.body;
|
||||
// We Use filename / id to control config
|
||||
// Front-end should pass the 'filename' or 'id' as the key identifier
|
||||
const { enable, filename, name } = req.body;
|
||||
// filename is the directory name (used for fs checks)
|
||||
// name is the package name (used for plugin manager API, if provided)
|
||||
// We need to determine: which to use for setPluginStatus call
|
||||
|
||||
if (!filename) return sendError(res, 'Plugin Filename/ID is required');
|
||||
if (!filename && !name) return sendError(res, 'Plugin Filename or Name is required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) {
|
||||
return sendError(res, 'Plugin Manager not found');
|
||||
}
|
||||
|
||||
// Calculate ID from filename (remove ext if file)
|
||||
// Or just use the logic consistent with loadPlugins
|
||||
let id = filename;
|
||||
// If it has extension .js/.mjs, remove it to get the ID used in config
|
||||
if (filename.endsWith('.js') || filename.endsWith('.mjs')) {
|
||||
id = path.parse(filename).name;
|
||||
}
|
||||
// Determine which ID to use
|
||||
// If 'name' (package name) is provided, use it for pluginManager calls
|
||||
// But 'filename' (dirname) is needed for filesystem operations
|
||||
const dirname = filename || name; // fallback
|
||||
const pluginName = name || filename; // fallback
|
||||
|
||||
try {
|
||||
pluginManager.setPluginStatus(id, enable);
|
||||
// setPluginStatus now handles both package name and dirname lookup internally
|
||||
pluginManager.setPluginStatus(pluginName, enable);
|
||||
|
||||
// If enabling, trigger load
|
||||
if (enable) {
|
||||
const pluginPath = pluginManager.getPluginPath();
|
||||
const fullPath = path.join(pluginPath, filename);
|
||||
const fullPath = path.join(pluginPath, dirname);
|
||||
|
||||
if (fs.statSync(fullPath).isDirectory()) {
|
||||
await pluginManager.loadDirectoryPlugin(filename);
|
||||
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
|
||||
await pluginManager.loadDirectoryPlugin(dirname);
|
||||
} else {
|
||||
await pluginManager.loadFilePlugin(filename);
|
||||
return sendError(res, 'Plugin directory not found: ' + dirname);
|
||||
}
|
||||
} else {
|
||||
// Disabling is handled inside setPluginStatus usually if implemented,
|
||||
// OR we can explicitly unload here using the loaded name.
|
||||
// The Manager's setPluginStatus implementation (if added) might logic this out.
|
||||
// But our current Manager implementation just saves config.
|
||||
// Wait, I updated Manager to try to unload.
|
||||
// Let's rely on Manager's setPluginStatus or do it here?
|
||||
// I implemented a basic unload loop in Manager.setPluginStatus.
|
||||
}
|
||||
// Disabling is handled by setPluginStatus
|
||||
|
||||
return sendSuccess(res, { message: 'Status updated successfully' });
|
||||
} catch (e: any) {
|
||||
@@ -186,7 +161,7 @@ export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
|
||||
};
|
||||
|
||||
export const UninstallPluginHandler: RequestHandler = async (req, res) => {
|
||||
const { name, filename } = req.body;
|
||||
const { name, filename, cleanData } = req.body;
|
||||
// If it's loaded, we use name. If it's disabled, we might use filename.
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
@@ -219,8 +194,88 @@ export const UninstallPluginHandler: RequestHandler = async (req, res) => {
|
||||
if (fs.existsSync(fsPath)) {
|
||||
fs.rmSync(fsPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
if (cleanData && name) {
|
||||
const dataPath = pluginManager.getPluginDataPath(name);
|
||||
if (fs.existsSync(dataPath)) {
|
||||
fs.rmSync(dataPath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
return sendSuccess(res, { message: 'Uninstalled successfully' });
|
||||
} catch (e: any) {
|
||||
return sendError(res, 'Failed to uninstall: ' + e.message);
|
||||
}
|
||||
};
|
||||
|
||||
export const GetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
const name = req.query['name'] as string;
|
||||
if (!name) return sendError(res, 'Plugin Name is required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) return sendError(res, 'Plugin Manager not found');
|
||||
|
||||
const plugin = pluginManager.getPluginInfo(name);
|
||||
if (!plugin) return sendError(res, 'Plugin not loaded');
|
||||
|
||||
// Support legacy schema or new API
|
||||
const schema = plugin.module.plugin_config_schema || plugin.module.plugin_config_ui;
|
||||
let config = {};
|
||||
|
||||
if (plugin.module.plugin_get_config) {
|
||||
try {
|
||||
config = await plugin.module.plugin_get_config(plugin.context);
|
||||
} catch (e) { }
|
||||
} else if (schema) {
|
||||
// Default behavior: read from default config path
|
||||
try {
|
||||
// Use context configPath if available
|
||||
const configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(name);
|
||||
if (fs.existsSync(configPath)) {
|
||||
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
return sendSuccess(res, { schema, config });
|
||||
};
|
||||
|
||||
export const SetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
const { name, config } = req.body;
|
||||
if (!name || !config) return sendError(res, 'Name and Config required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) return sendError(res, 'Plugin Manager not found');
|
||||
|
||||
const plugin = pluginManager.getPluginInfo(name);
|
||||
if (!plugin) return sendError(res, 'Plugin not loaded');
|
||||
|
||||
if (plugin.module.plugin_set_config) {
|
||||
try {
|
||||
await plugin.module.plugin_set_config(plugin.context, config);
|
||||
return sendSuccess(res, { message: 'Config updated' });
|
||||
} catch (e: any) {
|
||||
return sendError(res, 'Error updating config: ' + e.message);
|
||||
}
|
||||
} else if (plugin.module.plugin_config_schema || plugin.module.plugin_config_ui) {
|
||||
// Default behavior: write to default config path
|
||||
try {
|
||||
const configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(name);
|
||||
|
||||
const configDir = path.dirname(configPath);
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||
|
||||
// Auto-Reload plugin to apply changes
|
||||
await pluginManager.reloadPlugin(name);
|
||||
|
||||
return sendSuccess(res, { message: 'Config saved and plugin reloaded' });
|
||||
} catch (e: any) {
|
||||
return sendError(res, 'Error saving config: ' + e.message);
|
||||
}
|
||||
} else {
|
||||
return sendError(res, 'Plugin does not support config update');
|
||||
}
|
||||
};
|
||||
@@ -1,13 +1,25 @@
|
||||
import { Router } from 'express';
|
||||
import { GetPluginListHandler, ReloadPluginHandler, SetPluginStatusHandler, UninstallPluginHandler } from '@/napcat-webui-backend/src/api/Plugin';
|
||||
import { GetPluginStoreListHandler, GetPluginStoreDetailHandler, InstallPluginFromStoreHandler, InstallPluginFromStoreSSEHandler } from '@/napcat-webui-backend/src/api/PluginStore';
|
||||
import {
|
||||
GetPluginListHandler,
|
||||
SetPluginStatusHandler,
|
||||
UninstallPluginHandler,
|
||||
GetPluginConfigHandler,
|
||||
SetPluginConfigHandler
|
||||
} from '@/napcat-webui-backend/src/api/Plugin';
|
||||
import {
|
||||
GetPluginStoreListHandler,
|
||||
GetPluginStoreDetailHandler,
|
||||
InstallPluginFromStoreHandler,
|
||||
InstallPluginFromStoreSSEHandler
|
||||
} from '@/napcat-webui-backend/src/api/PluginStore';
|
||||
|
||||
const router: Router = Router();
|
||||
|
||||
router.get('/List', GetPluginListHandler);
|
||||
router.post('/Reload', ReloadPluginHandler);
|
||||
router.post('/SetStatus', SetPluginStatusHandler);
|
||||
router.post('/Uninstall', UninstallPluginHandler);
|
||||
router.get('/Config', GetPluginConfigHandler);
|
||||
router.post('/Config', SetPluginConfigHandler);
|
||||
|
||||
// 插件商店相关路由
|
||||
router.get('/Store/List', GetPluginStoreListHandler);
|
||||
|
||||
@@ -3,23 +3,25 @@ import { Switch } from '@heroui/switch';
|
||||
import { Chip } from '@heroui/chip';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { MdDeleteForever, MdPublishedWithChanges } from 'react-icons/md';
|
||||
import { MdDeleteForever, MdSettings } from 'react-icons/md';
|
||||
|
||||
import DisplayCardContainer from './container';
|
||||
import { PluginItem } from '@/controllers/plugin_manager';
|
||||
|
||||
export interface PluginDisplayCardProps {
|
||||
data: PluginItem;
|
||||
onReload: () => Promise<void>;
|
||||
onToggleStatus: () => Promise<void>;
|
||||
onUninstall: () => Promise<void>;
|
||||
onConfig?: () => void;
|
||||
hasConfig?: boolean;
|
||||
}
|
||||
|
||||
const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
|
||||
data,
|
||||
onReload,
|
||||
onToggleStatus,
|
||||
onUninstall,
|
||||
onConfig,
|
||||
hasConfig = false,
|
||||
}) => {
|
||||
const { name, version, author, description, status } = data;
|
||||
const isEnabled = status !== 'disabled';
|
||||
@@ -30,11 +32,6 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
|
||||
onToggleStatus().finally(() => setProcessing(false));
|
||||
};
|
||||
|
||||
const handleReload = () => {
|
||||
setProcessing(true);
|
||||
onReload().finally(() => setProcessing(false));
|
||||
};
|
||||
|
||||
const handleUninstall = () => {
|
||||
setProcessing(true);
|
||||
onUninstall().finally(() => setProcessing(false));
|
||||
@@ -44,32 +41,34 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
|
||||
<DisplayCardContainer
|
||||
className='w-full max-w-[420px]'
|
||||
action={
|
||||
<div className='flex gap-2 w-full'>
|
||||
<Button
|
||||
fullWidth
|
||||
radius='full'
|
||||
size='sm'
|
||||
variant='flat'
|
||||
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-primary/20 hover:text-primary transition-colors'
|
||||
startContent={<MdPublishedWithChanges size={16} />}
|
||||
onPress={handleReload}
|
||||
isDisabled={!isEnabled || processing}
|
||||
>
|
||||
重载
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
fullWidth
|
||||
radius='full'
|
||||
size='sm'
|
||||
variant='flat'
|
||||
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-danger/20 hover:text-danger transition-colors'
|
||||
startContent={<MdDeleteForever size={16} />}
|
||||
onPress={handleUninstall}
|
||||
isDisabled={processing}
|
||||
>
|
||||
卸载
|
||||
</Button>
|
||||
<div className='flex flex-col gap-2 w-full'>
|
||||
<div className='flex gap-2 w-full'>
|
||||
<Button
|
||||
fullWidth
|
||||
radius='full'
|
||||
size='sm'
|
||||
variant='flat'
|
||||
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-danger/20 hover:text-danger transition-colors'
|
||||
startContent={<MdDeleteForever size={16} />}
|
||||
onPress={handleUninstall}
|
||||
isDisabled={processing}
|
||||
>
|
||||
卸载
|
||||
</Button>
|
||||
</div>
|
||||
{hasConfig && (
|
||||
<Button
|
||||
fullWidth
|
||||
radius='full'
|
||||
size='sm'
|
||||
variant='flat'
|
||||
className='bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-secondary/20 hover:text-secondary transition-colors'
|
||||
startContent={<MdSettings size={16} />}
|
||||
onPress={onConfig}
|
||||
>
|
||||
配置
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
enableSwitch={
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface PluginItem {
|
||||
author: string;
|
||||
status: 'active' | 'disabled' | 'stopped';
|
||||
filename?: string;
|
||||
hasConfig?: boolean;
|
||||
}
|
||||
|
||||
export interface PluginListResponse {
|
||||
@@ -15,6 +16,21 @@ export interface PluginListResponse {
|
||||
pluginManagerNotFound: boolean;
|
||||
}
|
||||
|
||||
export interface PluginConfigSchemaItem {
|
||||
key: string;
|
||||
type: 'string' | 'number' | 'boolean' | 'select' | 'multi-select' | 'html' | 'text';
|
||||
label: string;
|
||||
description?: string;
|
||||
default?: any;
|
||||
options?: { label: string; value: string | number; }[];
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export interface PluginConfigResponse {
|
||||
schema: PluginConfigSchemaItem[];
|
||||
config: any;
|
||||
}
|
||||
|
||||
export interface ServerResponse<T> {
|
||||
code: number;
|
||||
message: string;
|
||||
@@ -27,16 +43,14 @@ export default class PluginManager {
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async reloadPlugin (name: string) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Reload', { name });
|
||||
}
|
||||
|
||||
|
||||
public static async setPluginStatus (name: string, enable: boolean, filename?: string) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/SetStatus', { name, enable, filename });
|
||||
}
|
||||
|
||||
public static async uninstallPlugin (name: string, filename?: string) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { name, filename });
|
||||
public static async uninstallPlugin (name: string, filename?: string, cleanData?: boolean) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { name, filename, cleanData });
|
||||
}
|
||||
|
||||
// 插件商店相关方法
|
||||
@@ -56,4 +70,14 @@ export default class PluginManager {
|
||||
timeout: 300000, // 5分钟
|
||||
});
|
||||
}
|
||||
|
||||
// 插件配置相关方法
|
||||
public static async getPluginConfig (name: string) {
|
||||
const { data } = await serverRequest.get<ServerResponse<PluginConfigResponse>>('/Plugin/Config', { params: { name } });
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async setPluginConfig (name: string, config: any) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Config', { name, config });
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@ import { Button } from '@heroui/button';
|
||||
import { useEffect, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { IoMdRefresh } from 'react-icons/io';
|
||||
import { useDisclosure } from '@heroui/modal';
|
||||
|
||||
import PageLoading from '@/components/page_loading';
|
||||
import PluginDisplayCard from '@/components/display_card/plugin_card';
|
||||
import PluginManager, { PluginItem } from '@/controllers/plugin_manager';
|
||||
import useDialog from '@/hooks/use-dialog';
|
||||
import PluginConfigModal from '@/pages/dashboard/plugin_config_modal';
|
||||
|
||||
export default function PluginPage () {
|
||||
const [plugins, setPlugins] = useState<PluginItem[]>([]);
|
||||
@@ -14,16 +16,20 @@ export default function PluginPage () {
|
||||
const [pluginManagerNotFound, setPluginManagerNotFound] = useState(false);
|
||||
const dialog = useDialog();
|
||||
|
||||
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
||||
const [currentPluginName, setCurrentPluginName] = useState<string>('');
|
||||
|
||||
const loadPlugins = async () => {
|
||||
setLoading(true);
|
||||
setPluginManagerNotFound(false);
|
||||
try {
|
||||
const result = await PluginManager.getPluginList();
|
||||
if (result.pluginManagerNotFound) {
|
||||
const listResult = await PluginManager.getPluginList();
|
||||
|
||||
if (listResult.pluginManagerNotFound) {
|
||||
setPluginManagerNotFound(true);
|
||||
setPlugins([]);
|
||||
} else {
|
||||
setPlugins(result.plugins);
|
||||
setPlugins(listResult.plugins);
|
||||
}
|
||||
} catch (e: any) {
|
||||
toast.error(e.message);
|
||||
@@ -36,16 +42,7 @@ export default function PluginPage () {
|
||||
loadPlugins();
|
||||
}, []);
|
||||
|
||||
const handleReload = async (name: string) => {
|
||||
const loadingToast = toast.loading('重载中...');
|
||||
try {
|
||||
await PluginManager.reloadPlugin(name);
|
||||
toast.success('重载成功', { id: loadingToast });
|
||||
loadPlugins();
|
||||
} catch (e: any) {
|
||||
toast.error(e.message, { id: loadingToast });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const handleToggle = async (plugin: PluginItem) => {
|
||||
const isEnable = plugin.status !== 'active';
|
||||
@@ -64,11 +61,31 @@ export default function PluginPage () {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
dialog.confirm({
|
||||
title: '卸载插件',
|
||||
content: `确定要卸载插件「${plugin.name}」吗? 此操作不可恢复。`,
|
||||
content: (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p>确定要卸载插件「{plugin.name}」吗? 此操作不可恢复。</p>
|
||||
<p className="text-small text-default-500">如果插件创建了数据文件,是否一并删除?</p>
|
||||
</div>
|
||||
),
|
||||
// This 'dialog' utility might not support returning a value from UI interacting.
|
||||
// We might need to implement a custom confirmation flow if we want a checkbox.
|
||||
// Alternatively, use two buttons? "Uninstall & Clean", "Uninstall Only"?
|
||||
// Standard dialog usually has Confirm/Cancel.
|
||||
// Let's stick to a simpler "Uninstall" and then maybe a second prompt? Or just clean data?
|
||||
// User requested: "Uninstall prompts whether to clean data".
|
||||
// Let's use `window.confirm` for the second step or assume `dialog.confirm` is flexible enough?
|
||||
// I will implement a two-step confirmation or try to modify the dialog hook if visible (not visible here).
|
||||
// Let's use a standard `window.confirm` for the data cleanup question if the custom dialog doesn't support complex return.
|
||||
// Better: Inside onConfirm, ask again?
|
||||
onConfirm: async () => {
|
||||
// Ask for data cleanup
|
||||
// Since we are in an async callback, we can use another dialog or confirm.
|
||||
// Native confirm is ugly but works reliably for logic:
|
||||
const cleanData = window.confirm(`是否同时清理插件「${plugin.name}」的数据文件?\n点击“确定”清理数据,点击“取消”仅卸载插件。`);
|
||||
|
||||
const loadingToast = toast.loading('卸载中...');
|
||||
try {
|
||||
await PluginManager.uninstallPlugin(plugin.name, plugin.filename);
|
||||
await PluginManager.uninstallPlugin(plugin.name, plugin.filename, cleanData);
|
||||
toast.success('卸载成功', { id: loadingToast });
|
||||
loadPlugins();
|
||||
resolve();
|
||||
@@ -84,11 +101,22 @@ export default function PluginPage () {
|
||||
});
|
||||
};
|
||||
|
||||
const handleConfig = (plugin: PluginItem) => {
|
||||
setCurrentPluginName(plugin.name); // Use Loaded Name for config lookup
|
||||
onOpen();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<title>插件管理 - NapCat WebUI</title>
|
||||
<div className='p-2 md:p-4 relative'>
|
||||
<PageLoading loading={loading} />
|
||||
<PluginConfigModal
|
||||
isOpen={isOpen}
|
||||
onOpenChange={onOpenChange}
|
||||
pluginName={currentPluginName}
|
||||
/>
|
||||
|
||||
<div className='flex mb-6 items-center gap-4'>
|
||||
<h1 className="text-2xl font-bold">插件管理</h1>
|
||||
<Button
|
||||
@@ -119,9 +147,16 @@ export default function PluginPage () {
|
||||
<PluginDisplayCard
|
||||
key={plugin.name}
|
||||
data={plugin}
|
||||
onReload={() => handleReload(plugin.name)}
|
||||
onToggleStatus={() => handleToggle(plugin)}
|
||||
onUninstall={() => handleUninstall(plugin)}
|
||||
onConfig={() => {
|
||||
if (plugin.hasConfig) {
|
||||
handleConfig(plugin);
|
||||
} else {
|
||||
toast.error('此插件没有配置哦');
|
||||
}
|
||||
}}
|
||||
hasConfig={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter } from '@heroui/modal';
|
||||
import { Button } from '@heroui/button';
|
||||
import { Input } from '@heroui/input';
|
||||
import { Select, SelectItem } from '@heroui/select';
|
||||
import { Switch } from '@heroui/switch';
|
||||
import { useEffect, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import PluginManager, { PluginConfigSchemaItem } from '@/controllers/plugin_manager';
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
onOpenChange: () => void;
|
||||
pluginName: string;
|
||||
}
|
||||
|
||||
export default function PluginConfigModal ({ isOpen, onOpenChange, pluginName }: Props) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [schema, setSchema] = useState<PluginConfigSchemaItem[]>([]);
|
||||
const [config, setConfig] = useState<any>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && pluginName) {
|
||||
loadConfig();
|
||||
}
|
||||
}, [isOpen, pluginName]);
|
||||
|
||||
const loadConfig = async () => {
|
||||
setLoading(true);
|
||||
setSchema([]);
|
||||
setConfig({});
|
||||
try {
|
||||
const data = await PluginManager.getPluginConfig(pluginName);
|
||||
setSchema(data.schema || []);
|
||||
setConfig(data.config || {});
|
||||
} catch (e: any) {
|
||||
toast.error('Load config failed: ' + e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await PluginManager.setPluginConfig(pluginName, config);
|
||||
toast.success('Configuration saved');
|
||||
onOpenChange();
|
||||
} catch (e: any) {
|
||||
toast.error('Save failed: ' + e.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const updateConfig = (key: string, value: any) => {
|
||||
setConfig((prev: any) => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const renderField = (item: PluginConfigSchemaItem) => {
|
||||
const value = config[item.key] ?? item.default;
|
||||
|
||||
switch (item.type) {
|
||||
case 'string':
|
||||
return (
|
||||
<Input
|
||||
key={item.key}
|
||||
label={item.label}
|
||||
placeholder={item.placeholder || item.description}
|
||||
value={value || ''}
|
||||
onValueChange={(val) => updateConfig(item.key, val)}
|
||||
description={item.description}
|
||||
className="mb-4"
|
||||
/>
|
||||
);
|
||||
case 'number':
|
||||
return (
|
||||
<Input
|
||||
key={item.key}
|
||||
type="number"
|
||||
label={item.label}
|
||||
placeholder={item.placeholder || item.description}
|
||||
value={String(value ?? 0)}
|
||||
onValueChange={(val) => updateConfig(item.key, Number(val))}
|
||||
description={item.description}
|
||||
className="mb-4"
|
||||
/>
|
||||
);
|
||||
case 'boolean':
|
||||
return (
|
||||
<div key={item.key} className="flex justify-between items-center mb-4 p-2 bg-default-100 rounded-lg">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-small">{item.label}</span>
|
||||
{item.description && <span className="text-tiny text-default-500">{item.description}</span>}
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={!!value}
|
||||
onValueChange={(val) => updateConfig(item.key, val)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
case 'select':
|
||||
// Handle value matching for default selected keys
|
||||
const selectedValue = value !== undefined ? String(value) : undefined;
|
||||
return (
|
||||
<Select
|
||||
key={item.key}
|
||||
label={item.label}
|
||||
placeholder={item.placeholder || 'Select an option'}
|
||||
selectedKeys={selectedValue ? [selectedValue] : []}
|
||||
onSelectionChange={(keys) => {
|
||||
const val = Array.from(keys)[0];
|
||||
// Map back to value
|
||||
const opt = item.options?.find(o => String(o.value) === val);
|
||||
updateConfig(item.key, opt ? opt.value : val);
|
||||
}}
|
||||
description={item.description}
|
||||
className="mb-4"
|
||||
>
|
||||
{(item.options || []).map((opt) => (
|
||||
<SelectItem key={String(opt.value)} textValue={opt.label}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
case 'multi-select':
|
||||
const selectedKeys = Array.isArray(value) ? value.map(String) : [];
|
||||
return (
|
||||
<Select
|
||||
key={item.key}
|
||||
label={item.label}
|
||||
placeholder={item.placeholder || 'Select options'}
|
||||
selectionMode="multiple"
|
||||
selectedKeys={new Set(selectedKeys)}
|
||||
onSelectionChange={(keys) => {
|
||||
const selected = Array.from(keys).map(k => {
|
||||
const opt = item.options?.find(o => String(o.value) === k);
|
||||
return opt ? opt.value : k;
|
||||
});
|
||||
updateConfig(item.key, selected);
|
||||
}}
|
||||
description={item.description}
|
||||
className="mb-4"
|
||||
>
|
||||
{(item.options || []).map((opt) => (
|
||||
<SelectItem key={String(opt.value)} textValue={opt.label}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
case 'html':
|
||||
return (
|
||||
<div key={item.key} className="mb-4">
|
||||
{item.label && <h4 className="text-small font-bold mb-1">{item.label}</h4>}
|
||||
<div dangerouslySetInnerHTML={{ __html: item.default || '' }} className="prose dark:prose-invert max-w-none" />
|
||||
{item.description && <p className="text-tiny text-default-500 mt-1">{item.description}</p>}
|
||||
</div>
|
||||
);
|
||||
case 'text':
|
||||
return (
|
||||
<div key={item.key} className="mb-4">
|
||||
{item.label && <h4 className="text-small font-bold mb-1">{item.label}</h4>}
|
||||
<div className="whitespace-pre-wrap text-default-700">{item.default || ''}</div>
|
||||
{item.description && <p className="text-tiny text-default-500 mt-1">{item.description}</p>}
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onOpenChange={onOpenChange} size="2xl" scrollBehavior="inside">
|
||||
<ModalContent>
|
||||
{(onClose) => (
|
||||
<>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
Configuration: {pluginName}
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
{loading ? (
|
||||
<div className="flex justify-center p-8">Loading configuration...</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{schema.length === 0 ? (
|
||||
<div className="text-center text-default-500">No configuration schema available.</div>
|
||||
) : (
|
||||
schema.map(renderField)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button color="danger" variant="light" onPress={onClose}>
|
||||
Close
|
||||
</Button>
|
||||
<Button color="primary" onPress={handleSave} isLoading={saving}>
|
||||
Save
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</>
|
||||
)}
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
Generated
+6
-15
@@ -210,21 +210,11 @@ importers:
|
||||
specifier: ^1.6.7
|
||||
version: 1.6.7
|
||||
|
||||
packages/napcat-plugin:
|
||||
dependencies:
|
||||
napcat-types:
|
||||
specifier: workspace:*
|
||||
version: link:../napcat-types
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.1
|
||||
version: 22.19.1
|
||||
|
||||
packages/napcat-plugin-builtin:
|
||||
dependencies:
|
||||
napcat-types:
|
||||
specifier: 0.0.3
|
||||
version: 0.0.3
|
||||
specifier: 0.0.9
|
||||
version: 0.0.9
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.1
|
||||
@@ -5448,8 +5438,8 @@ packages:
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
|
||||
napcat-types@0.0.3:
|
||||
resolution: {integrity: sha512-YZVBvtIw7N2TRck+JcVAoZJRqcoKf9PbKhHggZ/EcQzTkqGLgu8iIgMfQnCYscgXRglYBPexpb78piaEwlVcjQ==}
|
||||
napcat-types@0.0.9:
|
||||
resolution: {integrity: sha512-lhK9SgGotQc58jobqnZEnDTadwcwT/Y62aGCH4hQijdiP2eSiu3YWX2oFFoUJxyIpUKFYAfWJkPUv1YHZ/aaWQ==}
|
||||
|
||||
napcat.protobuf@1.1.4:
|
||||
resolution: {integrity: sha512-z7XtLSBJ/PxmYb0VD/w+eYr/X3LyGz+SZ2QejFTOczwt6zWNxy2yV1mTMTvJoc3BWkI3ESVFRxkuT6+pj1tb1Q==}
|
||||
@@ -12819,8 +12809,9 @@ snapshots:
|
||||
|
||||
nanoid@3.3.11: {}
|
||||
|
||||
napcat-types@0.0.3:
|
||||
napcat-types@0.0.9:
|
||||
dependencies:
|
||||
'@sinclair/typebox': 0.34.41
|
||||
'@types/cors': 2.8.19
|
||||
'@types/express': 4.17.25
|
||||
'@types/ip': 1.1.3
|
||||
|
||||
Reference in new issue
Block a user