Compare commits

...
18 Commits
Author SHA1 Message Date
手瓜一十雪 001fe01ace Add plugin logger interface and update builtin plugin
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduces a PluginLogger interface and injects a plugin-specific logger into the plugin context for consistent logging. Refactors the builtin plugin to use the new logger instead of direct console calls. Updates napcat-types to version 0.0.9 in dependencies and lock files.
2026-01-28 15:07:06 +08:00
手瓜一十雪 0aa0c44634 Refactor plugin identification to use package name and dirname
Updated plugin manager and API to distinguish between plugin package name and directory name (dirname) for more robust plugin identification and path resolution. Adjusted context creation, status management, and API handlers to use package name for identification and dirname for filesystem operations. Also replaced console.error with console.log in builtin plugin for consistency.
2026-01-28 15:02:47 +08:00
手瓜一十雪 93126e514e Refactor builtin plugin for improved type safety
Replaced generic 'any' types with 'NetworkAdapterConfig' for better type safety in getVersionInfo and sendMessage functions. Removed redundant comments and improved code clarity. Changed a warning log to a standard log for config load failures.
2026-01-28 14:54:43 +08:00
手瓜一十雪 1ae10ae0c6 Refactor plugin to use context actions and update deps
Refactored the builtin plugin to pass actions and adapterName explicitly from context instead of relying on a global variable. Updated napcat-types dependency to version 0.0.8.
2026-01-28 14:42:44 +08:00
手瓜一十雪 4b693bf6e2 Refactor plugin manager to support only directory plugins
Removed support for single-file plugins in OB11PluginMangerAdapter, simplifying plugin identification to use directory names as unique IDs. Updated related logic in the backend API to align with this change, ensuring consistent plugin management and status handling.
2026-01-28 14:38:11 +08:00
手瓜一十雪 574c257591 Refactor plugin manager to support only directory plugins
Removed support for single-file plugins in OB11PluginMangerAdapter, simplifying plugin identification to use directory names as unique IDs. Updated related logic in the backend API to align with this change, ensuring consistent plugin management and status handling.
2026-01-28 14:18:44 +08:00
手瓜一十雪 d680328762 Add config UI and persistence to builtin plugin
Introduces a configuration UI schema and persistent config storage for the napcat-plugin-builtin. The plugin now loads and saves its configuration, supports dynamic prefix and reply toggling, and updates dependencies to napcat-types v0.0.6.
2026-01-28 14:13:48 +08:00
手瓜一十雪 d711cdecaf Add plugin config management to backend and frontend
Introduces a unified plugin configuration schema and API in the backend, with endpoints for getting and setting plugin config. Updates the frontend to support plugin config modals, including a UI for editing plugin settings. Also adds support for uninstalling plugins with optional data cleanup, and updates dependencies to use napcat-types@0.0.5.
2026-01-28 13:56:40 +08:00
手瓜一十雪 c5f1792009 Add plugin data management API and frontend support
Introduced backend API endpoints for managing plugin configuration data, including listing, reading, saving, and deleting plugin data files. Added a new PluginData API module and registered related routes. Updated the frontend plugin manager controller to support these new API methods and corresponding TypeScript interfaces. Also fixed minor typos in documentation prompts.
2026-01-28 13:39:36 +08:00
手瓜一十雪 a5e705e6a4 Fix typo in Windows deployment instructions
Corrected a grammatical error in the Windows one-click deployment section in both the default prompt and release note prompt files.
2026-01-27 23:01:16 +08:00
手瓜一十雪 007f1db339 Update OpenAPI schema copy path in release workflow
The workflow now copies openapi.json from the dist directory instead of the package root, ensuring the built schema is used during the release process.
2026-01-27 23:00:14 +08:00
手瓜一十雪 008fb39f8f Reduce WebSocket maxPayload to 50 MB
Lowered the maxPayload limit from 1 GB to 50 MB in both the WebSocket client and server adapters to improve resource management and prevent excessively large payloads.
2026-01-27 22:56:27 +08:00
手瓜一十雪 6b8cc6756d Add plugin install SSE API and mirror selection UI
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduces a new SSE-based plugin installation API for real-time progress updates and adds frontend support for selecting download mirrors, especially for GitHub-based plugins. Refactors backend plugin directory handling, improves logging, and updates the frontend to use the new API with user-selectable mirrors and progress feedback.
2026-01-27 22:51:45 +08:00
手瓜一十雪 24623f18d8 Implement real plugin store backend and install logic
Replaces mock plugin store data with live fetching from a remote source using mirrors and caching. Implements actual plugin download, extraction, and installation logic in the backend. Updates frontend to call the new install API and display installation results, and removes unused icon/rating display from plugin cards.
2026-01-27 22:03:47 +08:00
手瓜一十雪 8b676ed693 Refactor plugin store types and update category logic
Simplified PluginStoreItem types by removing unused fields and standardizing the minimum version property. Updated frontend plugin store page to use new categories ('官方', '工具', '娱乐', '其它') instead of download-based sorting, aligning with the revised type definitions.
2026-01-27 21:47:44 +08:00
手瓜一十雪 ab2dfcfd8f Update dependencies in pnpm-lock.yaml
Added @sinclair/typebox to packages/napcat-types dependencies.
2026-01-27 21:31:31 +08:00
手瓜一十雪 2998e04435 Add @sinclair/typebox as dependency and remove shim
Removed the manual TypeBox type definitions from external-shims.d.ts and added @sinclair/typebox as a dependency in package.json and package.public.json. Bumped package version to 0.0.4 to reflect this change.
2026-01-27 21:24:50 +08:00
手瓜一十雪 613690f5af Fix build:openapi script to use sequential commands
Replaces '&' with '&&' in the build:openapi script to ensure that 'node ./dist/schemas.mjs' runs only after 'vite build' completes successfully.
2026-01-27 20:34:21 +08:00
36 changed files with 1179 additions and 700 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们为提供了的轻量化一键部署方案
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
+1 -1
View File
@@ -31,7 +31,7 @@
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们为提供了的轻量化一键部署方案
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
+1 -1
View File
@@ -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
-24
View File
@@ -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"
}
}
+9 -21
View File
@@ -383,17 +383,14 @@ export async function testUrlHead (url: string, timeout: number = 5000): Promise
}, (res) => {
const statusCode = res.statusCode || 0;
const contentType = (res.headers['content-type'] as string) || '';
const contentLength = parseInt((res.headers['content-length'] as string) || '0', 10);
// 验证条件:
// 简化验证条件:
// 1. 状态码 2xx 或 3xx
// 2. Content-Type 不应该是 text/html(表示错误页面)
// 3. 对于 .zip 文件,Content-Length 应该 > 1MB(避免获取到错误页面)
const isValidStatus = statusCode >= 200 && statusCode < 400;
const isNotHtmlError = !contentType.includes('text/html');
const isValidSize = url.endsWith('.zip') ? contentLength > 1024 * 1024 : true;
resolve(isValidStatus && isNotHtmlError && isValidSize);
resolve(isValidStatus && isNotHtmlError);
});
req.on('error', () => resolve(false));
@@ -437,10 +434,9 @@ export async function validateUrl (url: string, timeout: number = 5000): Promise
const contentType = (res.headers['content-type'] as string) || '';
const contentLength = parseInt((res.headers['content-length'] as string) || '0', 10);
// 验证条件
// 简化验证条件
const isValidStatus = statusCode >= 200 && statusCode < 400;
const isNotHtmlError = !contentType.includes('text/html');
const isValidSize = url.endsWith('.zip') ? contentLength > 1024 * 1024 : true;
if (!isValidStatus) {
resolve({
@@ -458,14 +454,6 @@ export async function validateUrl (url: string, timeout: number = 5000): Promise
contentLength,
error: '返回了 HTML 页面而非文件',
});
} else if (!isValidSize) {
resolve({
valid: false,
statusCode,
contentType,
contentLength,
error: `文件过小 (${contentLength} bytes),可能是错误页面`,
});
} else {
resolve({
valid: true,
@@ -542,21 +530,21 @@ export async function findAvailableDownloadUrl (
const testWithValidation = async (url: string): Promise<boolean> => {
if (validateContent) {
const result = await validateUrl(url, timeout);
// 额外检查文件大小
// 额外检查文件大小(仅当指定了 minFileSize 时)
if (result.valid && minFileSize && result.contentLength && result.contentLength < minFileSize) {
return false;
}
return result.valid;
}
return testMethod === 'head' ? testUrlHead(url, timeout) : testUrl(url, timeout);
// 不验证内容,只检查状态码
const isValid = testMethod === 'head' ? await testUrlHead(url, timeout) : await testUrl(url, timeout);
return isValid;
};
// 1. 如果设置了自定义镜像,优先使用
// 1. 如果设置了自定义镜像,直接使用(不测试,信任用户选择)
if (customMirror) {
const customUrl = buildMirrorUrl(originalUrl, customMirror);
if (await testWithValidation(customUrl)) {
return customUrl;
}
return customUrl;
}
// 2. 先测试原始 URL
@@ -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',
+170 -183
View File
@@ -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) {
+89 -37
View File
@@ -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);
}
}
+1 -1
View File
@@ -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"
@@ -5,7 +5,8 @@ import { builtinModules } from 'module';
import fs from 'fs';
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
// 依赖排除
const external = [];
// 构建后拷贝插件
function copyToShellPlugin () {
return {
@@ -68,7 +69,10 @@ export default defineConfig({
entry: 'index.ts',
formats: ['es'],
fileName: () => 'index.mjs',
}
},
rollupOptions: {
external: [...nodeModules, ...external],
},
},
plugins: [nodeResolve(), copyToShellPlugin()],
});
-3
View File
@@ -1,3 +0,0 @@
# Example Plugin
## Install
安装只需要将dist产物 `index.mjs` 目录放入 napcat根目录下`plugins/example`,如果没有这个目录请创建。
-22
View File
@@ -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 };
-16
View File
@@ -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"
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": [
"*.ts",
"**/*.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
-30
View File
@@ -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 -1
View File
@@ -5,7 +5,7 @@
"type": "module",
"main": "index.ts",
"scripts": {
"build:openapi": "vite build & node ./dist/schemas.mjs"
"build:openapi": "vite build && node ./dist/schemas.mjs"
},
"dependencies": {
"@sinclair/typebox": "^0.34.38",
-32
View File
@@ -75,38 +75,6 @@ declare module 'async-mutex' {
export default _async_mutex_default;
}
declare module '@sinclair/typebox' {
export const Type: {
Object: (...args: any[]) => any;
String: (...args: any[]) => any;
Number: (...args: any[]) => any;
Boolean: (...args: any[]) => any;
Array: (...args: any[]) => any;
Union: (...args: any[]) => any;
Literal: (...args: any[]) => any;
Optional: (...args: any[]) => any;
Record: (...args: any[]) => any;
Any: (...args: any[]) => any;
} & any;
// Make Static<> actually resolve to a structural type so optional properties work.
export type Static<T> = T extends { static: infer S; } ? S : any;
export interface TSchema { static?: any; }
export interface TObject<T = any> extends TSchema { }
export interface TOptional<T = any> extends TSchema { }
export interface TNumber extends TSchema { }
export interface TString extends TSchema { }
export interface TBoolean extends TSchema { }
export interface TArray<T = any> extends TSchema { }
export interface TUnion<T = any> extends TSchema { }
export interface TLiteral<T = any> extends TSchema { }
export interface TAny extends TSchema { }
export interface TNull extends TSchema { }
export interface TUndefined extends TSchema { }
export interface TVoid extends TSchema { }
}
declare module 'napcat-protobuf' {
export class NapProtoMsg<T = any> {
constructor (schema: any);
+2 -1
View File
@@ -20,7 +20,8 @@
"@types/multer": "^1.4.12",
"@types/winston": "^2.4.4",
"@types/yaml": "^1.9.7",
"@types/ip": "^1.1.3"
"@types/ip": "^1.1.3",
"@sinclair/typebox": "^0.34.38"
},
"devDependencies": {
"napcat-core": "workspace:*",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "napcat-types",
"version": "0.0.3",
"version": "0.0.9",
"private": false,
"type": "module",
"types": "./napcat-types/index.d.ts",
@@ -15,7 +15,8 @@
"@types/multer": "^1.4.12",
"@types/winston": "^2.4.4",
"@types/yaml": "^1.9.7",
"@types/ip": "^1.1.3"
"@types/ip": "^1.1.3",
"@sinclair/typebox": "^0.34.38"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
+105 -50
View File
@@ -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,126 +1,191 @@
import { RequestHandler } from 'express';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { PluginStoreList } from '@/napcat-webui-backend/src/types/PluginStore';
import * as fs from 'fs';
import * as path from 'path';
import { pipeline } from 'stream/promises';
import { createWriteStream } from 'fs';
import compressing from 'compressing';
import { findAvailableDownloadUrl, GITHUB_RAW_MIRRORS } from 'napcat-common/src/mirror';
import { webUiPathWrapper } from '@/napcat-webui-backend/index';
// Mock数据 - 模拟远程插件列表
const mockPluginStoreData: PluginStoreList = {
version: '1.0.0',
updateTime: new Date().toISOString(),
plugins: [
{
id: 'napcat-plugin-example',
name: '示例插件',
version: '1.0.0',
description: '这是一个示例插件,展示如何开发NapCat插件',
author: 'NapCat Team',
homepage: 'https://github.com/NapNeko/NapCatQQ',
repository: 'https://github.com/NapNeko/NapCatQQ',
downloadUrl: 'https://example.com/plugins/napcat-plugin-example-1.0.0.zip',
tags: ['示例', '教程'],
screenshots: ['https://picsum.photos/800/600?random=1'],
minNapCatVersion: '1.0.0',
downloads: 1234,
rating: 4.5,
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-20T00:00:00Z',
},
{
id: 'napcat-plugin-auto-reply',
name: '自动回复插件',
version: '2.1.0',
description: '支持关键词匹配的自动回复功能,可配置多种回复规则',
author: 'Community',
homepage: 'https://github.com/example/auto-reply',
repository: 'https://github.com/example/auto-reply',
downloadUrl: 'https://example.com/plugins/napcat-plugin-auto-reply-2.1.0.zip',
tags: ['自动回复', '消息处理'],
minNapCatVersion: '1.0.0',
downloads: 5678,
rating: 4.8,
createdAt: '2024-01-05T00:00:00Z',
updatedAt: '2024-01-22T00:00:00Z',
},
{
id: 'napcat-plugin-welcome',
name: '入群欢迎插件',
version: '1.2.3',
description: '新成员入群时自动发送欢迎消息,支持自定义欢迎语',
author: 'Developer',
homepage: 'https://github.com/example/welcome',
repository: 'https://github.com/example/welcome',
downloadUrl: 'https://example.com/plugins/napcat-plugin-welcome-1.2.3.zip',
tags: ['欢迎', '群管理'],
minNapCatVersion: '1.0.0',
downloads: 3456,
rating: 4.3,
createdAt: '2024-01-10T00:00:00Z',
updatedAt: '2024-01-18T00:00:00Z',
},
{
id: 'napcat-plugin-music',
name: '音乐点歌插件',
version: '3.0.1',
description: '支持网易云、QQ音乐等平台的点歌功能',
author: 'Music Lover',
homepage: 'https://github.com/example/music',
repository: 'https://github.com/example/music',
downloadUrl: 'https://example.com/plugins/napcat-plugin-music-3.0.1.zip',
tags: ['音乐', '娱乐'],
screenshots: ['https://picsum.photos/800/600?random=4', 'https://picsum.photos/800/600?random=5'],
minNapCatVersion: '1.1.0',
downloads: 8901,
rating: 4.9,
createdAt: '2023-12-01T00:00:00Z',
updatedAt: '2024-01-23T00:00:00Z',
},
{
id: 'napcat-plugin-admin',
name: '群管理插件',
version: '2.5.0',
description: '提供踢人、禁言、设置管理员等群管理功能',
author: 'Admin Tools',
homepage: 'https://github.com/example/admin',
repository: 'https://github.com/example/admin',
downloadUrl: 'https://example.com/plugins/napcat-plugin-admin-2.5.0.zip',
tags: ['管理', '群管理', '工具'],
minNapCatVersion: '1.0.0',
downloads: 6789,
rating: 4.6,
createdAt: '2023-12-15T00:00:00Z',
updatedAt: '2024-01-21T00:00:00Z',
},
{
id: 'napcat-plugin-image-search',
name: '以图搜图插件',
version: '1.5.2',
description: '支持多个搜图引擎,快速找到图片来源',
author: 'Image Hunter',
homepage: 'https://github.com/example/image-search',
repository: 'https://github.com/example/image-search',
downloadUrl: 'https://example.com/plugins/napcat-plugin-image-search-1.5.2.zip',
tags: ['图片', '搜索', '工具'],
minNapCatVersion: '1.0.0',
downloads: 4567,
rating: 4.4,
createdAt: '2024-01-08T00:00:00Z',
updatedAt: '2024-01-19T00:00:00Z',
},
],
};
// 插件商店源配置
const PLUGIN_STORE_SOURCES = [
'https://raw.githubusercontent.com/NapNeko/napcat-plugin-index/main/plugins.v4.json',
];
// 插件目录 - 使用 pathWrapper
const getPluginsDir = () => webUiPathWrapper.pluginPath;
// 插件列表缓存
let pluginListCache: PluginStoreList | null = null;
let cacheTimestamp: number = 0;
const CACHE_TTL = 10 * 60 * 1000; // 10分钟缓存
/**
* 从多个源获取插件列表,使用镜像系统
* 带10分钟缓存
*/
async function fetchPluginList (): Promise<PluginStoreList> {
// 检查缓存
const now = Date.now();
if (pluginListCache && (now - cacheTimestamp) < CACHE_TTL) {
//console.log('Using cached plugin list');
return pluginListCache;
}
const errors: string[] = [];
for (const source of PLUGIN_STORE_SOURCES) {
// 使用镜像系统的 raw 镜像列表
for (const mirror of GITHUB_RAW_MIRRORS) {
try {
const url = mirror ? `${mirror}/${source.replace('https://raw.githubusercontent.com/', '')}` : source;
const response = await fetch(url, {
headers: {
'User-Agent': 'NapCat-WebUI',
},
signal: AbortSignal.timeout(10000), // 10秒超时
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
//console.log(`Successfully fetched plugin list from: ${url}`);
// 更新缓存
pluginListCache = data as PluginStoreList;
cacheTimestamp = now;
return pluginListCache;
} catch (e: any) {
const errorMsg = `Failed to fetch from ${source} via mirror: ${e.message}`;
console.warn(errorMsg);
errors.push(errorMsg);
}
}
}
throw new Error(`All plugin sources failed:\n${errors.join('\n')}`);
}
/**
* 下载文件,使用镜像系统
* 自动识别 GitHub Release URL 并使用镜像加速
*/
async function downloadFile (url: string, destPath: string, customMirror?: string): Promise<void> {
try {
let downloadUrl: string;
// 判断是否是 GitHub Release URL
// 格式: https://github.com/{owner}/{repo}/releases/download/{tag}/{filename}
const githubReleasePattern = /^https:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//;
if (githubReleasePattern.test(url)) {
// 使用镜像系统查找可用的下载 URL(支持 GitHub Release 镜像)
console.log(`Detected GitHub Release URL: ${url}`);
console.log(`Custom mirror: ${customMirror || 'auto'}`);
downloadUrl = await findAvailableDownloadUrl(url, {
validateContent: false, // 不验证内容,只检查状态码和 Content-Type
timeout: 5000, // 每个镜像测试5秒超时
useFastMirrors: false, // 不使用快速镜像列表(避免测速阻塞)
customMirror: customMirror || undefined, // 使用用户选择的镜像
});
console.log(`Selected download URL: ${downloadUrl}`);
} else {
// 其他URL直接下载
console.log(`Direct download URL: ${url}`);
downloadUrl = url;
}
console.log(`Starting download from: ${downloadUrl}`);
// 确保目标目录存在
const destDir = path.dirname(destPath);
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
console.log(`Created directory: ${destDir}`);
}
const response = await fetch(downloadUrl, {
headers: {
'User-Agent': 'NapCat-WebUI',
},
signal: AbortSignal.timeout(120000), // 实际下载120秒超时
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
if (!response.body) {
throw new Error('Response body is null');
}
// 写入文件
const fileStream = createWriteStream(destPath);
await pipeline(response.body as any, fileStream);
console.log(`Successfully downloaded to: ${destPath}`);
} catch (e: any) {
// 删除可能的不完整文件
if (fs.existsSync(destPath)) {
fs.unlinkSync(destPath);
}
throw new Error(`Download failed: ${e.message}`);
}
}
/**
* 解压插件到指定目录
*/
async function extractPlugin (zipPath: string, pluginId: string): Promise<void> {
const PLUGINS_DIR = getPluginsDir();
const pluginDir = path.join(PLUGINS_DIR, pluginId);
console.log(`[extractPlugin] PLUGINS_DIR: ${PLUGINS_DIR}`);
console.log(`[extractPlugin] pluginId: ${pluginId}`);
console.log(`[extractPlugin] Target directory: ${pluginDir}`);
console.log(`[extractPlugin] Zip file: ${zipPath}`);
// 确保插件根目录存在
if (!fs.existsSync(PLUGINS_DIR)) {
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
console.log(`[extractPlugin] Created plugins root directory: ${PLUGINS_DIR}`);
}
// 如果目录已存在,先删除
if (fs.existsSync(pluginDir)) {
console.log(`[extractPlugin] Directory exists, removing: ${pluginDir}`);
fs.rmSync(pluginDir, { recursive: true, force: true });
}
// 创建插件目录
fs.mkdirSync(pluginDir, { recursive: true });
console.log(`[extractPlugin] Created directory: ${pluginDir}`);
// 解压
await compressing.zip.uncompress(zipPath, pluginDir);
console.log(`[extractPlugin] Plugin extracted to: ${pluginDir}`);
// 列出解压后的文件
const files = fs.readdirSync(pluginDir);
console.log(`[extractPlugin] Extracted files:`, files);
}
/**
* 获取插件商店列表
* 未来可以从远程URL读取
*/
export const GetPluginStoreListHandler: RequestHandler = async (_req, res) => {
try {
// TODO: 未来从远程URL读取
// const remoteUrl = 'https://napcat.example.com/plugin-list.json';
// const response = await fetch(remoteUrl);
// const data = await response.json();
// 目前返回Mock数据
return sendSuccess(res, mockPluginStoreData);
const data = await fetchPluginList();
return sendSuccess(res, data);
} catch (e: any) {
return sendError(res, 'Failed to fetch plugin store list: ' + e.message);
}
@@ -132,7 +197,8 @@ export const GetPluginStoreListHandler: RequestHandler = async (_req, res) => {
export const GetPluginStoreDetailHandler: RequestHandler = async (req, res) => {
try {
const { id } = req.params;
const plugin = mockPluginStoreData.plugins.find(p => p.id === id);
const data = await fetchPluginList();
const plugin = data.plugins.find(p => p.id === id);
if (!plugin) {
return sendError(res, 'Plugin not found');
@@ -145,33 +211,130 @@ export const GetPluginStoreDetailHandler: RequestHandler = async (req, res) => {
};
/**
* 安装插件(从商店)
* TODO: 实现实际的下载和安装逻辑
* 安装插件(从商店)- 普通 POST 接口
*/
export const InstallPluginFromStoreHandler: RequestHandler = async (req, res) => {
try {
const { id } = req.body;
const { id, mirror } = req.body;
if (!id) {
return sendError(res, 'Plugin ID is required');
}
const plugin = mockPluginStoreData.plugins.find(p => p.id === id);
// 获取插件信息
const data = await fetchPluginList();
const plugin = data.plugins.find(p => p.id === id);
if (!plugin) {
return sendError(res, 'Plugin not found in store');
}
// TODO: 实现实际的下载和安装逻辑
// 1. 下载插件文件
// 2. 解压到插件目录
// 3. 加载插件
// 下载插件
const PLUGINS_DIR = getPluginsDir();
const tempZipPath = path.join(PLUGINS_DIR, `${id}.temp.zip`);
return sendSuccess(res, {
message: 'Plugin installation started',
plugin: plugin
});
try {
await downloadFile(plugin.downloadUrl, tempZipPath, mirror);
// 解压插件
await extractPlugin(tempZipPath, id);
// 删除临时文件
fs.unlinkSync(tempZipPath);
return sendSuccess(res, {
message: 'Plugin installed successfully',
plugin: plugin,
installPath: path.join(PLUGINS_DIR, id),
});
} catch (downloadError: any) {
// 清理临时文件
if (fs.existsSync(tempZipPath)) {
fs.unlinkSync(tempZipPath);
}
throw downloadError;
}
} catch (e: any) {
return sendError(res, 'Failed to install plugin: ' + e.message);
}
};
/**
* 安装插件(从商店)- SSE 版本,实时推送进度
*/
export const InstallPluginFromStoreSSEHandler: RequestHandler = async (req, res) => {
const { id, mirror } = req.query;
if (!id || typeof id !== 'string') {
res.status(400).json({ error: 'Plugin ID is required' });
return;
}
// 设置 SSE 响应头
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
const sendProgress = (message: string, progress?: number) => {
res.write(`data: ${JSON.stringify({ message, progress })}\n\n`);
};
try {
sendProgress('正在获取插件信息...', 10);
// 获取插件信息
const data = await fetchPluginList();
const plugin = data.plugins.find(p => p.id === id);
if (!plugin) {
sendProgress('错误: 插件不存在', 0);
res.write(`data: ${JSON.stringify({ error: 'Plugin not found in store' })}\n\n`);
res.end();
return;
}
sendProgress(`找到插件: ${plugin.name} v${plugin.version}`, 20);
sendProgress(`下载地址: ${plugin.downloadUrl}`, 25);
if (mirror && typeof mirror === 'string') {
sendProgress(`使用镜像: ${mirror}`, 28);
}
// 下载插件
const PLUGINS_DIR = getPluginsDir();
const tempZipPath = path.join(PLUGINS_DIR, `${id}.temp.zip`);
try {
sendProgress('正在下载插件...', 30);
await downloadFile(plugin.downloadUrl, tempZipPath, mirror as string | undefined);
sendProgress('下载完成,正在解压...', 70);
await extractPlugin(tempZipPath, id);
sendProgress('解压完成,正在清理...', 90);
fs.unlinkSync(tempZipPath);
sendProgress('安装成功!', 100);
res.write(`data: ${JSON.stringify({
success: true,
message: 'Plugin installed successfully',
plugin: plugin,
installPath: path.join(PLUGINS_DIR, id),
})}\n\n`);
res.end();
} catch (downloadError: any) {
// 清理临时文件
if (fs.existsSync(tempZipPath)) {
fs.unlinkSync(tempZipPath);
}
sendProgress(`错误: ${downloadError.message}`, 0);
res.write(`data: ${JSON.stringify({ error: downloadError.message })}\n\n`);
res.end();
}
} catch (e: any) {
sendProgress(`错误: ${e.message}`, 0);
res.write(`data: ${JSON.stringify({ error: e.message })}\n\n`);
res.end();
}
};
@@ -1,17 +1,30 @@
import { Router } from 'express';
import { GetPluginListHandler, ReloadPluginHandler, SetPluginStatusHandler, UninstallPluginHandler } from '@/napcat-webui-backend/src/api/Plugin';
import { GetPluginStoreListHandler, GetPluginStoreDetailHandler, InstallPluginFromStoreHandler } 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);
router.get('/Store/Detail/:id', GetPluginStoreDetailHandler);
router.post('/Store/Install', InstallPluginFromStoreHandler);
router.get('/Store/Install/SSE', InstallPluginFromStoreSSEHandler);
export { router as PluginRouter };
@@ -7,17 +7,9 @@ export interface PluginStoreItem {
description: string; // 插件描述
author: string; // 作者
homepage?: string; // 主页链接
repository?: string; // 仓库地址
downloadUrl: string; // 下载地址
tags?: string[]; // 标签
icon?: string; // 图标URL
screenshots?: string[]; // 截图
minNapCatVersion?: string; // 最低NapCat版本要求
dependencies?: Record<string, string>; // 依赖
downloads?: number; // 下载次数
rating?: number; // 评分
createdAt?: string; // 创建时间
updatedAt?: string; // 更新时间
minVersion?: string; // 最低版本要求
}
export interface PluginStoreList {
@@ -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={
@@ -1,7 +1,7 @@
import { Button } from '@heroui/button';
import { Chip } from '@heroui/chip';
import { useState } from 'react';
import { IoMdStar, IoMdDownload } from 'react-icons/io';
import { IoMdDownload } from 'react-icons/io';
import DisplayCardContainer from './container';
import { PluginStoreItem } from '@/types/plugin-store';
@@ -15,7 +15,7 @@ const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
data,
onInstall,
}) => {
const { name, version, author, description, tags, rating, icon } = data;
const { name, version, author, description, tags, id } = data;
const [processing, setProcessing] = useState(false);
const handleInstall = () => {
@@ -37,17 +37,7 @@ const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
v{version}
</Chip>
}
enableSwitch={
icon ? (
<div className="flex items-center gap-2">
<img
src={icon}
alt={name}
className="w-10 h-10 rounded-lg object-cover"
/>
</div>
) : undefined
}
enableSwitch={undefined}
action={
<Button
fullWidth
@@ -88,14 +78,13 @@ const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
{description || '暂无描述'}
</div>
</div>
{rating && (
{id && (
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
评分
包名
</span>
<div className='flex items-center gap-1 text-sm font-medium text-default-700 dark:text-white/90'>
<IoMdStar className='text-warning' size={16} />
<span>{rating.toFixed(1)}</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 break-words line-clamp-2 h-10 overflow-hidden'>
{id || '包名'}
</div>
</div>
)}
@@ -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 });
}
// 插件商店相关方法
@@ -50,7 +64,20 @@ export default class PluginManager {
return data.data;
}
public static async installPluginFromStore (id: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Store/Install', { id });
public static async installPluginFromStore (id: string, mirror?: string) {
// 插件安装可能需要较长时间(下载+解压),设置5分钟超时
await serverRequest.post<ServerResponse<void>>('/Plugin/Store/Install', { id, mirror }, {
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>
);
}
@@ -1,15 +1,21 @@
import { Button } from '@heroui/button';
import { Input } from '@heroui/input';
import { Select, SelectItem } from '@heroui/select';
import { Tab, Tabs } from '@heroui/tabs';
import { useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import { IoMdRefresh, IoMdSearch } from 'react-icons/io';
import clsx from 'clsx';
import { useRequest } from 'ahooks';
import { EventSourcePolyfill } from 'event-source-polyfill';
import PageLoading from '@/components/page_loading';
import PluginStoreCard from '@/components/display_card/plugin_store_card';
import PluginManager from '@/controllers/plugin_manager';
import WebUIManager from '@/controllers/webui_manager';
import { PluginStoreItem } from '@/types/plugin-store';
import useDialog from '@/hooks/use-dialog';
import key from '@/const/key';
interface EmptySectionProps {
isEmpty: boolean;
@@ -32,6 +38,14 @@ export default function PluginStorePage () {
const [loading, setLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [activeTab, setActiveTab] = useState<string>('all');
const dialog = useDialog();
// 获取镜像列表
const { data: mirrorsData } = useRequest(WebUIManager.getMirrors, {
cacheKey: 'napcat-mirrors',
staleTime: 60 * 60 * 1000,
});
const mirrors = mirrorsData?.mirrors || [];
const loadPlugins = async () => {
setLoading(true);
@@ -64,16 +78,13 @@ export default function PluginStorePage () {
);
}
// 按下载量排序
filtered.sort((a, b) => (b.downloads || 0) - (a.downloads || 0));
// 定义主要分类
const categories: Record<string, PluginStoreItem[]> = {
all: filtered,
popular: filtered.filter(p => (p.downloads || 0) > 5000),
tools: filtered.filter(p => p.tags?.some(t => ['工具', '管理', '群管理'].includes(t))),
entertainment: filtered.filter(p => p.tags?.some(t => ['娱乐', '音乐', '游戏'].includes(t))),
message: filtered.filter(p => p.tags?.some(t => ['消息处理', '自动回复', '欢迎'].includes(t))),
official: filtered.filter(p => p.tags?.includes('官方')),
tools: filtered.filter(p => p.tags?.includes('工具')),
entertainment: filtered.filter(p => p.tags?.includes('娱乐')),
other: filtered.filter(p => !p.tags?.some(t => ['官方', '工具', '娱乐'].includes(t))),
};
return categories;
@@ -82,18 +93,124 @@ export default function PluginStorePage () {
const tabs = useMemo(() => {
return [
{ key: 'all', title: '全部', count: categorizedPlugins.all?.length || 0 },
{ key: 'popular', title: '热门推荐', count: categorizedPlugins.popular?.length || 0 },
{ key: 'tools', title: '工具管理', count: categorizedPlugins.tools?.length || 0 },
{ key: 'entertainment', title: '娱乐功能', count: categorizedPlugins.entertainment?.length || 0 },
{ key: 'message', title: '消息处理', count: categorizedPlugins.message?.length || 0 },
{ key: 'official', title: '官方', count: categorizedPlugins.official?.length || 0 },
{ key: 'tools', title: '工具', count: categorizedPlugins.tools?.length || 0 },
{ key: 'entertainment', title: '娱乐', count: categorizedPlugins.entertainment?.length || 0 },
{ key: 'other', title: '其它', count: categorizedPlugins.other?.length || 0 },
];
}, [categorizedPlugins]);
const handleInstall = async () => {
toast('该功能尚未完工,敬请期待', {
icon: '🚧',
duration: 3000,
});
const handleInstall = async (plugin: PluginStoreItem) => {
// 检测是否是 GitHub 下载链接
const githubPattern = /^https:\/\/github\.com\//;
const isGitHubUrl = githubPattern.test(plugin.downloadUrl);
// 如果是 GitHub 链接,弹出镜像选择对话框
if (isGitHubUrl) {
let selectedMirror: string | undefined = undefined;
dialog.confirm({
title: '安装插件',
content: (
<div className="space-y-4">
<div>
<p className="text-sm mb-2">
插件名称: <span className="font-semibold">{plugin.name}</span>
</p>
<p className="text-sm mb-2">
版本: <span className="font-semibold">v{plugin.version}</span>
</p>
<p className="text-sm text-default-500 mb-4">
{plugin.description}
</p>
</div>
<div>
<label className="text-sm font-medium mb-2 block">选择下载镜像源</label>
<Select
placeholder="自动选择 (默认)"
defaultSelectedKeys={['default']}
onSelectionChange={(keys) => {
const m = Array.from(keys)[0] as string;
selectedMirror = m === 'default' ? undefined : m;
}}
size="sm"
aria-label="选择镜像源"
>
{['default', ...mirrors].map(m => (
<SelectItem key={m} textValue={m === 'default' ? '自动选择' : m}>
{m === 'default' ? '自动选择 (默认)' : m}
</SelectItem>
))}
</Select>
</div>
</div>
),
confirmText: '开始安装',
cancelText: '取消',
onConfirm: async () => {
await installPluginWithSSE(plugin.id, selectedMirror);
},
});
} else {
// 非 GitHub 链接,直接安装
await installPluginWithSSE(plugin.id);
}
};
const installPluginWithSSE = async (pluginId: string, mirror?: string) => {
const loadingToast = toast.loading('正在准备安装...');
try {
// 获取认证 token
const token = localStorage.getItem(key.token);
if (!token) {
toast.error('未登录,请先登录', { id: loadingToast });
return;
}
const _token = JSON.parse(token);
const params = new URLSearchParams({ id: pluginId });
if (mirror) {
params.append('mirror', mirror);
}
const eventSource = new EventSourcePolyfill(
`/api/Plugin/Store/Install/SSE?${params.toString()}`,
{
headers: {
Authorization: `Bearer ${_token}`,
Accept: 'text/event-stream',
},
withCredentials: true,
}
);
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.error) {
toast.error(`安装失败: ${data.error}`, { id: loadingToast });
eventSource.close();
} else if (data.success) {
toast.success('插件安装成功!', { id: loadingToast });
eventSource.close();
} else if (data.message) {
toast.loading(data.message, { id: loadingToast });
}
} catch (e) {
console.error('Failed to parse SSE message:', e);
}
};
eventSource.onerror = (error) => {
console.error('SSE连接出错:', error);
toast.error('连接中断,安装失败', { id: loadingToast });
eventSource.close();
};
} catch (error: any) {
toast.error(`安装失败: ${error.message || '未知错误'}`, { id: loadingToast });
}
};
return (
@@ -148,7 +265,7 @@ export default function PluginStorePage () {
<PluginStoreCard
key={plugin.id}
data={plugin}
onInstall={handleInstall}
onInstall={() => handleInstall(plugin)}
/>
))}
</div>
@@ -7,17 +7,9 @@ export interface PluginStoreItem {
description: string; // 插件描述
author: string; // 作者
homepage?: string; // 主页链接
repository?: string; // 仓库地址
downloadUrl: string; // 下载地址
tags?: string[]; // 标签
icon?: string; // 图标URL
screenshots?: string[]; // 截图
minNapCatVersion?: string; // 最低NapCat版本要求
dependencies?: Record<string, string>; // 依赖
downloads?: number; // 下载次数
rating?: number; // 评分
createdAt?: string; // 创建时间
updatedAt?: string; // 更新时间
minVersion?: string; // 最低版本要求
}
export interface PluginStoreList {
+9 -15
View File
@@ -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
@@ -315,6 +305,9 @@ importers:
packages/napcat-types:
dependencies:
'@sinclair/typebox':
specifier: ^0.34.38
version: 0.34.41
'@types/cors':
specifier: ^2.8.17
version: 2.8.19
@@ -5445,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==}
@@ -12816,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