Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1b357347b | ||
|
|
129d63f66e | ||
|
|
699b46acbd | ||
|
|
7f05aee11d | ||
|
|
542036f46e | ||
|
|
b958e9e803 | ||
|
|
73fcfb5900 |
No files matched your search
@@ -9,6 +9,7 @@ import path from 'path';
|
||||
|
||||
export interface PluginPackageJson {
|
||||
name?: string;
|
||||
plugin?: string;
|
||||
version?: string;
|
||||
main?: string;
|
||||
description?: string;
|
||||
@@ -106,7 +107,7 @@ export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventCont
|
||||
|
||||
export interface LoadedPlugin {
|
||||
name: string;
|
||||
dirname: string; // Actual directory name for path resolution
|
||||
fileId: string; // 文件系统目录名,用于路径解析
|
||||
version?: string;
|
||||
pluginPath: string;
|
||||
entryPath: string;
|
||||
@@ -122,14 +123,15 @@ export interface PluginStatusConfig {
|
||||
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
|
||||
/** 插件注册表: 包名(id) -> 插件数据 */
|
||||
private pluginRegistry: Map<string, LoadedPlugin> = new Map();
|
||||
/** 失败的插件: ID -> 错误信息 */
|
||||
private failedPlugins: Map<string, string> = new Map();
|
||||
declare config: PluginConfig;
|
||||
public NapCatConfig = NapCatConfig;
|
||||
|
||||
override get isActive (): boolean {
|
||||
return this.isEnable && this.loadedPlugins.size > 0;
|
||||
return this.isEnable && this.pluginRegistry.size > 0;
|
||||
}
|
||||
|
||||
constructor (
|
||||
@@ -192,9 +194,19 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pluginId = item.name;
|
||||
// 先读取 package.json 获取包名(id)
|
||||
const packageJsonPath = path.join(this.pluginPath, item.name, 'package.json');
|
||||
let pluginId = item.name; // 默认使用目录名
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
if (pkg.name) {
|
||||
pluginId = pkg.name;
|
||||
}
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
// Check if plugin is disabled in config
|
||||
// Check if plugin is disabled in config (by id)
|
||||
if (pluginConfig[pluginId] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled in config, skipping`);
|
||||
continue;
|
||||
@@ -205,7 +217,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`
|
||||
`[Plugin Adapter] Loaded ${this.pluginRegistry.size} plugins`
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.logError('[Plugin Adapter] Error loading plugins:', error);
|
||||
@@ -219,13 +231,6 @@ 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
|
||||
|
||||
if (pluginConfig[pluginId] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled by user`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 尝试读取 package.json
|
||||
@@ -244,6 +249,16 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
// 获取插件 id(包名)
|
||||
const pluginId = packageJson?.name || dirname;
|
||||
|
||||
// 检查插件是否被禁用 (by id)
|
||||
const pluginConfig = this.loadPluginConfig();
|
||||
if (pluginConfig[pluginId] === false) {
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled by user`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 确定入口文件
|
||||
const entryFile = this.findEntryFile(pluginDir, packageJson);
|
||||
if (!entryFile) {
|
||||
@@ -264,8 +279,8 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
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
|
||||
name: pluginId, // 使用包名作为 id
|
||||
fileId: dirname, // 保留目录名用于路径解析
|
||||
version: packageJson?.version,
|
||||
pluginPath: pluginDir,
|
||||
entryPath,
|
||||
@@ -329,15 +344,12 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return module && typeof module.plugin_init === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册插件
|
||||
*/
|
||||
/**
|
||||
* 注册插件
|
||||
*/
|
||||
private async registerPlugin (plugin: LoadedPlugin): Promise<void> {
|
||||
// 检查名称冲突
|
||||
if (this.loadedPlugins.has(plugin.name)) {
|
||||
if (this.pluginRegistry.has(plugin.name)) {
|
||||
this.logger.logWarn(
|
||||
`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`
|
||||
);
|
||||
@@ -345,8 +357,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
|
||||
// Create Context
|
||||
// Use dirname for path resolution, name for identification
|
||||
const dataPath = path.join(this.pluginPath, plugin.dirname, 'data');
|
||||
const dataPath = path.join(plugin.pluginPath, 'data');
|
||||
const configPath = path.join(dataPath, 'config.json');
|
||||
|
||||
// Create plugin-specific logger with prefix
|
||||
@@ -376,7 +387,9 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
|
||||
plugin.context = context; // Store context on plugin object
|
||||
|
||||
this.loadedPlugins.set(plugin.name, plugin);
|
||||
// 注册到映射表
|
||||
this.pluginRegistry.set(plugin.name, plugin);
|
||||
|
||||
this.logger.log(
|
||||
`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''
|
||||
}`
|
||||
@@ -393,7 +406,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
);
|
||||
// Mark as failed
|
||||
this.failedPlugins.set(plugin.name, error.message || 'Initialization failed');
|
||||
this.loadedPlugins.delete(plugin.name);
|
||||
this.pluginRegistry.delete(plugin.name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,7 +414,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
* 卸载插件
|
||||
*/
|
||||
private async unloadPlugin (pluginName: string): Promise<void> {
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
const plugin = this.pluginRegistry.get(pluginName);
|
||||
if (!plugin) {
|
||||
return;
|
||||
}
|
||||
@@ -419,7 +432,8 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
this.loadedPlugins.delete(pluginName);
|
||||
// 从映射表中移除
|
||||
this.pluginRegistry.delete(pluginName);
|
||||
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
|
||||
}
|
||||
|
||||
@@ -435,19 +449,22 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
return this.loadPluginConfig();
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* 设置插件状态(启用/禁用)
|
||||
* @param pluginId 插件包名(id)
|
||||
* @param enable 是否启用
|
||||
*/
|
||||
public setPluginStatus (pluginId: string, enable: boolean): void {
|
||||
const config = this.loadPluginConfig();
|
||||
config[configKey] = enable;
|
||||
config[pluginId] = enable;
|
||||
this.savePluginConfig(config);
|
||||
|
||||
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 (!enable) {
|
||||
const plugin = this.pluginRegistry.get(pluginId);
|
||||
if (plugin) {
|
||||
this.unloadPlugin(pluginId).catch(e => this.logger.logError('Error unloading', e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,7 +475,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
|
||||
try {
|
||||
await Promise.allSettled(
|
||||
Array.from(this.loadedPlugins.values()).map((plugin) =>
|
||||
Array.from(this.pluginRegistry.values()).map((plugin) =>
|
||||
this.callPluginEventHandler(plugin, event)
|
||||
)
|
||||
);
|
||||
@@ -513,7 +530,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
await this.loadPlugins();
|
||||
|
||||
this.logger.log(
|
||||
`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`
|
||||
`[Plugin Adapter] Plugin adapter opened with ${this.pluginRegistry.size} plugins loaded`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -526,7 +543,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
this.isEnable = false;
|
||||
|
||||
// 卸载所有插件
|
||||
const pluginNames = Array.from(this.loadedPlugins.keys());
|
||||
const pluginNames = Array.from(this.pluginRegistry.keys());
|
||||
for (const pluginName of pluginNames) {
|
||||
await this.unloadPlugin(pluginName);
|
||||
}
|
||||
@@ -549,55 +566,119 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
* 获取已加载的插件列表
|
||||
*/
|
||||
public getLoadedPlugins (): LoadedPlugin[] {
|
||||
return Array.from(this.loadedPlugins.values());
|
||||
return Array.from(this.pluginRegistry.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件信息
|
||||
* 通过包名(id)获取插件信息
|
||||
*/
|
||||
public getPluginInfo (pluginName: string): LoadedPlugin | undefined {
|
||||
return this.loadedPlugins.get(pluginName);
|
||||
public getPluginInfo (pluginId: string): LoadedPlugin | undefined {
|
||||
return this.pluginRegistry.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 id 加载插件
|
||||
*/
|
||||
public async loadPluginById (id: string): Promise<boolean> {
|
||||
// 扫描文件系统查找 fileId
|
||||
if (!fs.existsSync(this.pluginPath)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin ${id} not found in filesystem`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
|
||||
for (const item of items) {
|
||||
if (!item.isDirectory()) continue;
|
||||
|
||||
const packageJsonPath = path.join(this.pluginPath, item.name, 'package.json');
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
if (pkg.name === id) {
|
||||
await this.loadDirectoryPlugin(item.name);
|
||||
return this.pluginRegistry.has(id);
|
||||
}
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin ${id} not found in filesystem`);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载并删除插件
|
||||
*/
|
||||
public async uninstallPlugin (id: string, cleanData: boolean = false): Promise<void> {
|
||||
const plugin = this.pluginRegistry.get(id);
|
||||
if (!plugin) {
|
||||
throw new Error(`Plugin ${id} not found or not loaded`);
|
||||
}
|
||||
|
||||
const pluginPath = plugin.context.pluginPath;
|
||||
const dataPath = plugin.context.dataPath;
|
||||
|
||||
// 先卸载插件
|
||||
await this.unloadPlugin(id);
|
||||
|
||||
// 删除插件目录
|
||||
if (fs.existsSync(pluginPath)) {
|
||||
fs.rmSync(pluginPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// 清理数据
|
||||
if (cleanData && fs.existsSync(dataPath)) {
|
||||
fs.rmSync(dataPath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载指定插件
|
||||
*/
|
||||
public async reloadPlugin (pluginName: string): Promise<boolean> {
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
public async reloadPlugin (pluginId: string): Promise<boolean> {
|
||||
const plugin = this.pluginRegistry.get(pluginId);
|
||||
if (!plugin) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginId} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const dirname = plugin.dirname;
|
||||
const dirname = path.basename(plugin.pluginPath);
|
||||
|
||||
try {
|
||||
// 卸载插件
|
||||
await this.unloadPlugin(pluginName);
|
||||
await this.unloadPlugin(pluginId);
|
||||
|
||||
// 重新加载插件 - use dirname for directory loading
|
||||
// 重新加载插件
|
||||
await this.loadDirectoryPlugin(dirname);
|
||||
|
||||
this.logger.log(
|
||||
`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`
|
||||
`[Plugin Adapter] Plugin ${pluginId} reloaded successfully`
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.logError(
|
||||
`[Plugin Adapter] Error reloading plugin ${pluginName}:`,
|
||||
`[Plugin Adapter] Error reloading plugin ${pluginId}:`,
|
||||
error
|
||||
);
|
||||
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 getPluginDataPath (pluginId: string): string {
|
||||
const plugin = this.pluginRegistry.get(pluginId);
|
||||
if (!plugin) {
|
||||
throw new Error(`Plugin ${pluginId} not found`);
|
||||
}
|
||||
return plugin.context.dataPath;
|
||||
}
|
||||
|
||||
public getPluginConfigPath (pluginName: string): string {
|
||||
return path.join(this.getPluginDataPath(pluginName), 'config.json');
|
||||
/**
|
||||
* 获取插件配置文件路径
|
||||
*/
|
||||
public getPluginConfigPath (pluginId: string): string {
|
||||
return path.join(this.getPluginDataPath(pluginId), 'config.json');
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import path from 'path';
|
||||
|
||||
export interface PluginPackageJson {
|
||||
name?: string;
|
||||
plugin?: string;
|
||||
version?: string;
|
||||
main?: string;
|
||||
}
|
||||
@@ -255,7 +256,7 @@ export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
|
||||
}
|
||||
|
||||
async onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||
async onEvent<T extends OB11EmitEventContent> (event: T) {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
@@ -357,7 +358,7 @@ export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
|
||||
// 重新加载插件
|
||||
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
|
||||
plugin.pluginPath !== this.pluginPath;
|
||||
plugin.pluginPath !== this.pluginPath;
|
||||
|
||||
if (isDirectory) {
|
||||
const dirname = path.basename(plugin.pluginPath);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"name": "napcat-plugin-builtin",
|
||||
"plugin": "内置插件",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -105,7 +105,8 @@ export function generateOpenAPI () {
|
||||
retcode: 0,
|
||||
data: schemas.returnExample || {},
|
||||
message: '',
|
||||
wording: ''
|
||||
wording: '',
|
||||
stream: 'normal-action'
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -119,7 +120,8 @@ export function generateOpenAPI () {
|
||||
retcode: error.code,
|
||||
data: null,
|
||||
message: error.description,
|
||||
wording: error.description
|
||||
wording: error.description,
|
||||
stream: 'normal-action'
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -132,7 +134,8 @@ export function generateOpenAPI () {
|
||||
retcode: 1400,
|
||||
data: null,
|
||||
message: '请求参数错误或业务逻辑执行失败',
|
||||
wording: '请求参数错误或业务逻辑执行失败'
|
||||
wording: '请求参数错误或业务逻辑执行失败',
|
||||
stream: 'normal-action'
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -171,7 +174,8 @@ export function generateOpenAPI () {
|
||||
retcode: { type: 'number', description: '返回码' },
|
||||
data: { ...cleanReturn, description: '数据' },
|
||||
message: { type: 'string', description: '消息' },
|
||||
wording: { type: 'string', description: '提示' }
|
||||
wording: { type: 'string', description: '提示' },
|
||||
stream: { type: 'string', description: '流式响应', enum: ['stream-action', 'normal-action'] }
|
||||
},
|
||||
required: ['status', 'retcode', 'data']
|
||||
},
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/// <reference path="./external-shims.d.ts" />
|
||||
// 聚合导出核心库的所有内容(包括枚举、类和类型)
|
||||
export * from '../napcat-core/index';
|
||||
|
||||
|
||||
@@ -14,13 +14,6 @@
|
||||
},
|
||||
"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",
|
||||
"@sinclair/typebox": "^0.34.38"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "napcat-types",
|
||||
"version": "0.0.9",
|
||||
"version": "0.0.10",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"types": "./napcat-types/index.d.ts",
|
||||
@@ -9,13 +9,6 @@
|
||||
],
|
||||
"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",
|
||||
"@sinclair/typebox": "^0.34.38"
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// 复制 cp README.md dist/ && cp package.public.json dist/package.json && cp external-shims.d.ts dist/
|
||||
// 复制 cp README.md dist/ && cp package.public.json dist/package.json
|
||||
import { copyFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -10,8 +10,4 @@ await copyFile(
|
||||
await copyFile(
|
||||
join(__dirname, 'README.md'),
|
||||
join(__dirname, 'dist', 'README.md')
|
||||
);
|
||||
await copyFile(
|
||||
join(__dirname, 'external-shims.d.ts'),
|
||||
join(__dirname, 'dist', 'external-shims.d.ts')
|
||||
);
|
||||
@@ -5,6 +5,111 @@ import { fileURLToPath } from 'node:url';
|
||||
const __dirname = fileURLToPath(new URL('../', import.meta.url));
|
||||
const distDir = join(__dirname, 'dist');
|
||||
|
||||
// 允许保留的包(白名单)
|
||||
const ALLOWED_PACKAGES = [
|
||||
'@sinclair/typebox',
|
||||
'node:', // node: 前缀的内置模块
|
||||
];
|
||||
|
||||
// 外部包类型到 any 的映射
|
||||
const EXTERNAL_TYPE_REPLACEMENTS = {
|
||||
// winston
|
||||
'winston.Logger': 'any',
|
||||
'winston.transport': 'any',
|
||||
// express
|
||||
'express.Express': 'any',
|
||||
'express.Application': 'any',
|
||||
'express.Router': 'any',
|
||||
'Express': 'any',
|
||||
'Request': 'any',
|
||||
'Response': 'any',
|
||||
'NextFunction': 'any',
|
||||
// ws
|
||||
'WebSocket': 'any',
|
||||
'WebSocketServer': 'any',
|
||||
'RawData': 'any',
|
||||
// ajv
|
||||
'Ajv': 'any',
|
||||
'AnySchema': 'any',
|
||||
'ValidateFunction': 'any',
|
||||
'ValidateFunction<T>': 'any',
|
||||
// inversify
|
||||
'Container': 'any',
|
||||
// async-mutex
|
||||
'Mutex': 'any',
|
||||
'Semaphore': 'any',
|
||||
// napcat-protobuf
|
||||
'NapProtoDecodeStructType': 'any',
|
||||
'NapProtoEncodeStructType': 'any',
|
||||
'NapProtoDecodeStructType<T>': 'any',
|
||||
'NapProtoEncodeStructType<T>': 'any',
|
||||
};
|
||||
|
||||
function isAllowedImport (importPath) {
|
||||
return ALLOWED_PACKAGES.some(pkg => importPath.startsWith(pkg));
|
||||
}
|
||||
|
||||
function removeExternalImports (content) {
|
||||
const lines = content.split('\n');
|
||||
const resultLines = [];
|
||||
|
||||
for (const line of lines) {
|
||||
// 匹配 import 语句
|
||||
const importMatch = line.match(/^import\s+.*\s+from\s+['"]([^'"]+)['"]/);
|
||||
if (importMatch) {
|
||||
const importPath = importMatch[1];
|
||||
// 如果是相对路径或白名单包,保留
|
||||
if (importPath.startsWith('.') || importPath.startsWith('/') || isAllowedImport(importPath)) {
|
||||
resultLines.push(line);
|
||||
}
|
||||
// 否则移除该 import
|
||||
continue;
|
||||
}
|
||||
resultLines.push(line);
|
||||
}
|
||||
|
||||
return resultLines.join('\n');
|
||||
}
|
||||
|
||||
function replaceExternalTypes (content) {
|
||||
let result = content;
|
||||
|
||||
// 替换带泛型的类型(先处理复杂的)
|
||||
result = result.replace(/NapProtoDecodeStructType<[^>]+>/g, 'any');
|
||||
result = result.replace(/NapProtoEncodeStructType<[^>]+>/g, 'any');
|
||||
result = result.replace(/ValidateFunction<[^>]+>/g, 'any');
|
||||
|
||||
// 替换 winston.Logger 等带命名空间的类型
|
||||
result = result.replace(/winston\.Logger/g, 'any');
|
||||
result = result.replace(/winston\.transport/g, 'any');
|
||||
result = result.replace(/express\.Express/g, 'any');
|
||||
result = result.replace(/express\.Application/g, 'any');
|
||||
result = result.replace(/express\.Router/g, 'any');
|
||||
|
||||
// 替换独立的类型名(需要小心不要替换变量名)
|
||||
// 使用类型上下文的模式匹配
|
||||
const typeContextPatterns = [
|
||||
// : Type
|
||||
/:\s*(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|Mutex|Semaphore|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[;,)\]\}|&]|$)/g,
|
||||
// <Type>
|
||||
/<(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|Mutex|Semaphore|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)>/g,
|
||||
// Type[]
|
||||
/(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|Mutex|Semaphore|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)\[\]/g,
|
||||
// extends Type
|
||||
/extends\s+(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|Mutex|Semaphore|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g,
|
||||
// implements Type
|
||||
/implements\s+(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|Mutex|Semaphore|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g,
|
||||
];
|
||||
|
||||
for (const pattern of typeContextPatterns) {
|
||||
result = result.replace(pattern, (match, typeName) => {
|
||||
return match.replace(typeName, 'any');
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function traverseDirectory (dir) {
|
||||
const entries = await readdir(dir, { withFileTypes: true });
|
||||
|
||||
@@ -23,7 +128,13 @@ async function processFile (filePath) {
|
||||
// Read file content
|
||||
let content = await readFile(filePath, 'utf-8');
|
||||
|
||||
// Replace "export declare enum" with "export enum"
|
||||
// 1. 移除外部包的 import
|
||||
content = removeExternalImports(content);
|
||||
|
||||
// 2. 替换外部类型为 any
|
||||
content = replaceExternalTypes(content);
|
||||
|
||||
// 3. Replace "export declare enum" with "export enum"
|
||||
content = content.replace(/export declare enum/g, 'export enum');
|
||||
|
||||
// Write back the modified content
|
||||
@@ -33,7 +144,7 @@ async function processFile (filePath) {
|
||||
const newPath = filePath.replace(/\.d\.ts$/, '.ts');
|
||||
await rename(filePath, newPath);
|
||||
|
||||
console.log(`Processed: ${basename(filePath)} -> ${basename(newPath)}`);
|
||||
//console.log(`Processed: ${basename(filePath)} -> ${basename(newPath)}`);
|
||||
}
|
||||
|
||||
console.log('Starting post-build processing...');
|
||||
|
||||
@@ -39,9 +39,6 @@
|
||||
"../napcat-onebot/**/*.ts",
|
||||
"../napcat-common/**/*.ts"
|
||||
],
|
||||
"files": [
|
||||
"./external-shims.d.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { RequestHandler } from 'express';
|
||||
import { sendSuccess, sendError } from '@/napcat-webui-backend/src/utils/response';
|
||||
import {
|
||||
GITHUB_FILE_MIRRORS,
|
||||
GITHUB_RAW_MIRRORS,
|
||||
buildMirrorUrl,
|
||||
getMirrorConfig,
|
||||
setCustomMirror,
|
||||
clearMirrorCache
|
||||
} from 'napcat-common/src/mirror';
|
||||
import https from 'https';
|
||||
import http from 'http';
|
||||
|
||||
export interface MirrorTestResult {
|
||||
mirror: string;
|
||||
latency: number;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试单个镜像的延迟
|
||||
*/
|
||||
async function testMirrorLatency (mirror: string, testUrl: string, timeout: number = 5000): Promise<MirrorTestResult> {
|
||||
const url = mirror ? buildMirrorUrl(testUrl, mirror) : testUrl;
|
||||
const start = Date.now();
|
||||
|
||||
return new Promise<MirrorTestResult>((resolve) => {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
const isHttps = urlObj.protocol === 'https:';
|
||||
const client = isHttps ? https : http;
|
||||
|
||||
const req = client.request({
|
||||
hostname: urlObj.hostname,
|
||||
port: urlObj.port || (isHttps ? 443 : 80),
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: 'HEAD',
|
||||
timeout,
|
||||
headers: {
|
||||
'User-Agent': 'NapCat-Mirror-Test',
|
||||
},
|
||||
}, (res) => {
|
||||
const statusCode = res.statusCode || 0;
|
||||
const isValid = statusCode >= 200 && statusCode < 400;
|
||||
resolve({
|
||||
mirror: mirror || 'https://github.com',
|
||||
latency: Date.now() - start,
|
||||
success: isValid,
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (e) => {
|
||||
resolve({
|
||||
mirror: mirror || 'https://github.com',
|
||||
latency: Date.now() - start,
|
||||
success: false,
|
||||
error: e.message,
|
||||
});
|
||||
});
|
||||
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve({
|
||||
mirror: mirror || 'https://github.com',
|
||||
latency: timeout,
|
||||
success: false,
|
||||
error: 'Timeout',
|
||||
});
|
||||
});
|
||||
|
||||
req.end();
|
||||
} catch (e: any) {
|
||||
resolve({
|
||||
mirror: mirror || 'https://github.com',
|
||||
latency: Date.now() - start,
|
||||
success: false,
|
||||
error: e.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有可用的镜像列表
|
||||
*/
|
||||
export const GetMirrorListHandler: RequestHandler = async (_req, res) => {
|
||||
try {
|
||||
const config = getMirrorConfig();
|
||||
return sendSuccess(res, {
|
||||
fileMirrors: GITHUB_FILE_MIRRORS.filter(m => m),
|
||||
rawMirrors: GITHUB_RAW_MIRRORS,
|
||||
customMirror: config.customMirror,
|
||||
timeout: config.timeout,
|
||||
});
|
||||
} catch (e: any) {
|
||||
return sendError(res, e.message);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置自定义镜像
|
||||
*/
|
||||
export const SetCustomMirrorHandler: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
const { mirror } = req.body;
|
||||
setCustomMirror(mirror || '');
|
||||
clearMirrorCache();
|
||||
return sendSuccess(res, { message: 'Mirror set successfully' });
|
||||
} catch (e: any) {
|
||||
return sendError(res, e.message);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* SSE 实时测速所有镜像
|
||||
*/
|
||||
export const TestMirrorsSSEHandler: RequestHandler = async (req, res) => {
|
||||
const { type = 'file' } = req.query;
|
||||
|
||||
// 设置 SSE 响应头
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.flushHeaders();
|
||||
|
||||
const sendProgress = (data: any) => {
|
||||
res.write(`data: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
|
||||
try {
|
||||
// 选择镜像列表
|
||||
let mirrors: string[];
|
||||
let testUrl: string;
|
||||
|
||||
if (type === 'raw') {
|
||||
mirrors = GITHUB_RAW_MIRRORS;
|
||||
testUrl = 'https://raw.githubusercontent.com/NapNeko/NapCatQQ/main/README.md';
|
||||
} else {
|
||||
mirrors = GITHUB_FILE_MIRRORS.filter(m => m);
|
||||
testUrl = 'https://github.com/NapNeko/NapCatQQ/releases/latest';
|
||||
}
|
||||
|
||||
// 添加原始 URL 测试
|
||||
if (!mirrors.includes('')) {
|
||||
mirrors = ['', ...mirrors];
|
||||
}
|
||||
|
||||
sendProgress({
|
||||
type: 'start',
|
||||
total: mirrors.length,
|
||||
message: `开始测试 ${mirrors.length} 个镜像源...`,
|
||||
});
|
||||
|
||||
const results: MirrorTestResult[] = [];
|
||||
const timeout = 5000;
|
||||
|
||||
// 逐个测试并实时推送结果
|
||||
for (let i = 0; i < mirrors.length; i++) {
|
||||
const mirror = mirrors[i] ?? '';
|
||||
const displayName = mirror || 'https://github.com (原始)';
|
||||
|
||||
sendProgress({
|
||||
type: 'testing',
|
||||
index: i,
|
||||
total: mirrors.length,
|
||||
mirror: displayName,
|
||||
message: `正在测试: ${displayName}`,
|
||||
});
|
||||
|
||||
const result = await testMirrorLatency(mirror, testUrl, timeout);
|
||||
results.push(result);
|
||||
|
||||
sendProgress({
|
||||
type: 'result',
|
||||
index: i,
|
||||
total: mirrors.length,
|
||||
result: {
|
||||
...result,
|
||||
mirror: result.mirror || 'https://github.com (原始)',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 按延迟排序
|
||||
const sortedResults = results
|
||||
.filter(r => r.success)
|
||||
.sort((a, b) => a.latency - b.latency);
|
||||
|
||||
const failedResults = results.filter(r => !r.success);
|
||||
|
||||
sendProgress({
|
||||
type: 'complete',
|
||||
results: sortedResults,
|
||||
failed: failedResults,
|
||||
fastest: sortedResults[0] || null,
|
||||
message: `测试完成!${sortedResults.length} 个可用,${failedResults.length} 个失败`,
|
||||
});
|
||||
|
||||
res.end();
|
||||
} catch (e: any) {
|
||||
sendProgress({
|
||||
type: 'error',
|
||||
error: e.message,
|
||||
});
|
||||
res.end();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 快速测试单个镜像
|
||||
*/
|
||||
export const TestSingleMirrorHandler: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
const { mirror, type = 'file' } = req.body;
|
||||
|
||||
let testUrl: string;
|
||||
if (type === 'raw') {
|
||||
testUrl = 'https://raw.githubusercontent.com/NapNeko/NapCatQQ/main/README.md';
|
||||
} else {
|
||||
testUrl = 'https://github.com/NapNeko/NapCatQQ/releases/latest';
|
||||
}
|
||||
|
||||
const result = await testMirrorLatency(mirror || '', testUrl, 5000);
|
||||
|
||||
return sendSuccess(res, result);
|
||||
} catch (e: any) {
|
||||
return sendError(res, e.message);
|
||||
}
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
|
||||
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
import { OB11PluginMangerAdapter } from '@/napcat-onebot/network/plugin-manger';
|
||||
import { webUiPathWrapper } from '@/napcat-webui-backend/index';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
@@ -13,6 +14,49 @@ const getPluginManager = (): OB11PluginMangerAdapter | null => {
|
||||
return ob11.networkManager.findSomeAdapter('plugin_manager') as OB11PluginMangerAdapter;
|
||||
};
|
||||
|
||||
// Helper to get OneBot context
|
||||
const getOneBotContext = (): NapCatOneBot11Adapter | null => {
|
||||
return WebUiDataRuntime.getOneBotContext() as NapCatOneBot11Adapter;
|
||||
};
|
||||
|
||||
/**
|
||||
* 手动注册插件管理器到 NetworkManager
|
||||
*/
|
||||
export const RegisterPluginManagerHandler: RequestHandler = async (_req, res) => {
|
||||
const ob11 = getOneBotContext();
|
||||
if (!ob11) {
|
||||
return sendError(res, 'OneBot context not found');
|
||||
}
|
||||
|
||||
// 检查是否已经注册
|
||||
const existingManager = ob11.networkManager.findSomeAdapter('plugin_manager');
|
||||
if (existingManager) {
|
||||
return sendError(res, '插件管理器已经注册');
|
||||
}
|
||||
|
||||
try {
|
||||
// 确保插件目录存在
|
||||
const pluginPath = webUiPathWrapper.pluginPath;
|
||||
if (!fs.existsSync(pluginPath)) {
|
||||
fs.mkdirSync(pluginPath, { recursive: true });
|
||||
}
|
||||
|
||||
// 创建并注册插件管理器
|
||||
const pluginManager = new OB11PluginMangerAdapter(
|
||||
'plugin_manager',
|
||||
ob11.core,
|
||||
ob11,
|
||||
ob11.actions
|
||||
);
|
||||
|
||||
await ob11.networkManager.registerAdapterAndOpen(pluginManager);
|
||||
|
||||
return sendSuccess(res, { message: '插件管理器注册成功' });
|
||||
} catch (e: any) {
|
||||
return sendError(res, '注册插件管理器失败: ' + e.message);
|
||||
}
|
||||
};
|
||||
|
||||
export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) {
|
||||
@@ -20,32 +64,18 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
return sendSuccess(res, { plugins: [], pluginManagerNotFound: true });
|
||||
}
|
||||
|
||||
// 辅助函数:根据文件名/路径生成唯一ID(作为配置键)
|
||||
const getPluginId = (fsName: string, isFile: boolean): string => {
|
||||
if (isFile) {
|
||||
return path.parse(fsName).name;
|
||||
}
|
||||
return fsName;
|
||||
};
|
||||
|
||||
const loadedPlugins = pluginManager.getLoadedPlugins();
|
||||
const loadedPluginMap = new Map<string, any>(); // Map ID -> Loaded Info
|
||||
const loadedPluginMap = new Map<string, any>(); // Map id -> Loaded Info
|
||||
|
||||
// 1. 整理已加载的插件
|
||||
for (const p of loadedPlugins) {
|
||||
// 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.name, // This is now package name (from packageJson.name || dirname)
|
||||
id: id,
|
||||
loadedPluginMap.set(p.name, {
|
||||
name: p.packageJson?.plugin || p.name, // 优先显示 package.json 的 plugin 字段
|
||||
id: p.name, // 包名,用于 API 操作
|
||||
version: p.version || '0.0.0',
|
||||
description: p.packageJson?.description || '',
|
||||
author: p.packageJson?.author || '',
|
||||
status: 'active',
|
||||
filename: fsName, // 真实文件/目录名
|
||||
loadedName: p.name, // 运行时注册的名称,用于重载/卸载 (package name)
|
||||
hasConfig: !!(p.module.plugin_config_schema || p.module.plugin_config_ui)
|
||||
});
|
||||
}
|
||||
@@ -59,15 +89,25 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
const items = fs.readdirSync(pluginPath, { withFileTypes: true });
|
||||
|
||||
for (const item of items) {
|
||||
let id = '';
|
||||
if (!item.isDirectory()) continue;
|
||||
|
||||
if (item.isFile()) {
|
||||
if (!['.js', '.mjs'].includes(path.extname(item.name))) continue;
|
||||
id = getPluginId(item.name, true);
|
||||
} else if (item.isDirectory()) {
|
||||
id = getPluginId(item.name, false);
|
||||
} else {
|
||||
continue;
|
||||
// 读取 package.json 获取插件信息
|
||||
let id = item.name;
|
||||
let name = item.name;
|
||||
let version = '0.0.0';
|
||||
let description = '';
|
||||
let author = '';
|
||||
|
||||
const packageJsonPath = path.join(pluginPath, item.name, 'package.json');
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
id = pkg.name || id;
|
||||
name = pkg.plugin || pkg.name || name;
|
||||
version = pkg.version || version;
|
||||
description = pkg.description || description;
|
||||
author = pkg.author || author;
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
const isActiveConfig = pluginConfig[id] !== false; // 默认为 true
|
||||
@@ -77,37 +117,14 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
const loadedInfo = loadedPluginMap.get(id);
|
||||
allPlugins.push(loadedInfo);
|
||||
} else {
|
||||
// 未加载 (可能是被禁用,或者加载失败,或者新增未运行)
|
||||
let version = '0.0.0';
|
||||
let description = '';
|
||||
let author = '';
|
||||
// 默认显示名称为 ID (文件名/目录名)
|
||||
let name = id;
|
||||
|
||||
try {
|
||||
// 尝试读取 package.json 获取信息
|
||||
if (item.isDirectory()) {
|
||||
const packageJsonPath = path.join(pluginPath, item.name, 'package.json');
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
version = pkg.version || version;
|
||||
description = pkg.description || description;
|
||||
author = pkg.author || author;
|
||||
// 如果 package.json 有 name,优先使用
|
||||
name = pkg.name || name;
|
||||
}
|
||||
}
|
||||
} catch (e) { }
|
||||
|
||||
allPlugins.push({
|
||||
name: name,
|
||||
id: id,
|
||||
name,
|
||||
id,
|
||||
version,
|
||||
description,
|
||||
author,
|
||||
// 如果配置是 false,则为 disabled;否则是 stopped (应启动但未启动)
|
||||
status: isActiveConfig ? 'stopped' : 'disabled',
|
||||
filename: item.name
|
||||
status: isActiveConfig ? 'stopped' : 'disabled'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -116,43 +133,27 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
|
||||
return sendSuccess(res, { plugins: allPlugins, pluginManagerNotFound: false });
|
||||
};
|
||||
|
||||
// ReloadPluginHandler removed
|
||||
|
||||
export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
|
||||
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
|
||||
const { enable, id } = req.body;
|
||||
|
||||
if (!filename && !name) return sendError(res, 'Plugin Filename or Name is required');
|
||||
if (!id) return sendError(res, 'Plugin id is required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) {
|
||||
return sendError(res, 'Plugin Manager not found');
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// setPluginStatus now handles both package name and dirname lookup internally
|
||||
pluginManager.setPluginStatus(pluginName, enable);
|
||||
// 设置插件状态
|
||||
pluginManager.setPluginStatus(id, enable);
|
||||
|
||||
// If enabling, trigger load
|
||||
// 如果启用,需要加载插件
|
||||
if (enable) {
|
||||
const pluginPath = pluginManager.getPluginPath();
|
||||
const fullPath = path.join(pluginPath, dirname);
|
||||
|
||||
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
|
||||
await pluginManager.loadDirectoryPlugin(dirname);
|
||||
} else {
|
||||
return sendError(res, 'Plugin directory not found: ' + dirname);
|
||||
const loaded = await pluginManager.loadPluginById(id);
|
||||
if (!loaded) {
|
||||
return sendError(res, 'Plugin not found: ' + id);
|
||||
}
|
||||
}
|
||||
// Disabling is handled by setPluginStatus
|
||||
|
||||
return sendSuccess(res, { message: 'Status updated successfully' });
|
||||
} catch (e: any) {
|
||||
@@ -161,47 +162,17 @@ export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
|
||||
};
|
||||
|
||||
export const UninstallPluginHandler: RequestHandler = async (req, res) => {
|
||||
const { name, filename, cleanData } = req.body;
|
||||
// If it's loaded, we use name. If it's disabled, we might use filename.
|
||||
const { id, cleanData } = req.body;
|
||||
|
||||
if (!id) return sendError(res, 'Plugin id is required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) {
|
||||
return sendError(res, 'Plugin Manager not found');
|
||||
}
|
||||
|
||||
// Check if loaded
|
||||
const plugin = pluginManager.getPluginInfo(name);
|
||||
let fsPath = '';
|
||||
|
||||
if (plugin) {
|
||||
// Active plugin
|
||||
await pluginManager.unregisterPlugin(name);
|
||||
if (plugin.pluginPath === pluginManager.getPluginPath()) {
|
||||
fsPath = plugin.entryPath;
|
||||
} else {
|
||||
fsPath = plugin.pluginPath;
|
||||
}
|
||||
} else {
|
||||
// Disabled or not loaded
|
||||
if (filename) {
|
||||
fsPath = path.join(pluginManager.getPluginPath(), filename);
|
||||
} else {
|
||||
return sendError(res, 'Plugin not found, provide filename if disabled');
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
await pluginManager.uninstallPlugin(id, cleanData);
|
||||
return sendSuccess(res, { message: 'Uninstalled successfully' });
|
||||
} catch (e: any) {
|
||||
return sendError(res, 'Failed to uninstall: ' + e.message);
|
||||
@@ -209,13 +180,13 @@ export const UninstallPluginHandler: RequestHandler = async (req, res) => {
|
||||
};
|
||||
|
||||
export const GetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
const name = req.query['name'] as string;
|
||||
if (!name) return sendError(res, 'Plugin Name is required');
|
||||
const id = req.query['id'] as string;
|
||||
if (!id) return sendError(res, 'Plugin id is required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) return sendError(res, 'Plugin Manager not found');
|
||||
|
||||
const plugin = pluginManager.getPluginInfo(name);
|
||||
const plugin = pluginManager.getPluginInfo(id);
|
||||
if (!plugin) return sendError(res, 'Plugin not loaded');
|
||||
|
||||
// Support legacy schema or new API
|
||||
@@ -230,7 +201,7 @@ export const GetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
// Default behavior: read from default config path
|
||||
try {
|
||||
// Use context configPath if available
|
||||
const configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(name);
|
||||
const configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(id);
|
||||
if (fs.existsSync(configPath)) {
|
||||
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
@@ -241,13 +212,13 @@ export const GetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
};
|
||||
|
||||
export const SetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
const { name, config } = req.body;
|
||||
if (!name || !config) return sendError(res, 'Name and Config required');
|
||||
const { id, config } = req.body;
|
||||
if (!id || !config) return sendError(res, 'Plugin id and config required');
|
||||
|
||||
const pluginManager = getPluginManager();
|
||||
if (!pluginManager) return sendError(res, 'Plugin Manager not found');
|
||||
|
||||
const plugin = pluginManager.getPluginInfo(name);
|
||||
const plugin = pluginManager.getPluginInfo(id);
|
||||
if (!plugin) return sendError(res, 'Plugin not loaded');
|
||||
|
||||
if (plugin.module.plugin_set_config) {
|
||||
@@ -260,7 +231,7 @@ export const SetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
} 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 configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(id);
|
||||
|
||||
const configDir = path.dirname(configPath);
|
||||
if (!fs.existsSync(configDir)) {
|
||||
@@ -269,7 +240,7 @@ export const SetPluginConfigHandler: RequestHandler = async (req, res) => {
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||
|
||||
// Auto-Reload plugin to apply changes
|
||||
await pluginManager.reloadPlugin(name);
|
||||
await pluginManager.reloadPlugin(id);
|
||||
|
||||
return sendSuccess(res, { message: 'Config saved and plugin reloaded' });
|
||||
} catch (e: any) {
|
||||
|
||||
@@ -8,6 +8,16 @@ 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';
|
||||
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
import { OB11PluginMangerAdapter } from '@/napcat-onebot/network/plugin-manger';
|
||||
|
||||
// Helper to get the plugin manager adapter
|
||||
const getPluginManager = (): OB11PluginMangerAdapter | null => {
|
||||
const ob11 = WebUiDataRuntime.getOneBotContext() as NapCatOneBot11Adapter;
|
||||
if (!ob11) return null;
|
||||
return ob11.networkManager.findSomeAdapter('plugin_manager') as OB11PluginMangerAdapter;
|
||||
};
|
||||
|
||||
// 插件商店源配置
|
||||
const PLUGIN_STORE_SOURCES = [
|
||||
@@ -242,6 +252,15 @@ export const InstallPluginFromStoreHandler: RequestHandler = async (req, res) =>
|
||||
// 删除临时文件
|
||||
fs.unlinkSync(tempZipPath);
|
||||
|
||||
// 如果 pluginManager 存在,立即注册插件
|
||||
const pluginManager = getPluginManager();
|
||||
if (pluginManager) {
|
||||
// 检查是否已注册,避免重复注册
|
||||
if (!pluginManager.getPluginInfo(id)) {
|
||||
await pluginManager.loadPluginById(id);
|
||||
}
|
||||
}
|
||||
|
||||
return sendSuccess(res, {
|
||||
message: 'Plugin installed successfully',
|
||||
plugin: plugin,
|
||||
@@ -315,6 +334,16 @@ export const InstallPluginFromStoreSSEHandler: RequestHandler = async (req, res)
|
||||
sendProgress('解压完成,正在清理...', 90);
|
||||
fs.unlinkSync(tempZipPath);
|
||||
|
||||
// 如果 pluginManager 存在,立即注册插件
|
||||
const pluginManager = getPluginManager();
|
||||
if (pluginManager) {
|
||||
// 检查是否已注册,避免重复注册
|
||||
if (!pluginManager.getPluginInfo(id)) {
|
||||
sendProgress('正在注册插件...', 95);
|
||||
await pluginManager.loadPluginById(id);
|
||||
}
|
||||
}
|
||||
|
||||
sendProgress('安装成功!', 100);
|
||||
res.write(`data: ${JSON.stringify({
|
||||
success: true,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Router } from 'express';
|
||||
import {
|
||||
GetMirrorListHandler,
|
||||
SetCustomMirrorHandler,
|
||||
TestMirrorsSSEHandler,
|
||||
TestSingleMirrorHandler
|
||||
} from '@/napcat-webui-backend/src/api/Mirror';
|
||||
|
||||
const router: Router = Router();
|
||||
|
||||
// 获取镜像列表
|
||||
router.get('/List', GetMirrorListHandler);
|
||||
|
||||
// 设置自定义镜像
|
||||
router.post('/SetCustom', SetCustomMirrorHandler);
|
||||
|
||||
// SSE 实时测速
|
||||
router.get('/Test/SSE', TestMirrorsSSEHandler);
|
||||
|
||||
// 测试单个镜像
|
||||
router.post('/Test', TestSingleMirrorHandler);
|
||||
|
||||
export { router as MirrorRouter };
|
||||
@@ -4,7 +4,8 @@ import {
|
||||
SetPluginStatusHandler,
|
||||
UninstallPluginHandler,
|
||||
GetPluginConfigHandler,
|
||||
SetPluginConfigHandler
|
||||
SetPluginConfigHandler,
|
||||
RegisterPluginManagerHandler
|
||||
} from '@/napcat-webui-backend/src/api/Plugin';
|
||||
import {
|
||||
GetPluginStoreListHandler,
|
||||
@@ -20,6 +21,7 @@ router.post('/SetStatus', SetPluginStatusHandler);
|
||||
router.post('/Uninstall', UninstallPluginHandler);
|
||||
router.get('/Config', GetPluginConfigHandler);
|
||||
router.post('/Config', SetPluginConfigHandler);
|
||||
router.post('/RegisterManager', RegisterPluginManagerHandler);
|
||||
|
||||
// 插件商店相关路由
|
||||
router.get('/Store/List', GetPluginStoreListHandler);
|
||||
|
||||
@@ -18,6 +18,7 @@ import { UpdateNapCatRouter } from './UpdateNapCat';
|
||||
import DebugRouter from '@/napcat-webui-backend/src/api/Debug';
|
||||
import { ProcessRouter } from './Process';
|
||||
import { PluginRouter } from './Plugin';
|
||||
import { MirrorRouter } from './Mirror';
|
||||
|
||||
const router: Router = Router();
|
||||
|
||||
@@ -50,5 +51,7 @@ router.use('/Debug', DebugRouter);
|
||||
router.use('/Process', ProcessRouter);
|
||||
// router:插件管理相关路由
|
||||
router.use('/Plugin', PluginRouter);
|
||||
// router:镜像管理相关路由
|
||||
router.use('/Mirror', MirrorRouter);
|
||||
|
||||
export { router as ALLRouter };
|
||||
@@ -24,7 +24,7 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
|
||||
hasConfig = false,
|
||||
}) => {
|
||||
const { name, version, author, description, status } = data;
|
||||
const isEnabled = status !== 'disabled';
|
||||
const isEnabled = status === 'active';
|
||||
const [processing, setProcessing] = useState(false);
|
||||
|
||||
const handleToggle = () => {
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
import { Button } from '@heroui/button';
|
||||
import { Chip } from '@heroui/chip';
|
||||
import { useState } from 'react';
|
||||
import { IoMdDownload } from 'react-icons/io';
|
||||
import { IoMdDownload, IoMdRefresh, IoMdCheckmarkCircle } from 'react-icons/io';
|
||||
|
||||
import DisplayCardContainer from './container';
|
||||
import { PluginStoreItem } from '@/types/plugin-store';
|
||||
|
||||
export type InstallStatus = 'not-installed' | 'installed' | 'update-available';
|
||||
|
||||
export interface PluginStoreCardProps {
|
||||
data: PluginStoreItem;
|
||||
onInstall: () => Promise<void>;
|
||||
installStatus?: InstallStatus;
|
||||
installedVersion?: string;
|
||||
}
|
||||
|
||||
const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
|
||||
data,
|
||||
onInstall,
|
||||
installStatus = 'not-installed',
|
||||
}) => {
|
||||
const { name, version, author, description, tags, id } = data;
|
||||
const [processing, setProcessing] = useState(false);
|
||||
@@ -23,19 +28,65 @@ const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
|
||||
onInstall().finally(() => setProcessing(false));
|
||||
};
|
||||
|
||||
// 根据安装状态返回按钮配置
|
||||
const getButtonConfig = () => {
|
||||
switch (installStatus) {
|
||||
case 'installed':
|
||||
return {
|
||||
text: '重新安装',
|
||||
icon: <IoMdRefresh size={16} />,
|
||||
color: 'default' as const,
|
||||
};
|
||||
case 'update-available':
|
||||
return {
|
||||
text: '更新',
|
||||
icon: <IoMdDownload size={16} />,
|
||||
color: 'success' as const,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
text: '安装',
|
||||
icon: <IoMdDownload size={16} />,
|
||||
color: 'primary' as const,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const buttonConfig = getButtonConfig();
|
||||
|
||||
return (
|
||||
<DisplayCardContainer
|
||||
className='w-full max-w-[420px]'
|
||||
title={name}
|
||||
tag={
|
||||
<Chip
|
||||
className="ml-auto"
|
||||
color="primary"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
v{version}
|
||||
</Chip>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{installStatus === 'installed' && (
|
||||
<Chip
|
||||
color="success"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
startContent={<IoMdCheckmarkCircle size={14} />}
|
||||
>
|
||||
已安装
|
||||
</Chip>
|
||||
)}
|
||||
{installStatus === 'update-available' && (
|
||||
<Chip
|
||||
color="warning"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
可更新
|
||||
</Chip>
|
||||
)}
|
||||
<Chip
|
||||
color="primary"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
v{version}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
enableSwitch={undefined}
|
||||
action={
|
||||
@@ -43,13 +94,13 @@ const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
|
||||
fullWidth
|
||||
radius='full'
|
||||
size='sm'
|
||||
color='primary'
|
||||
startContent={<IoMdDownload size={16} />}
|
||||
color={buttonConfig.color}
|
||||
startContent={buttonConfig.icon}
|
||||
onPress={handleInstall}
|
||||
isLoading={processing}
|
||||
isDisabled={processing}
|
||||
>
|
||||
安装
|
||||
{buttonConfig.text}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter } from '@heroui/modal';
|
||||
import { Button } from '@heroui/button';
|
||||
import { Chip } from '@heroui/chip';
|
||||
import { Tooltip } from '@heroui/tooltip';
|
||||
import { IoMdFlash, IoMdCheckmark, IoMdClose } from 'react-icons/io';
|
||||
import clsx from 'clsx';
|
||||
|
||||
import MirrorManager, { MirrorTestResult } from '@/controllers/mirror_manager';
|
||||
|
||||
interface MirrorSelectorModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (mirror: string | undefined) => void;
|
||||
currentMirror?: string;
|
||||
type?: 'file' | 'raw';
|
||||
}
|
||||
|
||||
export default function MirrorSelectorModal ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSelect,
|
||||
currentMirror,
|
||||
type = 'file',
|
||||
}: MirrorSelectorModalProps) {
|
||||
const [mirrors, setMirrors] = useState<string[]>([]);
|
||||
const [selectedMirror, setSelectedMirror] = useState<string>(currentMirror || 'auto');
|
||||
const [testResults, setTestResults] = useState<Map<string, MirrorTestResult>>(new Map());
|
||||
const [isTesting, setIsTesting] = useState(false);
|
||||
const [testProgress, setTestProgress] = useState(0);
|
||||
const [testMessage, setTestMessage] = useState('');
|
||||
const [fastestMirror, setFastestMirror] = useState<string | null>(null);
|
||||
|
||||
// 加载镜像列表
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadMirrors();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const loadMirrors = async () => {
|
||||
try {
|
||||
const data = await MirrorManager.getMirrorList();
|
||||
const mirrorList = type === 'raw' ? data.rawMirrors : data.fileMirrors;
|
||||
setMirrors(mirrorList);
|
||||
if (data.customMirror) {
|
||||
setSelectedMirror(data.customMirror);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load mirrors:', e);
|
||||
}
|
||||
};
|
||||
|
||||
const startSpeedTest = () => {
|
||||
setIsTesting(true);
|
||||
setTestProgress(0);
|
||||
setTestResults(new Map());
|
||||
setFastestMirror(null);
|
||||
setTestMessage('准备测速...');
|
||||
|
||||
MirrorManager.testMirrorsSSE(type, {
|
||||
onStart: (data) => {
|
||||
setTestMessage(data.message);
|
||||
},
|
||||
onTesting: (data) => {
|
||||
setTestProgress((data.index / data.total) * 100);
|
||||
setTestMessage(data.message);
|
||||
},
|
||||
onResult: (data) => {
|
||||
setTestResults((prev) => {
|
||||
const newMap = new Map(prev);
|
||||
newMap.set(data.result.mirror, data.result);
|
||||
return newMap;
|
||||
});
|
||||
setTestProgress(((data.index + 1) / data.total) * 100);
|
||||
},
|
||||
onComplete: (data) => {
|
||||
setIsTesting(false);
|
||||
setTestProgress(100);
|
||||
setTestMessage(data.message);
|
||||
if (data.fastest) {
|
||||
setFastestMirror(data.fastest.mirror);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
setIsTesting(false);
|
||||
setTestMessage(`测速失败: ${error}`);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
const mirror = selectedMirror === 'auto' ? undefined : selectedMirror;
|
||||
onSelect(mirror);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
size="2xl"
|
||||
scrollBehavior="inside"
|
||||
classNames={{
|
||||
backdrop: 'z-[200]',
|
||||
wrapper: 'z-[200]',
|
||||
}}
|
||||
>
|
||||
<ModalContent>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
<div className="flex items-center justify-between pr-8">
|
||||
<span>选择镜像源</span>
|
||||
<Button
|
||||
size="sm"
|
||||
color="primary"
|
||||
variant="flat"
|
||||
startContent={!isTesting && <IoMdFlash />}
|
||||
onPress={startSpeedTest}
|
||||
isLoading={isTesting}
|
||||
>
|
||||
{isTesting ? '测速中...' : '一键测速'}
|
||||
</Button>
|
||||
</div>
|
||||
{isTesting && (
|
||||
<div className="mt-2">
|
||||
<div className="w-full bg-default-200 rounded-full h-2">
|
||||
<div
|
||||
className="bg-primary h-2 rounded-full transition-all duration-300"
|
||||
style={{ width: `${testProgress}%` }}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-default-500 mt-1">{testMessage}</p>
|
||||
</div>
|
||||
)}
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* 自动选择选项 */}
|
||||
<MirrorOption
|
||||
value="auto"
|
||||
label="自动选择"
|
||||
description="系统自动选择最快的镜像源"
|
||||
isSelected={selectedMirror === 'auto'}
|
||||
onSelect={() => setSelectedMirror('auto')}
|
||||
badge={<Chip size="sm" color="primary" variant="flat">推荐</Chip>}
|
||||
/>
|
||||
|
||||
{/* 原始 GitHub */}
|
||||
<MirrorOption
|
||||
value="https://github.com"
|
||||
label="GitHub 原始"
|
||||
description="直连 GitHub(可能较慢)"
|
||||
isSelected={selectedMirror === 'https://github.com'}
|
||||
onSelect={() => setSelectedMirror('https://github.com')}
|
||||
testResult={testResults.get('https://github.com (原始)')}
|
||||
isFastest={fastestMirror === 'https://github.com (原始)'}
|
||||
/>
|
||||
|
||||
{/* 镜像列表 */}
|
||||
{mirrors.map((mirror) => {
|
||||
if (!mirror) return null;
|
||||
const result = testResults.get(mirror);
|
||||
const isFastest = fastestMirror === mirror;
|
||||
|
||||
let hostname = mirror;
|
||||
try {
|
||||
hostname = new URL(mirror).hostname;
|
||||
} catch { }
|
||||
|
||||
return (
|
||||
<MirrorOption
|
||||
key={mirror}
|
||||
value={mirror}
|
||||
label={hostname}
|
||||
description={mirror}
|
||||
isSelected={selectedMirror === mirror}
|
||||
onSelect={() => setSelectedMirror(mirror)}
|
||||
testResult={result}
|
||||
isFastest={isFastest}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onPress={onClose}>
|
||||
取消
|
||||
</Button>
|
||||
<Button color="primary" onPress={handleConfirm}>
|
||||
确认选择
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// 镜像选项组件
|
||||
interface MirrorOptionProps {
|
||||
value: string;
|
||||
label: string;
|
||||
description: string;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
testResult?: MirrorTestResult;
|
||||
isFastest?: boolean;
|
||||
badge?: React.ReactNode;
|
||||
}
|
||||
|
||||
function MirrorOption ({
|
||||
label,
|
||||
description,
|
||||
isSelected,
|
||||
onSelect,
|
||||
testResult,
|
||||
isFastest,
|
||||
badge,
|
||||
}: MirrorOptionProps) {
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'flex items-center justify-between p-3 rounded-lg cursor-pointer transition-all',
|
||||
'bg-content1 hover:bg-content2 border-2',
|
||||
isSelected ? 'border-primary' : 'border-transparent',
|
||||
isFastest && 'ring-2 ring-success'
|
||||
)}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium">{label}</p>
|
||||
<p className="text-xs text-default-500 truncate">{description}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 ml-2">
|
||||
{badge}
|
||||
{isFastest && !badge && (
|
||||
<Chip size="sm" color="success" variant="flat">最快</Chip>
|
||||
)}
|
||||
{testResult && <MirrorStatus result={testResult} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 镜像状态显示组件
|
||||
function MirrorStatus ({ result }: { result: MirrorTestResult; }) {
|
||||
const formatLatency = (latency: number) => {
|
||||
if (latency >= 5000) return '>5s';
|
||||
if (latency >= 1000) return `${(latency / 1000).toFixed(1)}s`;
|
||||
return `${latency}ms`;
|
||||
};
|
||||
|
||||
if (!result.success) {
|
||||
return (
|
||||
<Tooltip content={result.error || '连接失败'}>
|
||||
<Chip
|
||||
size="sm"
|
||||
color="danger"
|
||||
variant="flat"
|
||||
startContent={<IoMdClose size={14} />}
|
||||
>
|
||||
失败
|
||||
</Chip>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
const getColor = (): 'success' | 'warning' | 'danger' => {
|
||||
if (result.latency < 300) return 'success';
|
||||
if (result.latency < 1000) return 'warning';
|
||||
return 'danger';
|
||||
};
|
||||
|
||||
return (
|
||||
<Chip
|
||||
size="sm"
|
||||
color={getColor()}
|
||||
variant="flat"
|
||||
startContent={<IoMdCheckmark size={14} />}
|
||||
>
|
||||
{formatLatency(result.latency)}
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
@@ -8,18 +8,22 @@ import { Switch } from '@heroui/switch';
|
||||
import { Pagination } from '@heroui/pagination';
|
||||
import { Tabs, Tab } from '@heroui/tabs';
|
||||
import { Input } from '@heroui/input';
|
||||
import { Button } from '@heroui/button';
|
||||
import { useLocalStorage, useDebounce } from '@uidotdev/usehooks';
|
||||
import { useRequest } from 'ahooks';
|
||||
import clsx from 'clsx';
|
||||
import { FaCircleInfo, FaQq } from 'react-icons/fa6';
|
||||
import { IoLogoChrome, IoLogoOctocat, IoSearch } from 'react-icons/io5';
|
||||
import { IoMdFlash, IoMdCheckmark, IoMdSettings } from 'react-icons/io';
|
||||
import { RiMacFill } from 'react-icons/ri';
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
import key from '@/const/key';
|
||||
import WebUIManager from '@/controllers/webui_manager';
|
||||
import MirrorManager from '@/controllers/mirror_manager';
|
||||
import useDialog from '@/hooks/use-dialog';
|
||||
import Modal from '@/components/modal';
|
||||
import MirrorSelectorModal from '@/components/mirror_selector_modal';
|
||||
import { hasNewVersion, compareVersion } from '@/utils/version';
|
||||
|
||||
|
||||
@@ -304,17 +308,54 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const debouncedSearch = useDebounce(searchQuery, 300);
|
||||
|
||||
// 镜像相关状态
|
||||
const [selectedMirror, setSelectedMirror] = useState<string | undefined>(undefined);
|
||||
const { data: mirrorsData } = useRequest(WebUIManager.getMirrors, {
|
||||
cacheKey: 'napcat-mirrors',
|
||||
staleTime: 60 * 60 * 1000,
|
||||
});
|
||||
const mirrors = mirrorsData?.mirrors || [];
|
||||
const [mirrorLatency, setMirrorLatency] = useState<number | null>(null);
|
||||
const [mirrorTesting, setMirrorTesting] = useState(false);
|
||||
const [mirrorModalOpen, setMirrorModalOpen] = useState(false);
|
||||
|
||||
const pageSize = 15;
|
||||
// 测试当前镜像速度
|
||||
const testCurrentMirror = async () => {
|
||||
setMirrorTesting(true);
|
||||
try {
|
||||
const result = await MirrorManager.testSingleMirror(selectedMirror || '', 'file');
|
||||
if (result.success) {
|
||||
setMirrorLatency(result.latency);
|
||||
} else {
|
||||
setMirrorLatency(null);
|
||||
}
|
||||
} catch (e) {
|
||||
setMirrorLatency(null);
|
||||
} finally {
|
||||
setMirrorTesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatLatency = (latency: number) => {
|
||||
if (latency >= 5000) return '>5s';
|
||||
if (latency >= 1000) return `${(latency / 1000).toFixed(1)}s`;
|
||||
return `${latency}ms`;
|
||||
};
|
||||
|
||||
const getLatencyColor = (latency: number | null): 'success' | 'warning' | 'danger' | 'default' => {
|
||||
if (latency === null) return 'default';
|
||||
if (latency < 300) return 'success';
|
||||
if (latency < 1000) return 'warning';
|
||||
return 'danger';
|
||||
};
|
||||
|
||||
const getMirrorDisplayName = () => {
|
||||
if (!selectedMirror) return '自动选择';
|
||||
try {
|
||||
return new URL(selectedMirror).hostname;
|
||||
} catch {
|
||||
return selectedMirror;
|
||||
}
|
||||
};
|
||||
|
||||
// 获取所有可用版本(带分页、过滤和搜索)
|
||||
// 懒加载:根据 activeTab 只获取对应类型的版本
|
||||
const pageSize = 15;
|
||||
const { data: releasesData, loading: releasesLoading, error: releasesError } = useRequest(
|
||||
() => WebUIManager.getAllReleases({
|
||||
page: currentPage,
|
||||
@@ -502,46 +543,78 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
|
||||
<Tab key='action' title='临时版本 (Action)' />
|
||||
</Tabs>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{/* 搜索框 */}
|
||||
<Input
|
||||
placeholder='搜索版本号...'
|
||||
size='sm'
|
||||
value={searchQuery}
|
||||
onValueChange={(value) => {
|
||||
setSearchQuery(value);
|
||||
setCurrentPage(1);
|
||||
setSelectedVersion(null);
|
||||
}}
|
||||
startContent={<IoSearch className='text-default-400' />}
|
||||
isClearable
|
||||
onClear={() => setSearchQuery('')}
|
||||
classNames={{
|
||||
inputWrapper: 'h-9',
|
||||
base: 'flex-1'
|
||||
}}
|
||||
/>
|
||||
{/* 下载镜像状态卡片 */}
|
||||
<Card className="bg-default-100/50 shadow-sm">
|
||||
<CardBody className="py-2 px-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-default-500">镜像源:</span>
|
||||
<span className="text-sm font-medium">{getMirrorDisplayName()}</span>
|
||||
{mirrorLatency !== null && (
|
||||
<Chip
|
||||
size="sm"
|
||||
color={getLatencyColor(mirrorLatency)}
|
||||
variant="flat"
|
||||
startContent={<IoMdCheckmark size={12} />}
|
||||
>
|
||||
{formatLatency(mirrorLatency)}
|
||||
</Chip>
|
||||
)}
|
||||
{mirrorLatency === null && !mirrorTesting && (
|
||||
<Chip size="sm" color="default" variant="flat">
|
||||
未测试
|
||||
</Chip>
|
||||
)}
|
||||
{mirrorTesting && (
|
||||
<Chip size="sm" color="primary" variant="flat">
|
||||
测速中...
|
||||
</Chip>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Tooltip content="测速">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={testCurrentMirror}
|
||||
isLoading={mirrorTesting}
|
||||
>
|
||||
<IoMdFlash size={16} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content="切换镜像">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => setMirrorModalOpen(true)}
|
||||
>
|
||||
<IoMdSettings size={16} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 镜像选择 */}
|
||||
<Select
|
||||
placeholder="自动选择 (默认)"
|
||||
selectedKeys={selectedMirror ? [selectedMirror] : ['default']}
|
||||
onSelectionChange={(keys) => {
|
||||
const m = Array.from(keys)[0] as string;
|
||||
setSelectedMirror(m === 'default' ? undefined : m);
|
||||
}}
|
||||
size="sm"
|
||||
className="w-48"
|
||||
classNames={{ trigger: 'h-9 min-h-9' }}
|
||||
aria-label="选择镜像源"
|
||||
>
|
||||
{['default', ...mirrors].map(m => (
|
||||
<SelectItem key={m} textValue={m === 'default' ? '自动选择' : m}>
|
||||
{m === 'default' ? '自动选择 (默认)' : m}
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
{/* 搜索框 */}
|
||||
<Input
|
||||
placeholder='搜索版本号...'
|
||||
size='sm'
|
||||
value={searchQuery}
|
||||
onValueChange={(value) => {
|
||||
setSearchQuery(value);
|
||||
setCurrentPage(1);
|
||||
setSelectedVersion(null);
|
||||
}}
|
||||
startContent={<IoSearch className='text-default-400' />}
|
||||
isClearable
|
||||
onClear={() => setSearchQuery('')}
|
||||
classNames={{
|
||||
inputWrapper: 'h-9',
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 版本选择 */}
|
||||
<div className='space-y-2'>
|
||||
@@ -703,6 +776,18 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
|
||||
{isSelectedDowngrade ? '确认降级更新' : '更新到此版本'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 镜像选择弹窗 */}
|
||||
<MirrorSelectorModal
|
||||
isOpen={mirrorModalOpen}
|
||||
onClose={() => setMirrorModalOpen(false)}
|
||||
currentMirror={selectedMirror}
|
||||
onSelect={(mirror) => {
|
||||
setSelectedMirror(mirror || undefined);
|
||||
setMirrorLatency(null);
|
||||
}}
|
||||
type="file"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { EventSourcePolyfill } from 'event-source-polyfill';
|
||||
import { serverRequest } from '@/utils/request';
|
||||
import key from '@/const/key';
|
||||
|
||||
export interface MirrorTestResult {
|
||||
mirror: string;
|
||||
latency: number;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface MirrorListResponse {
|
||||
fileMirrors: string[];
|
||||
rawMirrors: string[];
|
||||
customMirror?: string;
|
||||
timeout: number;
|
||||
}
|
||||
|
||||
export default class MirrorManager {
|
||||
/**
|
||||
* 获取镜像列表
|
||||
*/
|
||||
public static async getMirrorList (): Promise<MirrorListResponse> {
|
||||
const { data } = await serverRequest.get<ServerResponse<MirrorListResponse>>('/Mirror/List');
|
||||
return data.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置自定义镜像
|
||||
*/
|
||||
public static async setCustomMirror (mirror: string): Promise<void> {
|
||||
await serverRequest.post('/Mirror/SetCustom', { mirror });
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试单个镜像
|
||||
*/
|
||||
public static async testSingleMirror (mirror: string, type: 'file' | 'raw' = 'file'): Promise<MirrorTestResult> {
|
||||
const { data } = await serverRequest.post<ServerResponse<MirrorTestResult>>('/Mirror/Test', { mirror, type });
|
||||
return data.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE 实时测速所有镜像
|
||||
*/
|
||||
public static testMirrorsSSE (
|
||||
type: 'file' | 'raw' = 'file',
|
||||
callbacks: {
|
||||
onStart?: (data: { total: number; message: string; }) => void;
|
||||
onTesting?: (data: { index: number; total: number; mirror: string; message: string; }) => void;
|
||||
onResult?: (data: { index: number; total: number; result: MirrorTestResult; }) => void;
|
||||
onComplete?: (data: { results: MirrorTestResult[]; failed: MirrorTestResult[]; fastest: MirrorTestResult | null; message: string; }) => void;
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
): EventSourcePolyfill {
|
||||
const token = localStorage.getItem(key.token);
|
||||
if (!token) {
|
||||
throw new Error('未登录');
|
||||
}
|
||||
const _token = JSON.parse(token);
|
||||
|
||||
const eventSource = new EventSourcePolyfill(
|
||||
`/api/Mirror/Test/SSE?type=${type}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${_token}`,
|
||||
Accept: 'text/event-stream',
|
||||
},
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
switch (data.type) {
|
||||
case 'start':
|
||||
callbacks.onStart?.(data);
|
||||
break;
|
||||
case 'testing':
|
||||
callbacks.onTesting?.(data);
|
||||
break;
|
||||
case 'result':
|
||||
callbacks.onResult?.(data);
|
||||
break;
|
||||
case 'complete':
|
||||
callbacks.onComplete?.(data);
|
||||
eventSource.close();
|
||||
break;
|
||||
case 'error':
|
||||
callbacks.onError?.(data.error);
|
||||
eventSource.close();
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse SSE message:', e);
|
||||
}
|
||||
};
|
||||
|
||||
eventSource.onerror = (error) => {
|
||||
console.error('SSE连接出错:', error);
|
||||
callbacks.onError?.('连接中断');
|
||||
eventSource.close();
|
||||
};
|
||||
|
||||
return eventSource;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,34 @@
|
||||
import { serverRequest } from '@/utils/request';
|
||||
import { PluginStoreList, PluginStoreItem } from '@/types/plugin-store';
|
||||
|
||||
/** 插件状态 */
|
||||
export type PluginStatus = 'active' | 'disabled' | 'stopped';
|
||||
|
||||
/** 插件信息 */
|
||||
export interface PluginItem {
|
||||
/** 显示名称 (优先 package.json 的 plugin 字段) */
|
||||
name: string;
|
||||
/** 包名 (package name),用于 API 操作 */
|
||||
id: string;
|
||||
/** 版本号 */
|
||||
version: string;
|
||||
/** 描述 */
|
||||
description: string;
|
||||
/** 作者 */
|
||||
author: string;
|
||||
status: 'active' | 'disabled' | 'stopped';
|
||||
filename?: string;
|
||||
/** 状态: active-运行中, disabled-已禁用, stopped-已停止 */
|
||||
status: PluginStatus;
|
||||
/** 是否有配置项 */
|
||||
hasConfig?: boolean;
|
||||
}
|
||||
|
||||
/** 插件列表响应 */
|
||||
export interface PluginListResponse {
|
||||
plugins: PluginItem[];
|
||||
pluginManagerNotFound: boolean;
|
||||
}
|
||||
|
||||
/** 插件配置项定义 */
|
||||
export interface PluginConfigSchemaItem {
|
||||
key: string;
|
||||
type: 'string' | 'number' | 'boolean' | 'select' | 'multi-select' | 'html' | 'text';
|
||||
@@ -26,58 +39,108 @@ export interface PluginConfigSchemaItem {
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
/** 插件配置响应 */
|
||||
export interface PluginConfigResponse {
|
||||
schema: PluginConfigSchemaItem[];
|
||||
config: any;
|
||||
config: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 服务端响应 */
|
||||
export interface ServerResponse<T> {
|
||||
code: number;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件管理器 API
|
||||
*/
|
||||
export default class PluginManager {
|
||||
public static async getPluginList () {
|
||||
/**
|
||||
* 获取插件列表
|
||||
*/
|
||||
public static async getPluginList (): Promise<PluginListResponse> {
|
||||
const { data } = await serverRequest.get<ServerResponse<PluginListResponse>>('/Plugin/List');
|
||||
return data.data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static async setPluginStatus (name: string, enable: boolean, filename?: string) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/SetStatus', { name, enable, filename });
|
||||
/**
|
||||
* 手动注册插件管理器到 NetworkManager
|
||||
*/
|
||||
public static async registerPluginManager (): Promise<{ message: string; }> {
|
||||
const { data } = await serverRequest.post<ServerResponse<{ message: string; }>>('/Plugin/RegisterManager');
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async uninstallPlugin (name: string, filename?: string, cleanData?: boolean) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { name, filename, cleanData });
|
||||
/**
|
||||
* 设置插件状态(启用/禁用)
|
||||
* @param id 插件包名
|
||||
* @param enable 是否启用
|
||||
*/
|
||||
public static async setPluginStatus (id: string, enable: boolean): Promise<void> {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/SetStatus', { id, enable });
|
||||
}
|
||||
|
||||
// 插件商店相关方法
|
||||
public static async getPluginStoreList () {
|
||||
/**
|
||||
* 卸载插件
|
||||
* @param id 插件包名
|
||||
* @param cleanData 是否清理数据
|
||||
*/
|
||||
public static async uninstallPlugin (id: string, cleanData?: boolean): Promise<void> {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { id, cleanData });
|
||||
}
|
||||
|
||||
// ==================== 插件商店 ====================
|
||||
|
||||
/**
|
||||
* 获取插件商店列表
|
||||
*/
|
||||
public static async getPluginStoreList (): Promise<PluginStoreList> {
|
||||
const { data } = await serverRequest.get<ServerResponse<PluginStoreList>>('/Plugin/Store/List');
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async getPluginStoreDetail (id: string) {
|
||||
/**
|
||||
* 获取插件商店详情
|
||||
* @param id 插件 ID
|
||||
*/
|
||||
public static async getPluginStoreDetail (id: string): Promise<PluginStoreItem> {
|
||||
const { data } = await serverRequest.get<ServerResponse<PluginStoreItem>>(`/Plugin/Store/Detail/${id}`);
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async installPluginFromStore (id: string, mirror?: string) {
|
||||
// 插件安装可能需要较长时间(下载+解压),设置5分钟超时
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Store/Install', { id, mirror }, {
|
||||
timeout: 300000, // 5分钟
|
||||
});
|
||||
/**
|
||||
* 从商店安装插件
|
||||
* @param id 插件 ID
|
||||
* @param mirror 镜像源
|
||||
*/
|
||||
public static async installPluginFromStore (id: string, mirror?: string): Promise<void> {
|
||||
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 } });
|
||||
// ==================== 插件配置 ====================
|
||||
|
||||
/**
|
||||
* 获取插件配置
|
||||
* @param id 插件包名
|
||||
*/
|
||||
public static async getPluginConfig (id: string): Promise<PluginConfigResponse> {
|
||||
const { data } = await serverRequest.get<ServerResponse<PluginConfigResponse>>('/Plugin/Config', {
|
||||
params: { id }
|
||||
});
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async setPluginConfig (name: string, config: any) {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Config', { name, config });
|
||||
/**
|
||||
* 设置插件配置
|
||||
* @param id 插件包名
|
||||
* @param config 配置内容
|
||||
*/
|
||||
public static async setPluginConfig (id: string, config: Record<string, unknown>): Promise<void> {
|
||||
await serverRequest.post<ServerResponse<void>>('/Plugin/Config', { id, config });
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export default function PluginPage () {
|
||||
const dialog = useDialog();
|
||||
|
||||
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
||||
const [currentPluginName, setCurrentPluginName] = useState<string>('');
|
||||
const [currentPluginId, setCurrentPluginId] = useState<string>('');
|
||||
|
||||
const loadPlugins = async () => {
|
||||
setLoading(true);
|
||||
@@ -49,7 +49,7 @@ export default function PluginPage () {
|
||||
const actionText = isEnable ? '启用' : '禁用';
|
||||
const loadingToast = toast.loading(`${actionText}中...`);
|
||||
try {
|
||||
await PluginManager.setPluginStatus(plugin.name, isEnable, plugin.filename);
|
||||
await PluginManager.setPluginStatus(plugin.id, isEnable);
|
||||
toast.success(`${actionText}成功`, { id: loadingToast });
|
||||
loadPlugins();
|
||||
} catch (e: any) {
|
||||
@@ -85,7 +85,7 @@ export default function PluginPage () {
|
||||
|
||||
const loadingToast = toast.loading('卸载中...');
|
||||
try {
|
||||
await PluginManager.uninstallPlugin(plugin.name, plugin.filename, cleanData);
|
||||
await PluginManager.uninstallPlugin(plugin.id, cleanData);
|
||||
toast.success('卸载成功', { id: loadingToast });
|
||||
loadPlugins();
|
||||
resolve();
|
||||
@@ -102,7 +102,7 @@ export default function PluginPage () {
|
||||
};
|
||||
|
||||
const handleConfig = (plugin: PluginItem) => {
|
||||
setCurrentPluginName(plugin.name); // Use Loaded Name for config lookup
|
||||
setCurrentPluginId(plugin.id);
|
||||
onOpen();
|
||||
};
|
||||
|
||||
@@ -114,7 +114,7 @@ export default function PluginPage () {
|
||||
<PluginConfigModal
|
||||
isOpen={isOpen}
|
||||
onOpenChange={onOpenChange}
|
||||
pluginName={currentPluginName}
|
||||
pluginId={currentPluginId}
|
||||
/>
|
||||
|
||||
<div className='flex mb-6 items-center gap-4'>
|
||||
@@ -145,7 +145,7 @@ export default function PluginPage () {
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 justify-start items-stretch gap-x-2 gap-y-4'>
|
||||
{plugins.map(plugin => (
|
||||
<PluginDisplayCard
|
||||
key={plugin.name}
|
||||
key={plugin.id}
|
||||
data={plugin}
|
||||
onToggleStatus={() => handleToggle(plugin)}
|
||||
onUninstall={() => handleUninstall(plugin)}
|
||||
|
||||
@@ -10,31 +10,32 @@ import PluginManager, { PluginConfigSchemaItem } from '@/controllers/plugin_mana
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
onOpenChange: () => void;
|
||||
pluginName: string;
|
||||
/** 插件包名 (id) */
|
||||
pluginId: string;
|
||||
}
|
||||
|
||||
export default function PluginConfigModal ({ isOpen, onOpenChange, pluginName }: Props) {
|
||||
export default function PluginConfigModal ({ isOpen, onOpenChange, pluginId }: Props) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [schema, setSchema] = useState<PluginConfigSchemaItem[]>([]);
|
||||
const [config, setConfig] = useState<any>({});
|
||||
const [config, setConfig] = useState<Record<string, unknown>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && pluginName) {
|
||||
if (isOpen && pluginId) {
|
||||
loadConfig();
|
||||
}
|
||||
}, [isOpen, pluginName]);
|
||||
}, [isOpen, pluginId]);
|
||||
|
||||
const loadConfig = async () => {
|
||||
setLoading(true);
|
||||
setSchema([]);
|
||||
setConfig({});
|
||||
try {
|
||||
const data = await PluginManager.getPluginConfig(pluginName);
|
||||
const data = await PluginManager.getPluginConfig(pluginId);
|
||||
setSchema(data.schema || []);
|
||||
setConfig(data.config || {});
|
||||
} catch (e: any) {
|
||||
toast.error('Load config failed: ' + e.message);
|
||||
toast.error('加载配置失败: ' + e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -43,7 +44,7 @@ export default function PluginConfigModal ({ isOpen, onOpenChange, pluginName }:
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await PluginManager.setPluginConfig(pluginName, config);
|
||||
await PluginManager.setPluginConfig(pluginId, config);
|
||||
toast.success('Configuration saved');
|
||||
onOpenChange();
|
||||
} catch (e: any) {
|
||||
@@ -177,7 +178,7 @@ export default function PluginConfigModal ({ isOpen, onOpenChange, pluginName }:
|
||||
{(onClose) => (
|
||||
<>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
Configuration: {pluginName}
|
||||
插件配置: {pluginId}
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
{loading ? (
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { Button } from '@heroui/button';
|
||||
import { Input } from '@heroui/input';
|
||||
import { Select, SelectItem } from '@heroui/select';
|
||||
import { Tab, Tabs } from '@heroui/tabs';
|
||||
import { Card, CardBody } from '@heroui/card';
|
||||
import { Tooltip } from '@heroui/tooltip';
|
||||
import { Spinner } from '@heroui/spinner';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { IoMdRefresh, IoMdSearch } from 'react-icons/io';
|
||||
import { IoMdRefresh, IoMdSearch, IoMdSettings } 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 PluginStoreCard, { InstallStatus } from '@/components/display_card/plugin_store_card';
|
||||
import PluginManager, { PluginItem } from '@/controllers/plugin_manager';
|
||||
import MirrorSelectorModal from '@/components/mirror_selector_modal';
|
||||
import { PluginStoreItem } from '@/types/plugin-store';
|
||||
import useDialog from '@/hooks/use-dialog';
|
||||
import key from '@/const/key';
|
||||
@@ -35,23 +35,32 @@ const EmptySection: React.FC<EmptySectionProps> = ({ isEmpty }) => {
|
||||
|
||||
export default function PluginStorePage () {
|
||||
const [plugins, setPlugins] = useState<PluginStoreItem[]>([]);
|
||||
const [installedPlugins, setInstalledPlugins] = useState<PluginItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<string>('all');
|
||||
const [pluginManagerNotFound, setPluginManagerNotFound] = useState(false);
|
||||
const dialog = useDialog();
|
||||
|
||||
// 获取镜像列表
|
||||
const { data: mirrorsData } = useRequest(WebUIManager.getMirrors, {
|
||||
cacheKey: 'napcat-mirrors',
|
||||
staleTime: 60 * 60 * 1000,
|
||||
});
|
||||
const mirrors = mirrorsData?.mirrors || [];
|
||||
// 商店列表源相关状态
|
||||
const [storeSourceModalOpen, setStoreSourceModalOpen] = useState(false);
|
||||
const [currentStoreSource, setCurrentStoreSource] = useState<string | undefined>(undefined);
|
||||
|
||||
// 下载镜像弹窗状态(安装时使用)
|
||||
const [downloadMirrorModalOpen, setDownloadMirrorModalOpen] = useState(false);
|
||||
const [pendingInstallPlugin, setPendingInstallPlugin] = useState<PluginStoreItem | null>(null);
|
||||
const [selectedDownloadMirror, setSelectedDownloadMirror] = useState<string | undefined>(undefined);
|
||||
|
||||
const loadPlugins = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await PluginManager.getPluginStoreList();
|
||||
setPlugins(data.plugins);
|
||||
|
||||
// 检查插件管理器是否已加载
|
||||
const listResult = await PluginManager.getPluginList();
|
||||
setPluginManagerNotFound(listResult.pluginManagerNotFound);
|
||||
setInstalledPlugins(listResult.plugins || []);
|
||||
} catch (e: any) {
|
||||
toast.error(e.message);
|
||||
} finally {
|
||||
@@ -61,7 +70,7 @@ export default function PluginStorePage () {
|
||||
|
||||
useEffect(() => {
|
||||
loadPlugins();
|
||||
}, []);
|
||||
}, [currentStoreSource]);
|
||||
|
||||
// 按标签分类和搜索
|
||||
const categorizedPlugins = useMemo(() => {
|
||||
@@ -90,6 +99,23 @@ export default function PluginStorePage () {
|
||||
return categories;
|
||||
}, [plugins, searchQuery]);
|
||||
|
||||
// 获取插件的安装状态和已安装版本
|
||||
const getPluginInstallInfo = (plugin: PluginStoreItem): { status: InstallStatus; installedVersion?: string; } => {
|
||||
// 通过 id (包名) 或 name 匹配已安装的插件
|
||||
const installed = installedPlugins.find(p => p.id === plugin.id);
|
||||
|
||||
if (!installed) {
|
||||
return { status: 'not-installed' };
|
||||
}
|
||||
|
||||
// 使用不等于判断:版本不同就显示更新
|
||||
if (installed.version !== plugin.version) {
|
||||
return { status: 'update-available', installedVersion: installed.version };
|
||||
}
|
||||
|
||||
return { status: 'installed', installedVersion: installed.version };
|
||||
};
|
||||
|
||||
const tabs = useMemo(() => {
|
||||
return [
|
||||
{ key: 'all', title: '全部', count: categorizedPlugins.all?.length || 0 },
|
||||
@@ -101,60 +127,9 @@ export default function PluginStorePage () {
|
||||
}, [categorizedPlugins]);
|
||||
|
||||
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);
|
||||
}
|
||||
// 弹窗选择下载镜像
|
||||
setPendingInstallPlugin(plugin);
|
||||
setDownloadMirrorModalOpen(true);
|
||||
};
|
||||
|
||||
const installPluginWithSSE = async (pluginId: string, mirror?: string) => {
|
||||
@@ -195,6 +170,35 @@ export default function PluginStorePage () {
|
||||
} else if (data.success) {
|
||||
toast.success('插件安装成功!', { id: loadingToast });
|
||||
eventSource.close();
|
||||
// 刷新插件列表
|
||||
loadPlugins();
|
||||
// 安装成功后检查插件管理器状态
|
||||
if (pluginManagerNotFound) {
|
||||
dialog.confirm({
|
||||
title: '插件管理器未加载',
|
||||
content: (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-default-600">
|
||||
插件已安装成功,但插件管理器尚未加载。
|
||||
</p>
|
||||
<p className="text-sm text-default-600">
|
||||
是否立即注册插件管理器?注册后插件才能正常运行。
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
confirmText: '注册插件管理器',
|
||||
cancelText: '稍后再说',
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await PluginManager.registerPluginManager();
|
||||
toast.success('插件管理器注册成功');
|
||||
setPluginManagerNotFound(false);
|
||||
} catch (e: any) {
|
||||
toast.error('注册失败: ' + e.message);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (data.message) {
|
||||
toast.loading(data.message, { id: loadingToast });
|
||||
}
|
||||
@@ -213,23 +217,55 @@ export default function PluginStorePage () {
|
||||
}
|
||||
};
|
||||
|
||||
const getStoreSourceDisplayName = () => {
|
||||
if (!currentStoreSource) return '默认源';
|
||||
try {
|
||||
return new URL(currentStoreSource).hostname;
|
||||
} catch {
|
||||
return currentStoreSource;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<title>插件商店 - NapCat WebUI</title>
|
||||
<div className="p-2 md:p-4 relative">
|
||||
<PageLoading loading={loading} />
|
||||
|
||||
{/* 头部 */}
|
||||
<div className="flex mb-6 items-center gap-4">
|
||||
<h1 className="text-2xl font-bold">插件商店</h1>
|
||||
<Button
|
||||
isIconOnly
|
||||
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
|
||||
radius="full"
|
||||
onPress={loadPlugins}
|
||||
>
|
||||
<IoMdRefresh size={24} />
|
||||
</Button>
|
||||
<div className="flex mb-6 items-center justify-between flex-wrap gap-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<h1 className="text-2xl font-bold">插件商店</h1>
|
||||
<Button
|
||||
isIconOnly
|
||||
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
|
||||
radius="full"
|
||||
onPress={loadPlugins}
|
||||
isLoading={loading}
|
||||
>
|
||||
<IoMdRefresh size={24} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 商店列表源卡片 */}
|
||||
<Card className="bg-default-100/50 backdrop-blur-md shadow-sm">
|
||||
<CardBody className="py-2 px-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-default-500">列表源:</span>
|
||||
<span className="text-sm font-medium">{getStoreSourceDisplayName()}</span>
|
||||
</div>
|
||||
<Tooltip content="切换列表源">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => setStoreSourceModalOpen(true)}
|
||||
>
|
||||
<IoMdSettings size={16} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 搜索框 */}
|
||||
@@ -244,35 +280,80 @@ export default function PluginStorePage () {
|
||||
</div>
|
||||
|
||||
{/* 标签页 */}
|
||||
<Tabs
|
||||
aria-label="Plugin Store Categories"
|
||||
className="max-w-full"
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(String(key))}
|
||||
classNames={{
|
||||
tabList: 'bg-white/40 dark:bg-black/20 backdrop-blur-md',
|
||||
cursor: 'bg-white/80 dark:bg-white/10 backdrop-blur-md shadow-sm',
|
||||
}}
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<Tab
|
||||
key={tab.key}
|
||||
title={`${tab.title} (${tab.count})`}
|
||||
>
|
||||
<EmptySection isEmpty={!categorizedPlugins[tab.key]?.length} />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 justify-start items-stretch gap-x-2 gap-y-4">
|
||||
{categorizedPlugins[tab.key]?.map((plugin) => (
|
||||
<PluginStoreCard
|
||||
key={plugin.id}
|
||||
data={plugin}
|
||||
onInstall={() => handleInstall(plugin)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</Tab>
|
||||
))}
|
||||
</Tabs>
|
||||
<div className="relative">
|
||||
{/* 加载遮罩 - 只遮住插件列表区域 */}
|
||||
{loading && (
|
||||
<div className="absolute inset-0 bg-zinc-500/10 z-30 flex justify-center items-center backdrop-blur-sm rounded-lg">
|
||||
<Spinner size='lg' />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Tabs
|
||||
aria-label="Plugin Store Categories"
|
||||
className="max-w-full"
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(String(key))}
|
||||
classNames={{
|
||||
tabList: 'bg-white/40 dark:bg-black/20 backdrop-blur-md',
|
||||
cursor: 'bg-white/80 dark:bg-white/10 backdrop-blur-md shadow-sm',
|
||||
}}
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<Tab
|
||||
key={tab.key}
|
||||
title={`${tab.title} (${tab.count})`}
|
||||
>
|
||||
<EmptySection isEmpty={!categorizedPlugins[tab.key]?.length} />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 justify-start items-stretch gap-x-2 gap-y-4">
|
||||
{categorizedPlugins[tab.key]?.map((plugin) => {
|
||||
const installInfo = getPluginInstallInfo(plugin);
|
||||
return (
|
||||
<PluginStoreCard
|
||||
key={plugin.id}
|
||||
data={plugin}
|
||||
installStatus={installInfo.status}
|
||||
installedVersion={installInfo.installedVersion}
|
||||
onInstall={() => handleInstall(plugin)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Tab>
|
||||
))}
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 商店列表源选择弹窗 */}
|
||||
<MirrorSelectorModal
|
||||
isOpen={storeSourceModalOpen}
|
||||
onClose={() => setStoreSourceModalOpen(false)}
|
||||
onSelect={(mirror) => {
|
||||
setCurrentStoreSource(mirror);
|
||||
}}
|
||||
currentMirror={currentStoreSource}
|
||||
type="raw"
|
||||
/>
|
||||
|
||||
{/* 下载镜像选择弹窗 */}
|
||||
<MirrorSelectorModal
|
||||
isOpen={downloadMirrorModalOpen}
|
||||
onClose={() => {
|
||||
setDownloadMirrorModalOpen(false);
|
||||
setPendingInstallPlugin(null);
|
||||
}}
|
||||
onSelect={(mirror) => {
|
||||
setSelectedDownloadMirror(mirror);
|
||||
// 选择后立即开始安装
|
||||
if (pendingInstallPlugin) {
|
||||
setDownloadMirrorModalOpen(false);
|
||||
installPluginWithSSE(pendingInstallPlugin.id, mirror);
|
||||
setPendingInstallPlugin(null);
|
||||
}
|
||||
}}
|
||||
currentMirror={selectedDownloadMirror}
|
||||
type="file"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Generated
-21
@@ -308,30 +308,9 @@ importers:
|
||||
'@sinclair/typebox':
|
||||
specifier: ^0.34.38
|
||||
version: 0.34.41
|
||||
'@types/cors':
|
||||
specifier: ^2.8.17
|
||||
version: 2.8.19
|
||||
'@types/express':
|
||||
specifier: ^4.17.21
|
||||
version: 4.17.25
|
||||
'@types/ip':
|
||||
specifier: ^1.1.3
|
||||
version: 1.1.3
|
||||
'@types/multer':
|
||||
specifier: ^1.4.12
|
||||
version: 1.4.13
|
||||
'@types/node':
|
||||
specifier: ^22.10.7
|
||||
version: 22.19.1
|
||||
'@types/winston':
|
||||
specifier: ^2.4.4
|
||||
version: 2.4.4
|
||||
'@types/ws':
|
||||
specifier: ^8.5.12
|
||||
version: 8.18.1
|
||||
'@types/yaml':
|
||||
specifier: ^1.9.7
|
||||
version: 1.9.7
|
||||
devDependencies:
|
||||
napcat-core:
|
||||
specifier: workspace:*
|
||||
|
||||
Reference in new issue
Block a user