Compare commits

..
19 Commits
Author SHA1 Message Date
手瓜一十雪 2f8569f30c Add Registry20 GUID management and DPAPI support
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduce tools and UI to read, write, backup and restore QQ Registry20 GUIDs using Windows DPAPI. Adds a Python CLI (guid_tool.py) for local Registry20 operations and a new TypeScript package napcat-dpapi with native bindings for DPAPI. Implements Registry20Utils in the webui-backend to protect/unprotect Registry20, plus backup/restore/delete helpers. Exposes new backend API handlers and routes (get/set GUID, backups, restore, reset, restart) and integrates frontend GUIDManager component and qq_manager controller methods. Propagates QQ data path via WebUiDataRuntime (setter/getter) and wires it up in framework/shell; updates Vite alias and package.json to include the new dpapi workspace. Includes native addon binaries for win32 x64/arm64 and basic tsconfig/readme/license for the new package.
2026-02-12 17:08:24 +08:00
林小槐 82d0c51716 feat(webui): 插件商店增加插件详情弹窗并支持通过 url 传递 id 直接打开 (#1615)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
* feat(webui): 插件商店增加插件详情弹窗并支持通过 url 传递 id 直接打开

* fix(webui):type check
2026-02-11 12:12:06 +08:00
手瓜一十雪 37fb2d68d7 Prefer QQAppId/ marker when parsing AppID
Add parseAppidFromMajorV2 to napcat-common to scan a Major file for the "QQAppId/" marker and extract a null-terminated numeric AppID. Update qq-basic-info to import and prefer this new parser (falling back to the existing parseAppidFromMajor). Also correct the getMajorPath argument order when obtaining the major file path. This enables detection of AppID from a newer Major format while preserving legacy fallback behavior.
2026-02-08 09:55:31 +08:00
手瓜一十雪 a240f93784 Add appid entry for 9.9.27-45758
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add a new mapping to packages/napcat-core/external/appid.json for version 9.9.27-45758 (Windows). The entry sets appid to 537340213 and qua to "V1_WIN_NQ_9.9.27_45758_GW_B".
2026-02-08 09:41:14 +08:00
时瑾 172a75b514 fix(webui-backend): sanitize plugin ID to prevent path injection (CodeQL js/path-injection)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-02-07 13:52:15 +08:00
时瑾 beef1233fa fix(ci): 修复 Update apifox 步骤中因 OpenAPI 文件过大导致的参数列表过长错误
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-02-07 13:44:25 +08:00
时瑾 8f69e2424a fix(backend): 修复插件列表接口新增字段导致的类型错误
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-02-07 13:38:53 +08:00
时瑾 f3156b1843 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-02-07 13:32:58 +08:00
时瑾 61a16b44a4 style(webui): 优化插件商店与插件管理界面 UI/UX
- 重构插件卡片样式,采用毛玻璃效果与主题色交互
- 优化插件商店搜索栏布局,增加对顶部搜索及 Ctrl+F 快捷键的支持
- 实现智能头像提取逻辑,支持从 GitHub、自定义域名(Favicon)及 Vercel 自动生成
- 增加插件描述溢出预览(悬停提示及点击展开功能)
- 修复标签溢出处理,支持 Tooltip 完整显示
- 增强后端插件列表 API,支持返回主页及仓库信息
- 修复部分类型错误与代码规范问题
2026-02-07 13:30:50 +08:00
Nepenthe 7b17ef44dd Merge pull request #1598 from faithleysath/feat/schema-enhancement-refactor
refactor(schema): 重构 schema 组件引用与 OpenAPI 生成流程,并补齐消息 union 类型
2026-02-07 13:27:58 +08:00
吴天一 2c166299a3 fix(schema): 添加 data 字段描述到 BaseResponseSchema 2026-02-07 13:21:06 +08:00
吴天一 75d2611eda fix(schema): 将响应 data 字段标记为必填 2026-02-07 09:27:47 +08:00
吴天一 e2d2e65620 fix(schema): 修复 properties 容器误判导致错误注入 type 2026-02-06 21:37:50 +08:00
吴天一 f479fccf3e refactor(schema): 提取并复用 OpenAPI 响应示例,减少重复定义
在 napcat-schema 中引入 ActionExamples,统一复用公共错误示例定义。

新增默认成功示例 Success_Default,并注册到 components.examples。

将公共错误示例(1400/1401/1404)集中注册到 components.examples,统一响应示例来源。

优化 buildResponseExamples:当 returnExample 为 null、空对象或空数组时,自动引用默认成功示例;当错误示例命中公共定义时,优先使用  引用组件示例,未命中时保持内联示例。

未提供 errorExamples 时,默认引用 #/components/examples/Error_1400,减少重复定义并提升文档一致性。

本次变更不改变接口响应结构,主要改进 OpenAPI 示例复用策略与文档可维护性。
2026-02-06 17:07:24 +08:00
吴天一 45652612b4 refactor(schema): 重构消息 schema 与 OpenAPI 生成流程
- 为 OneBot action 相关对象补充稳定 $id,提升 schema 复用与组件引用能力
- 补齐消息联合类型,纳入 location/xml/miniapp 等消息段定义
- 重构 napcat-schema 中 OpenAPI 生成逻辑,优化组件注册与缺失项报告
- openapi schema 文件行数从 36433 缩减到 23137(减少 13296 行,约 36.5%)
- 统一 schema 结构与描述,降低后续扩展与文档生成维护成本
2026-02-06 16:12:34 +08:00
pohgxz 54266f97f8 fix: 尝试修复 Update apifox 错误 2026-02-05 22:47:02 +08:00
手瓜一十雪 687a5f5708 Update ffmpeg native addon binaries
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
feat: ogg opus格式支持 fix #1593
2026-02-05 22:00:12 +08:00
手瓜一十雪 3dab2b4361 Update appid for 3.2.25-45758
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Correct the appid entry in packages/napcat-core/external/appid.json for version 3.2.25-45758, changing it from 537314197 to 537340249 to ensure the build is identified correctly. (File now lacks a trailing newline.)
2026-02-05 20:28:11 +08:00
006lp 74be268dbe Update appid and qua for version 3.2.25-45758 (#1596)
Signed-off-by: 006lp <144674902+006lp@users.noreply.github.com>
2026-02-05 20:27:53 +08:00
43 changed files with 2817 additions and 464 deletions

No files matched your search

+9 -10
View File
@@ -458,24 +458,23 @@ jobs:
pnpm i
pnpm run build:openapi
# 读取并压缩 openapi.json 内容
OPENAPI_CONTENT=$(cat packages/napcat-schema/openapi.json | tr -d '\n\r\t' | sed 's/ */ /g' | sed 's/"/\\"/g')
# 构建 JSON 数据
JSON_DATA=$(printf '{
"input": "%s",
"options": {
# 使用 jq 安全地构建大型 JSON 数据并保存到文件
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
'{
input: $input,
options: {
"endpointOverwriteBehavior": "OVERWRITE_EXISTING",
"schemaOverwriteBehavior": "OVERWRITE_EXISTING",
"updateFolderOfChangedEndpoint": true,
"moduleId": 1140714,
"deleteUnmatchedResources": true
}
}' "$OPENAPI_CONTENT")
}' > apifox_payload.json
# 通过文件形式发送数据,避免命令行长度限制
curl --location -g --request POST 'https://api.apifox.com/v1/projects/5348325/import-openapi?locale=zh-CN' \
--header 'X-Apifox-Api-Version: 2024-03-28' \
--header 'Authorization: Bearer $APIFOX_TOKEN' \
--header "Authorization: Bearer $APIFOX_TOKEN" \
--header 'Content-Type: application/json' \
--data-raw "$JSON_DATA"
--data-binary @apifox_payload.json
+3
View File
@@ -10,6 +10,9 @@ devconfig/*
!.vscode/extensions.json
.idea/*
# macOS
.DS_Store
# Build
*.db
checkVersion.sh
+29
View File
@@ -184,6 +184,35 @@ export function stringifyWithBigInt (obj: any) {
);
}
export function parseAppidFromMajorV2 (nodeMajor: string): string | undefined {
const marker = Buffer.from('QQAppId/', 'utf-8');
const filePath = path.resolve(nodeMajor);
const fileContent = fs.readFileSync(filePath);
let searchPosition = 0;
while (true) {
const index = fileContent.indexOf(marker, searchPosition);
if (index === -1) {
break;
}
const start = index + marker.length;
const end = fileContent.indexOf(0x00, start);
if (end === -1) {
break;
}
const content = fileContent.subarray(start, end);
const str = content.toString('utf-8');
if (/^\d+$/.test(str)) {
return str;
}
searchPosition = end + 1;
}
return undefined;
}
export function parseAppidFromMajor (nodeMajor: string): string | undefined {
const hexSequence = 'A4 09 00 00 00 35';
const sequenceBytes = Buffer.from(hexSequence.replace(/ /g, ''), 'hex');
+5 -1
View File
@@ -529,6 +529,10 @@
},
"3.2.25-45758": {
"appid": 537340249,
"qua": "V1_LNX_NQ_3.2.25_45627_GW_B"
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"9.9.27-45758": {
"appid": 537340213,
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
}
}
+8 -2
View File
@@ -1,6 +1,6 @@
import fs from 'node:fs';
import { systemPlatform } from 'napcat-common/src/system';
import { getDefaultQQVersionConfigInfo, getQQPackageInfoPath, getQQVersionConfigPath, parseAppidFromMajor } from 'napcat-common/src/helper';
import { getDefaultQQVersionConfigInfo, getQQPackageInfoPath, getQQVersionConfigPath, parseAppidFromMajor, parseAppidFromMajorV2 } from 'napcat-common/src/helper';
import AppidTable from '@/napcat-core/external/appid.json';
import { LogWrapper } from './log';
import { getMajorPath } from '@/napcat-core/index';
@@ -107,7 +107,13 @@ export class QQBasicInfoWrapper {
if (!this.QQMainPath) {
throw new Error('QQMainPath未定义 无法通过Major获取Appid');
}
const majorPath = getMajorPath(QQVersion, this.QQMainPath);
const majorPath = getMajorPath(this.QQMainPath, QQVersion);
// 优先通过 QQAppId/ 标记搜索
const appidV2 = parseAppidFromMajorV2(majorPath);
if (appidV2) {
return appidV2;
}
// 回落到旧方式
const appid = parseAppidFromMajor(majorPath);
return appid;
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Xavier Monin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+4
View File
@@ -0,0 +1,4 @@
# @primno/dpapi
## 协议与说明
全部遵守原仓库要求
+65
View File
@@ -0,0 +1,65 @@
/**
* napcat-dpapi - Windows DPAPI wrapper
*
* Loads the native @primno+dpapi.node addon from the runtime
* native/dpapi/ directory using process.dlopen, consistent
* with how other native modules (ffmpeg, packet, pty) are loaded.
*/
import { fileURLToPath } from 'node:url';
import path, { dirname } from 'node:path';
export type DataProtectionScope = 'CurrentUser' | 'LocalMachine';
export interface DpapiBindings {
protectData (dataToEncrypt: Uint8Array, optionalEntropy: Uint8Array | null, scope: DataProtectionScope): Uint8Array;
unprotectData (encryptData: Uint8Array, optionalEntropy: Uint8Array | null, scope: DataProtectionScope): Uint8Array;
}
let dpapiBindings: DpapiBindings | null = null;
let loadError: Error | null = null;
function getAddonPath (): string {
// At runtime, import.meta.url resolves to dist/ directory.
// Native files are at dist/native/dpapi/{platform}-{arch}/@primno+dpapi.node
const importDir = dirname(fileURLToPath(import.meta.url));
const platform = process.platform; // 'win32'
const arch = process.arch; // 'x64' or 'arm64'
return path.join(importDir, 'native', 'dpapi', `${platform}-${arch}`, '@primno+dpapi.node');
}
function loadDpapi (): DpapiBindings {
if (dpapiBindings) {
return dpapiBindings;
}
if (loadError) {
throw loadError;
}
try {
const addonPath = getAddonPath();
const nativeModule: { exports: DpapiBindings } = { exports: {} as DpapiBindings };
process.dlopen(nativeModule, addonPath);
dpapiBindings = nativeModule.exports;
return dpapiBindings;
} catch (e) {
loadError = e as Error;
throw new Error(`Failed to load DPAPI native addon: ${(e as Error).message}`);
}
}
export const isPlatformSupported = process.platform === 'win32';
export function protectData (data: Uint8Array, optionalEntropy: Uint8Array | null, scope: DataProtectionScope): Uint8Array {
return loadDpapi().protectData(data, optionalEntropy, scope);
}
export function unprotectData (data: Uint8Array, optionalEntropy: Uint8Array | null, scope: DataProtectionScope): Uint8Array {
return loadDpapi().unprotectData(data, optionalEntropy, scope);
}
export const Dpapi = {
protectData,
unprotectData,
};
export default Dpapi;
+18
View File
@@ -0,0 +1,18 @@
{
"name": "napcat-dpapi",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "index.ts",
"exports": {
".": {
"import": "./index.ts"
}
},
"devDependencies": {
"@types/node": "^22.0.1"
},
"engines": {
"node": ">=18.0.0"
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "."
},
"include": [
"./**/*.ts"
]
}
+1
View File
@@ -78,6 +78,7 @@ export async function NCoreInitFramework (
// 启动WebUi
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
WebUiDataRuntime.setQQDataPath(loaderObject.core.dataPath);
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
// 使用 NapCatAdapterManager 统一管理协议适配器
const adapterManager = new NapCatAdapterManager(loaderObject.core, loaderObject.context, pathWrapper);
+6 -6
View File
@@ -17,7 +17,7 @@ export const OB11UserSchema = Type.Object({
login_days: Type.Optional(Type.Number({ description: '登录天数' })),
categoryName: Type.Optional(Type.String({ description: '分组名称' })),
categoryId: Type.Optional(Type.Number({ description: '分组ID' })),
}, { description: 'OneBot 11 用户信息' });
}, { $id: 'OB11User', description: 'OneBot 11 用户信息' });
export const OB11GroupSchema = Type.Object({
group_all_shut: Type.Number({ description: '是否全员禁言' }),
@@ -26,7 +26,7 @@ export const OB11GroupSchema = Type.Object({
group_name: Type.String({ description: '群名称' }),
member_count: Type.Optional(Type.Number({ description: '成员人数' })),
max_member_count: Type.Optional(Type.Number({ description: '最大成员人数' })),
}, { description: 'OneBot 11 群信息' });
}, { $id: 'OB11Group', description: 'OneBot 11 群信息' });
export const OB11GroupMemberSchema = Type.Object({
group_id: Type.Number({ description: '群号' }),
@@ -48,7 +48,7 @@ export const OB11GroupMemberSchema = Type.Object({
shut_up_timestamp: Type.Optional(Type.Number({ description: '禁言截止时间戳' })),
is_robot: Type.Optional(Type.Boolean({ description: '是否为机器人' })),
qage: Type.Optional(Type.Number({ description: 'Q龄' })),
}, { description: 'OneBot 11 群成员信息' });
}, { $id: 'OB11GroupMember', description: 'OneBot 11 群成员信息' });
export const OB11NotifySchema = Type.Object({
request_id: Type.Number({ description: '请求ID' }),
@@ -60,7 +60,7 @@ export const OB11NotifySchema = Type.Object({
checked: Type.Boolean({ description: '是否已处理' }),
actor: Type.Number({ description: '操作者QQ' }),
requester_nick: Type.String({ description: '申请者昵称' }),
}, { description: 'OneBot 11 通知信息' });
}, { $id: 'OB11Notify', description: 'OneBot 11 通知信息' });
export const lastestMessageSchema = Type.Object({
self_id: Type.Number({ description: '发送者QQ号' }),
@@ -82,7 +82,7 @@ export const lastestMessageSchema = Type.Object({
post_type: Type.String({ description: '发布类型' }),
group_id: Type.Number({ description: '群号' }),
group_name: Type.String({ description: '群名称' }),
}, { description: '最后一条消息' });
}, { $id: 'OB11LatestMessage', description: '最后一条消息' });
export const OB11MessageSchema = Type.Intersect([
lastestMessageSchema,
@@ -95,4 +95,4 @@ export const OB11MessageSchema = Type.Intersect([
likes_cnt: Type.String({ description: '点赞数' }),
})),
}, { description: 'OneBot 11 消息信息' })
]);
], { $id: 'OB11ActionMessage', description: 'OneBot 11 消息信息' });
@@ -13,6 +13,8 @@ export interface PluginPackageJson {
main?: string;
description?: string;
author?: string;
homepage?: string;
repository?: string | { type: string; url: string; };
}
// ==================== 插件配置 Schema ====================
+3
View File
@@ -325,8 +325,11 @@ export const OB11MessageDataSchema = Type.Union([
OB11MessageDiceSchema,
OB11MessageRPSSchema,
OB11MessageContactSchema,
OB11MessageLocationSchema,
OB11MessageJsonSchema,
OB11MessageXmlSchema,
OB11MessageMarkdownSchema,
OB11MessageMiniAppSchema,
OB11MessageNodeSchema,
OB11MessageForwardSchema,
OB11MessageOnlineFileSchema,
+614 -90
View File
@@ -2,13 +2,16 @@ import { getAllHandlers } from '@/napcat-onebot/action/index';
import { AutoRegisterRouter } from '@/napcat-onebot/action/auto-register';
import { writeFileSync, existsSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { TSchema } from '@sinclair/typebox';
import { fileURLToPath } from 'node:url';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { TSchema } from '@sinclair/typebox';
import { OneBotAction, ActionExamples } from '@/napcat-onebot/action/OneBotAction';
import { napCatVersion } from 'napcat-common/src/version';
import * as MessageSchemas from '@/napcat-onebot/types/message';
import * as ActionSchemas from '@/napcat-onebot/action/schemas';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
/* -------------------------------------------------------------------------- */
/* 基础类型 */
/* -------------------------------------------------------------------------- */
interface ActionSchemaInfo {
payload?: TSchema;
@@ -21,52 +24,524 @@ interface ActionSchemaInfo {
errorExamples?: Array<{ code: number, description: string; }>;
}
type JsonObject = { [key: string]: unknown; };
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const OPENAPI_OUTPUT_PATH = resolve(__dirname, 'openapi.json');
const MISSING_REPORT_PATH = resolve(__dirname, 'missing_props.log');
export const actionSchemas: Record<string, ActionSchemaInfo> = {};
/* -------------------------------------------------------------------------- */
/* 日志工具 */
/* -------------------------------------------------------------------------- */
/**
* 统一日志前缀,方便在构建日志中快速检索。
*/
const LOG_SCOPE = '[napcat-schema]';
function logSection (title: string) {
console.log(`\n${LOG_SCOPE} ── ${title}`);
}
function logInfo (message: string) {
console.log(`${LOG_SCOPE} ℹ ${message}`);
}
function logWarn (message: string) {
console.warn(`${LOG_SCOPE} ⚠ ${message}`);
}
function logSuccess (message: string) {
console.log(`${LOG_SCOPE} ✅ ${message}`);
}
/* -------------------------------------------------------------------------- */
/* OpenAPI 基础组件(固定部分) */
/* -------------------------------------------------------------------------- */
const BaseResponseSchema: JsonObject = {
type: 'object',
'x-schema-id': 'BaseResponse',
properties: {
status: { type: 'string', description: '状态 (ok/failed)' },
retcode: { type: 'number', description: '返回码' },
data: { description: '业务数据(具体结构由各接口定义)' },
message: { type: 'string', description: '消息' },
wording: { type: 'string', description: '提示' },
stream: {
type: 'string',
description: '流式响应',
enum: ['stream-action', 'normal-action']
}
},
required: ['status', 'retcode']
};
const EmptyDataSchema: JsonObject = {
description: '无数据',
type: 'null'
};
const DEFAULT_SUCCESS_EXAMPLE_VALUE = {
status: 'ok',
retcode: 0,
data: {},
message: '',
wording: '',
stream: 'normal-action'
} as const;
const DEFAULT_ERROR_EXAMPLE_DEFINITIONS = ActionExamples.Common.errors;
const SUCCESS_DEFAULT_EXAMPLE_KEY = 'Success_Default';
function isObjectRecord (value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
function isEmptyObject (value: unknown): value is Record<string, never> {
return isObjectRecord(value) && Object.keys(value).length === 0;
}
function isEmptyArray (value: unknown): value is [] {
return Array.isArray(value) && value.length === 0;
}
function isMeaninglessSuccessExampleData (value: unknown): boolean {
return value === null || isEmptyObject(value) || isEmptyArray(value);
}
function resolveCommonErrorExampleKey (error: { code: number, description: string; }): string | null {
const matched = DEFAULT_ERROR_EXAMPLE_DEFINITIONS.find(
item => item.code === error.code && item.description === error.description
);
return matched ? `Error_${matched.code}` : null;
}
/* -------------------------------------------------------------------------- */
/* 通用工具函数 */
/* -------------------------------------------------------------------------- */
/**
* 深拷贝 schema,优先使用 structuredClone,失败时回落到 JSON 序列化。
*/
function cloneSchema<T> (schema: T): T {
if (typeof globalThis.structuredClone === 'function') {
try {
return globalThis.structuredClone(schema);
} catch {
// fallback
}
}
return JSON.parse(JSON.stringify(schema)) as T;
}
/**
* 在 anyOf/oneOf 中,将“多个单值 enum 分支 + 可选 nullable 分支”压缩为单个 enum。
*
* 例:
* - anyOf: [{ type:'string', enum:['a'] }, { type:'string', enum:['b'] }]
* -> { type:'string', enum:['a','b'] }
*/
function collapseSingleValueEnumCombinator (items: unknown[]): Record<string, unknown> | null {
const enumValues: unknown[] = [];
let type: string | undefined;
let nullable = false;
for (const item of items) {
if (!item || typeof item !== 'object') {
return null;
}
const branch = item as Record<string, unknown>;
// 兼容仅有 nullable 的分支
if (branch['nullable'] === true && Object.keys(branch).length === 1) {
nullable = true;
continue;
}
const branchEnum = branch['enum'];
if (!Array.isArray(branchEnum) || branchEnum.length !== 1) {
return null;
}
enumValues.push(branchEnum[0]);
if (typeof branch['type'] === 'string') {
if (!type) {
type = branch['type'];
} else if (type !== branch['type']) {
return null;
}
}
}
if (enumValues.length === 0) {
return null;
}
const merged: Record<string, unknown> = { enum: [...new Set(enumValues)] };
if (type) {
merged['type'] = type;
}
if (nullable) {
merged['nullable'] = true;
}
return merged;
}
/**
* 将 TypeBox/JSON-Schema 映射为 OpenAPI 3.1 兼容结构。
*
* 关键规则:
* - $id -> x-schema-id(保留标识用于后续 $ref 替换)
* - const -> enum:[const]
* - type:'void' / type:'undefined' -> type:'null'
* - nullable:true -> type 包含 'null'
* - anyOf/oneOf 的简单 enum 分支做压缩
*/
function sanitizeSchemaForOpenAPI<T> (schema: T): T {
const walk = (value: unknown): unknown => {
if (Array.isArray(value)) {
return value.map(walk);
}
if (value && typeof value === 'object') {
const obj = value as Record<string, unknown>;
const next: Record<string, unknown> = {};
for (const [key, child] of Object.entries(obj)) {
// 特殊处理 properties 容器:只遍历每个属性的 schema,避免将容器对象误判为 schema 元对象
if (key === 'properties' && child && typeof child === 'object' && !Array.isArray(child)) {
const cleanProps: Record<string, unknown> = {};
for (const [propName, propSchema] of Object.entries(child as Record<string, unknown>)) {
cleanProps[propName] = walk(propSchema);
}
next[key] = cleanProps;
continue;
}
if (key === '$id') {
if (typeof child === 'string' && child.length > 0) {
next['x-schema-id'] = child;
}
continue;
}
if (key === 'const') {
next['enum'] = [child];
continue;
}
if (key === 'type' && typeof child === 'string') {
if (child === 'void' || child === 'undefined') {
next['type'] = 'null';
} else {
next['type'] = child;
}
continue;
}
if (key === 'type' && Array.isArray(child)) {
const types = child
.filter((t): t is string => typeof t === 'string')
.map(t => (t === 'void' || t === 'undefined') ? 'null' : t);
const normalizedTypes = [...new Set(types)];
if (normalizedTypes.length === 0) {
next['type'] = 'null';
} else if (normalizedTypes.length === 1) {
next['type'] = normalizedTypes[0];
} else {
next['type'] = normalizedTypes;
}
continue;
}
if ((key === 'anyOf' || key === 'oneOf') && Array.isArray(child)) {
const normalized = child.map(walk);
const mergedEnum = collapseSingleValueEnumCombinator(normalized);
if (mergedEnum) {
Object.assign(next, mergedEnum);
} else {
next[key] = normalized;
}
continue;
}
next[key] = walk(child);
}
// OpenAPI 3.1:将 nullable 归一到 type 包含 null
if (next['nullable'] === true) {
const currentType = next['type'];
if (typeof currentType === 'string') {
next['type'] = currentType === 'null' ? 'null' : [currentType, 'null'];
} else if (Array.isArray(currentType)) {
const normalizedTypes = [
...new Set(currentType
.filter((t): t is string => typeof t === 'string')
.map(t => (t === 'void' || t === 'undefined') ? 'null' : t)
.concat('null'))
];
next['type'] = normalizedTypes.length === 1 ? normalizedTypes[0] : normalizedTypes;
} else if (!('anyOf' in next) && !('oneOf' in next) && !('allOf' in next) && !('$ref' in next)) {
next['type'] = 'null';
}
delete next['nullable'];
}
// 兜底:仅有描述/元信息但缺少 type 时,补 object,避免严格校验失败
if (
!('type' in next)
&& !('$ref' in next)
&& !('anyOf' in next)
&& !('oneOf' in next)
&& !('allOf' in next)
&& !('enum' in next)
&& !('properties' in next)
&& !('items' in next)
) {
const schemaMetaKeys = [
'description', 'title', 'default', 'examples', 'example',
'deprecated', 'readOnly', 'writeOnly', 'x-schema-id'
];
if (schemaMetaKeys.some(key => key in next)) {
next['type'] = 'object';
}
}
return next;
}
return value;
};
return walk(schema) as T;
}
/* -------------------------------------------------------------------------- */
/* Schema 注册 & 引用替换逻辑 */
/* -------------------------------------------------------------------------- */
/**
* 将模块中所有“含 $id 的导出 schema”注册到 components.schemas。
*/
function registerSchemasFromModule (
openapi: JsonObject,
source: Record<string, unknown>,
sourceName: string
) {
const components = ((openapi['components'] as JsonObject)['schemas'] as JsonObject);
let registeredCount = 0;
let duplicatedCount = 0;
for (const exportedValue of Object.values(source)) {
if (!exportedValue || typeof exportedValue !== 'object') {
continue;
}
const schema = cloneSchema(exportedValue) as JsonObject;
const schemaId = typeof schema['$id'] === 'string' && (schema['$id'] as string).length > 0
? schema['$id'] as string
: '';
if (!schemaId) {
continue;
}
if (components[schemaId]) {
duplicatedCount += 1;
logWarn(`发现重复 schema id(${sourceName}):${schemaId},将覆盖旧定义`);
}
components[schemaId] = sanitizeSchemaForOpenAPI(schema);
registeredCount += 1;
}
logInfo(`${sourceName} 注册完成:${registeredCount} 个 schema,重复 ${duplicatedCount} 个`);
}
/**
* 对 components.schemas 做去内联:
* - 若子节点含 x-schema-id 且在 components.schemas 可命中
* - 则替换为 $ref
*
* 注意:组件根节点不会替换为自身,避免根级自引用。
*/
function replaceComponentInlineSchemasWithRefs (openapi: JsonObject) {
const components = openapi['components'] as JsonObject | undefined;
const schemas = components?.['schemas'] as JsonObject | undefined;
if (!schemas || typeof schemas !== 'object') {
return;
}
const availableSchemaIds = new Set(Object.keys(schemas));
let replacedCount = 0;
const walk = (value: unknown, ownerSchemaId: string): unknown => {
if (Array.isArray(value)) {
return value.map(item => walk(item, ownerSchemaId));
}
if (value && typeof value === 'object') {
const obj = value as JsonObject;
const schemaId = obj['x-schema-id'];
if (
typeof schemaId === 'string'
&& schemaId !== ownerSchemaId
&& availableSchemaIds.has(schemaId)
) {
replacedCount += 1;
return { $ref: `#/components/schemas/${schemaId}` };
}
const next: JsonObject = {};
for (const [key, child] of Object.entries(obj)) {
next[key] = walk(child, ownerSchemaId);
}
return next;
}
return value;
};
for (const [schemaId, schema] of Object.entries(schemas)) {
schemas[schemaId] = walk(schema, schemaId);
}
logInfo(`components 内联替换完成:${replacedCount} 处`);
}
/**
* 对 paths 做去内联:
* - 若节点含 x-schema-id 且在 components.schemas 可命中
* - 则替换为 $ref
*/
function replacePathInlineSchemasWithRefs (openapi: JsonObject) {
const paths = openapi['paths'];
const components = openapi['components'] as JsonObject | undefined;
const schemas = components?.['schemas'] as JsonObject | undefined;
if (!paths || typeof paths !== 'object' || !schemas || typeof schemas !== 'object') {
return;
}
const availableSchemaIds = new Set(Object.keys(schemas));
let replacedCount = 0;
const walk = (value: unknown): unknown => {
if (Array.isArray(value)) {
return value.map(walk);
}
if (value && typeof value === 'object') {
const obj = value as JsonObject;
const schemaId = obj['x-schema-id'];
if (typeof schemaId === 'string' && availableSchemaIds.has(schemaId)) {
replacedCount += 1;
return { $ref: `#/components/schemas/${schemaId}` };
}
const next: JsonObject = {};
for (const [key, child] of Object.entries(obj)) {
next[key] = walk(child);
}
return next;
}
return value;
};
openapi['paths'] = walk(paths) as JsonObject;
logInfo(`paths 内联替换完成:${replacedCount} 处`);
}
/* -------------------------------------------------------------------------- */
/* Action 收集逻辑 */
/* -------------------------------------------------------------------------- */
/**
* 收集全部 action schema 信息。
*/
export function initSchemas () {
const handlers = getAllHandlers(null as any, null as any);
handlers.forEach(handler => {
if (handler.actionName && (handler.actionName as string) !== 'unknown') {
const action = handler as OneBotAction<unknown, unknown>;
actionSchemas[handler.actionName] = {
payload: action.payloadSchema,
return: action.returnSchema,
summary: action.actionSummary,
description: action.actionDescription,
tags: action.actionTags,
payloadExample: action.payloadExample,
returnExample: action.returnExample,
errorExamples: action.errorExamples
};
if (!handler.actionName || (handler.actionName as string) === 'unknown') {
return;
}
const action = handler as OneBotAction<unknown, unknown>;
actionSchemas[handler.actionName] = {
payload: action.payloadSchema,
return: action.returnSchema,
summary: action.actionSummary,
description: action.actionDescription,
tags: action.actionTags,
payloadExample: action.payloadExample,
returnExample: action.returnExample,
errorExamples: action.errorExamples
};
});
AutoRegisterRouter.forEach((ActionClass) => {
AutoRegisterRouter.forEach(ActionClass => {
const handler = new ActionClass(null as any, null as any);
if (handler.actionName && (handler.actionName as string) !== 'unknown') {
const action = handler as OneBotAction<unknown, unknown>;
actionSchemas[handler.actionName] = {
payload: action.payloadSchema,
return: action.returnSchema,
summary: action.actionSummary,
description: action.actionDescription,
tags: action.actionTags,
payloadExample: action.payloadExample,
returnExample: action.returnExample,
errorExamples: action.errorExamples
};
if (!handler.actionName || (handler.actionName as string) === 'unknown') {
return;
}
const action = handler as OneBotAction<unknown, unknown>;
actionSchemas[handler.actionName] = {
payload: action.payloadSchema,
return: action.returnSchema,
summary: action.actionSummary,
description: action.actionDescription,
tags: action.actionTags,
payloadExample: action.payloadExample,
returnExample: action.returnExample,
errorExamples: action.errorExamples
};
});
}
export function generateOpenAPI () {
try {
initSchemas();
} catch (e) {
console.warn('Init schemas partial failure, proceeding with collected data...');
}
/* -------------------------------------------------------------------------- */
/* OpenAPI 构建主流程 */
/* -------------------------------------------------------------------------- */
const openapi: Record<string, unknown> = {
openapi: '3.0.1',
function createOpenAPIDocument (): Record<string, unknown> {
const componentExamples: Record<string, unknown> = {
[SUCCESS_DEFAULT_EXAMPLE_KEY]: {
summary: '成功响应',
value: DEFAULT_SUCCESS_EXAMPLE_VALUE
}
};
DEFAULT_ERROR_EXAMPLE_DEFINITIONS.forEach(error => {
componentExamples[`Error_${error.code}`] = {
summary: error.description,
value: {
status: 'failed',
retcode: error.code,
data: null,
message: error.description,
wording: error.description,
stream: 'normal-action'
}
};
});
return {
openapi: '3.1.0',
info: {
title: 'NapCat OneBot 11 HTTP API',
description: 'NapCatOneBot11 HTTP POST 接口文档',
@@ -81,39 +556,43 @@ export function generateOpenAPI () {
],
paths: {} as Record<string, unknown>,
components: {
schemas: {},
schemas: {
BaseResponse: BaseResponseSchema,
EmptyData: EmptyDataSchema
},
examples: componentExamples,
responses: {},
securitySchemes: {}
},
servers: [],
security: []
};
}
for (const [actionName, schemas] of Object.entries(actionSchemas)) {
if (!schemas.payload && !schemas.summary) continue;
const path = '/' + actionName;
const cleanPayload = schemas.payload ? JSON.parse(JSON.stringify(schemas.payload)) : { type: 'object', properties: {} };
const cleanReturn = schemas.return ? JSON.parse(JSON.stringify(schemas.return)) : { type: 'object', properties: {} };
// 构造响应示例
const responseExamples: Record<string, any> = {
'Success': {
function buildResponseExamples (schemas: ActionSchemaInfo): Record<string, unknown> {
const successData = schemas.returnExample ?? {};
const examples: Record<string, any> = {
Success: isMeaninglessSuccessExampleData(successData)
? { $ref: `#/components/examples/${SUCCESS_DEFAULT_EXAMPLE_KEY}` }
: {
summary: '成功响应',
value: {
status: 'ok',
retcode: 0,
data: schemas.returnExample || {},
data: successData,
message: '',
wording: '',
stream: 'normal-action'
}
}
};
};
if (schemas.errorExamples) {
schemas.errorExamples.forEach(error => {
responseExamples['Error_' + error.code] = {
if (schemas.errorExamples) {
schemas.errorExamples.forEach(error => {
const commonErrorKey = resolveCommonErrorExampleKey(error);
examples[`Error_${error.code}`] = commonErrorKey
? { $ref: `#/components/examples/${commonErrorKey}` }
: {
summary: error.description,
value: {
status: 'failed',
@@ -124,23 +603,33 @@ export function generateOpenAPI () {
stream: 'normal-action'
}
};
});
} else {
// 默认提供一个通用错误
responseExamples['Generic_Error'] = {
summary: '通用错误',
value: {
status: 'failed',
retcode: 1400,
data: null,
message: '请求参数错误或业务逻辑执行失败',
wording: '请求参数错误或业务逻辑执行失败',
stream: 'normal-action'
}
};
});
return examples;
}
examples['Generic_Error'] = {
$ref: '#/components/examples/Error_1400'
};
return examples;
}
function appendActionPaths (openapi: Record<string, unknown>) {
const paths = openapi['paths'] as Record<string, any>;
for (const [actionName, schemas] of Object.entries(actionSchemas)) {
if (!schemas.payload && !schemas.summary) {
continue;
}
const paths = openapi['paths'] as Record<string, any>;
const path = `/${actionName}`;
const cleanPayload = schemas.payload
? sanitizeSchemaForOpenAPI(cloneSchema(schemas.payload))
: { type: 'object', properties: {} };
const cleanReturn = schemas.return
? sanitizeSchemaForOpenAPI(cloneSchema(schemas.return))
: { $ref: '#/components/schemas/EmptyData' };
paths[path] = {
post: {
summary: schemas.summary || actionName,
@@ -154,7 +643,7 @@ export function generateOpenAPI () {
'application/json': {
schema: cleanPayload,
examples: {
'Default': {
Default: {
summary: '默认请求示例',
value: schemas.payloadExample || {}
}
@@ -168,18 +657,21 @@ export function generateOpenAPI () {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
status: { type: 'string', description: '状态 (ok/failed)' },
retcode: { type: 'number', description: '返回码' },
data: { ...cleanReturn, description: '数据' },
message: { type: 'string', description: '消息' },
wording: { type: 'string', description: '提示' },
stream: { type: 'string', description: '流式响应', enum: ['stream-action', 'normal-action'] }
},
required: ['status', 'retcode', 'data']
allOf: [
{ $ref: '#/components/schemas/BaseResponse' },
{
type: 'object',
required: ['data'],
properties: {
data: {
...(typeof cleanReturn === 'object' && cleanReturn ? cleanReturn : {}),
description: '业务数据'
}
}
}
]
},
examples: responseExamples
examples: buildResponseExamples(schemas)
}
}
}
@@ -188,16 +680,46 @@ export function generateOpenAPI () {
}
};
}
}
const outputPath = resolve(__dirname, 'openapi.json');
writeFileSync(outputPath, JSON.stringify(openapi, null, 2));
console.log('OpenAPI schema (3.0.1 Format) generated at: ' + outputPath);
export function generateOpenAPI () {
logSection('开始生成 OpenAPI 文档');
try {
initSchemas();
logInfo(`已收集 action: ${Object.keys(actionSchemas).length} 个`);
} catch {
logWarn('初始化 schema 过程中出现部分失败,将继续使用已收集的数据');
}
const openapi = createOpenAPIDocument();
logSection('注册组件 schema');
registerSchemasFromModule(openapi as JsonObject, MessageSchemas, 'types/message.ts');
registerSchemasFromModule(openapi as JsonObject, ActionSchemas, 'action/schemas.ts');
logSection('处理组件内联引用');
replaceComponentInlineSchemasWithRefs(openapi as JsonObject);
logSection('构建 paths');
appendActionPaths(openapi);
logSection('处理 paths 内联引用');
replacePathInlineSchemasWithRefs(openapi as JsonObject);
writeFileSync(OPENAPI_OUTPUT_PATH, JSON.stringify(openapi, null, 2));
logSuccess(`OpenAPI 生成完成:${OPENAPI_OUTPUT_PATH}`);
generateMissingReport();
}
/* -------------------------------------------------------------------------- */
/* 元数据缺失报告 */
/* -------------------------------------------------------------------------- */
function generateMissingReport () {
const missingReport: string[] = [];
for (const [actionName, schemas] of Object.entries(actionSchemas)) {
const missing: string[] = [];
if (!schemas.summary) missing.push('actionSummary');
@@ -206,18 +728,20 @@ function generateMissingReport () {
if (schemas.returnExample === undefined) missing.push('returnExample');
if (missing.length > 0) {
missingReport.push('[' + actionName + '] 缺失属性: ' + missing.join(', '));
missingReport.push(`[${actionName}] 缺失属性: ${missing.join(', ')}`);
}
}
const reportPath = resolve(__dirname, 'missing_props.log');
if (missingReport.length > 0) {
writeFileSync(reportPath, missingReport.join('\n'));
console.warn('\n检查到 ' + missingReport.length + ' 个接口存在元数据缺失,报告已保存至: ' + reportPath);
} else {
if (existsSync(reportPath)) writeFileSync(reportPath, '');
console.log('\n所有接口元数据已完整!');
writeFileSync(MISSING_REPORT_PATH, missingReport.join('\n'));
logWarn(`检查到 ${missingReport.length} 个接口元数据缺失,报告已写入:${MISSING_REPORT_PATH}`);
return;
}
if (existsSync(MISSING_REPORT_PATH)) {
writeFileSync(MISSING_REPORT_PATH, '');
}
logSuccess('所有接口元数据完整');
}
generateOpenAPI();
+2 -1
View File
@@ -390,7 +390,7 @@ export async function NCoreInitShell () {
// 初始化 FFmpeg 服务
await FFmpegService.init(pathWrapper.binaryPath, logger);
if (!(process.env['NAPCAT_DISABLE_PIPE'] == '1' || process.env['NAPCAT_WORKER_PROCESS'] == '1')) {
if (!(process.env['NAPCAT_DISABLE_PIPE'] === '1' || process.env['NAPCAT_WORKER_PROCESS'] === '1')) {
await connectToNamedPipe(logger).catch(e => logger.logError('命名管道连接失败', e));
}
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
@@ -425,6 +425,7 @@ export async function NCoreInitShell () {
}
}
const [dataPath, dataPathGlobal] = getDataPaths(wrapper);
WebUiDataRuntime.setQQDataPath(dataPath);
const systemPlatform = getPlatformType();
if (!basicInfoWrapper.QQVersionAppid || !basicInfoWrapper.QQVersionQua) throw new Error('QQVersionAppid or QQVersionQua is not defined');
+1
View File
@@ -45,6 +45,7 @@ const ShellBaseConfig = (source_map: boolean = false) =>
'@/napcat-common': resolve(__dirname, '../napcat-common'),
'@/napcat-onebot': resolve(__dirname, '../napcat-onebot'),
'@/napcat-pty': resolve(__dirname, '../napcat-pty'),
'@/napcat-dpapi': resolve(__dirname, '../napcat-dpapi'),
'@/napcat-webui-backend': resolve(__dirname, '../napcat-webui-backend'),
'@/napcat-image-size': resolve(__dirname, '../napcat-image-size'),
'@/napcat-protocol': resolve(__dirname, '../napcat-protocol'),
@@ -26,6 +26,7 @@
"json5": "^2.2.3",
"multer": "^2.0.1",
"napcat-common": "workspace:*",
"napcat-dpapi": "workspace:*",
"napcat-pty": "workspace:*",
"ws": "^8.18.3"
},
@@ -75,6 +75,8 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
status: string;
hasConfig: boolean;
hasPages: boolean;
homepage?: string;
repository?: string;
}> = new Array();
// 收集所有插件的扩展页面
@@ -111,7 +113,11 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
author: p.packageJson?.author || '',
status,
hasConfig: !!(p.runtime.module?.plugin_config_schema || p.runtime.module?.plugin_config_ui),
hasPages
hasPages,
homepage: p.packageJson?.homepage,
repository: typeof p.packageJson?.repository === 'string'
? p.packageJson.repository
: p.packageJson?.repository?.url
});
// 收集插件的扩展页面
@@ -27,6 +27,22 @@ const PLUGIN_STORE_SOURCES = [
// 插件目录 - 使用 pathWrapper
const getPluginsDir = () => webUiPathWrapper.pluginPath;
/**
* 验证插件 ID,防止路径注入攻击
*/
function validatePluginId (id: any): string {
if (typeof id !== 'string') {
throw new Error('Invalid plugin ID');
}
// 仅允许字母、数字、点、下划线、连字符,禁止路径遍历字符
// 通过 path.basename 进一步确保不包含路径分隔符
const safeId = path.basename(id);
if (!/^[a-zA-Z0-9._-]+$/.test(safeId) || safeId !== id) {
throw new Error('Invalid plugin ID format');
}
return safeId;
}
// 插件列表缓存
let pluginListCache: PluginStoreList | null = null;
let cacheTimestamp: number = 0;
@@ -40,7 +56,7 @@ async function fetchPluginList (forceRefresh: boolean = false): Promise<PluginSt
// 检查缓存(如果不是强制刷新)
const now = Date.now();
if (!forceRefresh && pluginListCache && (now - cacheTimestamp) < CACHE_TTL) {
//console.log('Using cached plugin list');
// console.log('Using cached plugin list');
return pluginListCache;
}
@@ -64,7 +80,7 @@ async function fetchPluginList (forceRefresh: boolean = false): Promise<PluginSt
}
const data = await response.json();
//console.log(`Successfully fetched plugin list from: ${url}`);
// console.log(`Successfully fetched plugin list from: ${url}`);
// 更新缓存
pluginListCache = data as PluginStoreList;
@@ -86,7 +102,13 @@ async function fetchPluginList (forceRefresh: boolean = false): Promise<PluginSt
* 下载文件,使用镜像系统
* 自动识别 GitHub Release URL 并使用镜像加速
*/
async function downloadFile (url: string, destPath: string, customMirror?: string): Promise<void> {
async function downloadFile (
url: string,
destPath: string,
customMirror?: string,
onProgress?: (percent: number, downloaded: number, total: number, speed: number) => void,
timeout: number = 120000 // 默认120秒超时
): Promise<void> {
try {
let downloadUrl: string;
@@ -126,7 +148,7 @@ async function downloadFile (url: string, destPath: string, customMirror?: strin
headers: {
'User-Agent': 'NapCat-WebUI',
},
signal: AbortSignal.timeout(120000), // 实际下载120秒超时
signal: AbortSignal.timeout(timeout), // 使用传入的超时时间
});
if (!response.ok) {
@@ -137,9 +159,45 @@ async function downloadFile (url: string, destPath: string, customMirror?: strin
throw new Error('Response body is null');
}
const totalLength = Number(response.headers.get('content-length')) || 0;
// 初始进度通知
if (onProgress) {
onProgress(0, 0, totalLength, 0);
}
let downloaded = 0;
let lastTime = Date.now();
let lastDownloaded = 0;
// 进度监控流
// eslint-disable-next-line @stylistic/generator-star-spacing
const progressMonitor = async function* (source: any) {
for await (const chunk of source) {
downloaded += chunk.length;
const now = Date.now();
const elapsedSinceLast = now - lastTime;
// 每隔 500ms 或完成时计算一次速度并更新进度
if (elapsedSinceLast >= 500 || (totalLength && downloaded === totalLength)) {
const percent = totalLength ? Math.round((downloaded / totalLength) * 100) : 0;
const speed = (downloaded - lastDownloaded) / (elapsedSinceLast / 1000); // bytes/s
if (onProgress) {
onProgress(percent, downloaded, totalLength, speed);
}
lastTime = now;
lastDownloaded = downloaded;
}
yield chunk;
}
};
// 写入文件
const fileStream = createWriteStream(destPath);
await pipeline(response.body as any, fileStream);
await pipeline(progressMonitor(response.body), fileStream);
console.log(`Successfully downloaded to: ${destPath}`);
} catch (e: any) {
@@ -155,13 +213,15 @@ async function downloadFile (url: string, destPath: string, customMirror?: strin
* 解压插件到指定目录
*/
async function extractPlugin (zipPath: string, pluginId: string): Promise<void> {
// 验证 pluginId 确保安全
const safeId = validatePluginId(pluginId);
const PLUGINS_DIR = getPluginsDir();
const pluginDir = path.join(PLUGINS_DIR, pluginId);
const pluginDir = path.join(PLUGINS_DIR, safeId);
const dataDir = path.join(pluginDir, 'data');
const tempDataDir = path.join(PLUGINS_DIR, `${pluginId}.data.backup`);
const tempDataDir = path.join(PLUGINS_DIR, `${safeId}.data.backup`);
console.log(`[extractPlugin] PLUGINS_DIR: ${PLUGINS_DIR}`);
console.log(`[extractPlugin] pluginId: ${pluginId}`);
console.log(`[extractPlugin] pluginId: ${safeId}`);
console.log(`[extractPlugin] Target directory: ${pluginDir}`);
console.log(`[extractPlugin] Zip file: ${zipPath}`);
@@ -210,7 +270,7 @@ async function extractPlugin (zipPath: string, pluginId: string): Promise<void>
} catch (e) {
// 解压失败时,尝试恢复 data 文件夹
if (hasDataBackup && fs.existsSync(tempDataDir)) {
console.log(`[extractPlugin] Extract failed, restoring data directory`);
console.log('[extractPlugin] Extract failed, restoring data directory');
if (!fs.existsSync(pluginDir)) {
fs.mkdirSync(pluginDir, { recursive: true });
}
@@ -224,7 +284,7 @@ async function extractPlugin (zipPath: string, pluginId: string): Promise<void>
// 列出解压后的文件
const files = fs.readdirSync(pluginDir);
console.log(`[extractPlugin] Extracted files:`, files);
console.log('[extractPlugin] Extracted files:', files);
}
/**
@@ -246,7 +306,7 @@ export const GetPluginStoreListHandler: RequestHandler = async (req, res) => {
*/
export const GetPluginStoreDetailHandler: RequestHandler = async (req, res) => {
try {
const { id } = req.params;
const id = validatePluginId(req.params['id']);
const data = await fetchPluginList();
const plugin = data.plugins.find(p => p.id === id);
@@ -265,12 +325,14 @@ export const GetPluginStoreDetailHandler: RequestHandler = async (req, res) => {
*/
export const InstallPluginFromStoreHandler: RequestHandler = async (req, res) => {
try {
const { id, mirror } = req.body;
const { id: rawId, mirror } = req.body;
if (!id) {
if (!rawId) {
return sendError(res, 'Plugin ID is required');
}
const id = validatePluginId(rawId);
// 获取插件信息
const data = await fetchPluginList();
const plugin = data.plugins.find(p => p.id === id);
@@ -279,12 +341,21 @@ export const InstallPluginFromStoreHandler: RequestHandler = async (req, res) =>
return sendError(res, 'Plugin not found in store');
}
// 检查是否已安装相同版本
const pm = getPluginManager();
if (pm) {
const installedInfo = pm.getPluginInfo(id);
if (installedInfo && installedInfo.version === plugin.version) {
return sendError(res, '该插件已安装且版本相同,无需重复安装');
}
}
// 下载插件
const PLUGINS_DIR = getPluginsDir();
const tempZipPath = path.join(PLUGINS_DIR, `${id}.temp.zip`);
try {
await downloadFile(plugin.downloadUrl, tempZipPath, mirror);
await downloadFile(plugin.downloadUrl, tempZipPath, mirror, undefined, 300000);
// 解压插件
await extractPlugin(tempZipPath, id);
@@ -305,7 +376,7 @@ export const InstallPluginFromStoreHandler: RequestHandler = async (req, res) =>
return sendSuccess(res, {
message: 'Plugin installed successfully',
plugin: plugin,
plugin,
installPath: path.join(PLUGINS_DIR, id),
});
} catch (downloadError: any) {
@@ -324,21 +395,29 @@ export const InstallPluginFromStoreHandler: RequestHandler = async (req, res) =>
* 安装插件(从商店)- SSE 版本,实时推送进度
*/
export const InstallPluginFromStoreSSEHandler: RequestHandler = async (req, res) => {
const { id, mirror } = req.query;
const { id: rawId, mirror } = req.query;
if (!id || typeof id !== 'string') {
if (!rawId || typeof rawId !== 'string') {
res.status(400).json({ error: 'Plugin ID is required' });
return;
}
let id: string;
try {
id = validatePluginId(rawId);
} catch (err: any) {
res.status(400).json({ error: err.message });
return;
}
// 设置 SSE 响应头
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
const sendProgress = (message: string, progress?: number) => {
res.write(`data: ${JSON.stringify({ message, progress })}\n\n`);
const sendProgress = (message: string, progress?: number, detail?: any) => {
res.write(`data: ${JSON.stringify({ message, progress, ...detail })}\n\n`);
};
try {
@@ -355,6 +434,18 @@ export const InstallPluginFromStoreSSEHandler: RequestHandler = async (req, res)
return;
}
// 检查是否已安装相同版本
const pm = getPluginManager();
if (pm) {
const installedInfo = pm.getPluginInfo(id);
if (installedInfo && installedInfo.version === plugin.version) {
sendProgress('错误: 该插件已安装且版本相同', 0);
res.write(`data: ${JSON.stringify({ error: '该插件已安装且版本相同,无需重复安装' })}\n\n`);
res.end();
return;
}
}
sendProgress(`找到插件: ${plugin.name} v${plugin.version}`, 20);
sendProgress(`下载地址: ${plugin.downloadUrl}`, 25);
@@ -368,12 +459,28 @@ export const InstallPluginFromStoreSSEHandler: RequestHandler = async (req, res)
try {
sendProgress('正在下载插件...', 30);
await downloadFile(plugin.downloadUrl, tempZipPath, mirror as string | undefined);
await downloadFile(plugin.downloadUrl, tempZipPath, mirror as string | undefined, (percent, downloaded, total, speed) => {
const overallProgress = 30 + Math.round(percent * 0.5);
const downloadedMb = (downloaded / 1024 / 1024).toFixed(1);
const totalMb = total ? (total / 1024 / 1024).toFixed(1) : '?';
const speedMb = (speed / 1024 / 1024).toFixed(2);
const eta = (total > 0 && speed > 0) ? Math.round((total - downloaded) / speed) : -1;
sendProgress('下载完成,正在解压...', 70);
sendProgress(`正在下载插件... ${percent}%`, overallProgress, {
downloaded,
total,
speed,
eta,
downloadedStr: `${downloadedMb}MB`,
totalStr: `${totalMb}MB`,
speedStr: `${speedMb}MB/s`,
});
}, 300000);
sendProgress('下载完成,正在解压...', 85);
await extractPlugin(tempZipPath, id);
sendProgress('解压完成,正在清理...', 90);
sendProgress('解压完成,正在清理...', 95);
fs.unlinkSync(tempZipPath);
// 如果 pluginManager 存在,立即注册或重载插件
@@ -393,7 +500,7 @@ export const InstallPluginFromStoreSSEHandler: RequestHandler = async (req, res)
res.write(`data: ${JSON.stringify({
success: true,
message: 'Plugin installed successfully',
plugin: plugin,
plugin,
installPath: path.join(PLUGINS_DIR, id),
})}\n\n`);
res.end();
@@ -4,6 +4,22 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { WebUiConfig } from '@/napcat-webui-backend/index';
import { isEmpty } from '@/napcat-webui-backend/src/utils/check';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { Registry20Utils } from '@/napcat-webui-backend/src/utils/guid';
// 获取 Registry20 路径的辅助函数
const getRegistryPath = () => {
// 优先从 WebUiDataRuntime 获取早期设置的 dataPath
let dataPath = WebUiDataRuntime.getQQDataPath();
if (!dataPath) {
// 回退: 从 OneBotContext 获取
const oneBotContext = WebUiDataRuntime.getOneBotContext();
dataPath = oneBotContext?.core?.dataPath;
}
if (!dataPath) {
throw new Error('QQ data path not available yet');
}
return Registry20Utils.getRegistryPath(dataPath);
};
// 获取QQ登录二维码
export const QQGetQRcodeHandler: RequestHandler = async (_, res) => {
@@ -147,3 +163,106 @@ export const QQPasswordLoginHandler: RequestHandler = async (req, res) => {
}
return sendSuccess(res, null);
};
// 重置设备信息
export const QQResetDeviceIDHandler: RequestHandler = async (_, res) => {
try {
const registryPath = getRegistryPath();
// 自动备份
try {
await Registry20Utils.backup(registryPath);
} catch (e) {
// 忽略备份错误(例如文件不存在)
}
await Registry20Utils.delete(registryPath);
return sendSuccess(res, { message: 'Device ID reset successfully (Registry20 deleted)' });
} catch (e) {
return sendError(res, `Failed to reset Device ID: ${(e as Error).message}`);
}
};
// 获取设备 GUID
export const QQGetDeviceGUIDHandler: RequestHandler = async (_, res) => {
try {
const registryPath = getRegistryPath();
const guid = await Registry20Utils.readGuid(registryPath);
return sendSuccess(res, { guid });
} catch (e) {
// 可能是文件不存在,或者非 Windows 平台,或者解密失败
return sendError(res, `Failed to get GUID: ${(e as Error).message}`);
}
};
// 设置设备 GUID
export const QQSetDeviceGUIDHandler: RequestHandler = async (req, res) => {
const { guid } = req.body;
if (!guid || typeof guid !== 'string' || guid.length !== 32) {
return sendError(res, 'Invalid GUID format, must be 32 hex characters');
}
try {
const registryPath = getRegistryPath();
// 自动备份
try {
await Registry20Utils.backup(registryPath);
} catch { }
await Registry20Utils.writeGuid(registryPath, guid);
return sendSuccess(res, { message: 'GUID set successfully' });
} catch (e) {
return sendError(res, `Failed to set GUID: ${(e as Error).message}`);
}
};
// 获取备份列表
export const QQGetGUIDBackupsHandler: RequestHandler = async (_, res) => {
try {
const registryPath = getRegistryPath();
const backups = Registry20Utils.getBackups(registryPath);
return sendSuccess(res, backups);
} catch (e) {
return sendError(res, `Failed to get backups: ${(e as Error).message}`);
}
};
// 恢复备份
export const QQRestoreGUIDBackupHandler: RequestHandler = async (req, res) => {
const { backupName } = req.body;
if (!backupName) {
return sendError(res, 'Backup name is required');
}
try {
const registryPath = getRegistryPath();
await Registry20Utils.restore(registryPath, backupName);
return sendSuccess(res, { message: 'Restored successfully' });
} catch (e) {
return sendError(res, `Failed to restore: ${(e as Error).message}`);
}
};
// 创建备份
export const QQCreateGUIDBackupHandler: RequestHandler = async (_, res) => {
try {
const registryPath = getRegistryPath();
const backupPath = await Registry20Utils.backup(registryPath);
return sendSuccess(res, { message: 'Backup created', path: backupPath });
} catch (e) {
return sendError(res, `Failed to backup: ${(e as Error).message}`);
}
};
// 重启NapCat
export const QQRestartNapCatHandler: RequestHandler = async (_, res) => {
try {
const result = await WebUiDataRuntime.requestRestartProcess();
if (result.result) {
return sendSuccess(res, { message: result.message || 'Restart initiated' });
} else {
return sendError(res, result.message || 'Restart failed');
}
} catch (e) {
return sendError(res, `Restart error: ${(e as Error).message}`);
}
};
@@ -16,6 +16,7 @@ const LoginRuntime: LoginRuntimeType = {
},
QQLoginError: '',
QQVersion: 'unknown',
QQDataPath: '',
OneBotContext: null,
onQQLoginStatusChange: async (status: boolean) => {
LoginRuntime.QQLoginStatus = status;
@@ -167,6 +168,14 @@ export const WebUiDataRuntime = {
return LoginRuntime.QQVersion;
},
setQQDataPath (dataPath: string) {
LoginRuntime.QQDataPath = dataPath;
},
getQQDataPath (): string {
return LoginRuntime.QQDataPath;
},
setWebUiConfigQuickFunction (func: LoginRuntimeType['WebUiConfigQuickFunction']): void {
LoginRuntime.WebUiConfigQuickFunction = func;
},
@@ -11,6 +11,13 @@ import {
setAutoLoginAccountHandler,
QQRefreshQRcodeHandler,
QQPasswordLoginHandler,
QQResetDeviceIDHandler,
QQRestartNapCatHandler,
QQGetDeviceGUIDHandler,
QQSetDeviceGUIDHandler,
QQGetGUIDBackupsHandler,
QQRestoreGUIDBackupHandler,
QQCreateGUIDBackupHandler,
} from '@/napcat-webui-backend/src/api/QQLogin';
const router: Router = Router();
@@ -34,5 +41,19 @@ router.post('/SetQuickLoginQQ', setAutoLoginAccountHandler);
router.post('/RefreshQRcode', QQRefreshQRcodeHandler);
// router:密码登录
router.post('/PasswordLogin', QQPasswordLoginHandler);
// router:重置设备信息
router.post('/ResetDeviceID', QQResetDeviceIDHandler);
// router:重启NapCat
router.post('/RestartNapCat', QQRestartNapCatHandler);
// router:获取设备GUID
router.post('/GetDeviceGUID', QQGetDeviceGUIDHandler);
// router:设置设备GUID
router.post('/SetDeviceGUID', QQSetDeviceGUIDHandler);
// router:获取GUID备份列表
router.post('/GetGUIDBackups', QQGetGUIDBackupsHandler);
// router:恢复GUID备份
router.post('/RestoreGUIDBackup', QQRestoreGUIDBackupHandler);
// router:创建GUID备份
router.post('/CreateGUIDBackup', QQCreateGUIDBackupHandler);
export { router as QQLoginRouter };
@@ -49,6 +49,7 @@ export interface LoginRuntimeType {
QQLoginInfo: SelfInfo;
QQLoginError: string;
QQVersion: string;
QQDataPath: string;
onQQLoginStatusChange: (status: boolean) => Promise<void>;
onWebUiTokenChange: (token: string) => Promise<void>;
onRefreshQRCode: () => Promise<void>;
@@ -0,0 +1,116 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { protectData, unprotectData } from 'napcat-dpapi';
const GUID_HEADER = Buffer.from([0x00, 0x00, 0x00, 0x14]);
const XOR_KEY = 0x10;
/**
* Unprotects data using Windows DPAPI via napcat-dpapi.
*/
function dpapiUnprotect (filePath: string): Buffer {
const encrypted = fs.readFileSync(filePath);
return Buffer.from(unprotectData(encrypted, null, 'CurrentUser'));
}
/**
* Protects data using Windows DPAPI and writes to file.
*/
function dpapiProtectAndWrite (filePath: string, data: Buffer): void {
const encrypted = protectData(data, null, 'CurrentUser');
fs.writeFileSync(filePath, Buffer.from(encrypted));
}
export class Registry20Utils {
static getRegistryPath (dataPath: string): string {
return path.join(dataPath, 'nt_qq', 'global', 'nt_data', 'msf', 'Registry20');
}
static readGuid (registryPath: string): string {
if (!fs.existsSync(registryPath)) {
throw new Error('Registry20 file not found');
}
if (os.platform() !== 'win32') {
throw new Error('Registry20 decryption is only supported on Windows');
}
const decrypted = dpapiUnprotect(registryPath);
if (decrypted.length < 20) {
throw new Error(`Decrypted data too short (got ${decrypted.length} bytes, need 20)`);
}
// Decode payload: header(4) + obfuscated_guid(16)
const payload = decrypted.subarray(4, 20);
const guidBuf = Buffer.alloc(16);
for (let i = 0; i < 16; i++) {
const payloadByte = payload[i] ?? 0;
guidBuf[i] = (~(payloadByte ^ XOR_KEY)) & 0xFF;
}
return guidBuf.toString('hex');
}
static writeGuid (registryPath: string, guidHex: string): void {
if (guidHex.length !== 32) {
throw new Error('Invalid GUID length, must be 32 hex chars');
}
if (os.platform() !== 'win32') {
throw new Error('Registry20 encryption is only supported on Windows');
}
const guidBytes = Buffer.from(guidHex, 'hex');
const payload = Buffer.alloc(16);
for (let i = 0; i < 16; i++) {
const guidByte = guidBytes[i] ?? 0;
payload[i] = XOR_KEY ^ (~guidByte & 0xFF);
}
const data = Buffer.concat([GUID_HEADER, payload]);
// Create directory if not exists
const dir = path.dirname(registryPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
dpapiProtectAndWrite(registryPath, data);
}
static getBackups (registryPath: string): string[] {
const dir = path.dirname(registryPath);
const baseName = path.basename(registryPath);
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir)
.filter(f => f.startsWith(`${baseName}.bak.`))
.sort()
.reverse();
}
static backup (registryPath: string): string {
if (!fs.existsSync(registryPath)) {
throw new Error('Registry20 does not exist');
}
const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
const backupPath = `${registryPath}.bak.${timestamp}`;
fs.copyFileSync(registryPath, backupPath);
return backupPath;
}
static restore (registryPath: string, backupFileName: string): void {
const dir = path.dirname(registryPath);
const backupPath = path.join(dir, backupFileName);
if (!fs.existsSync(backupPath)) {
throw new Error('Backup file not found');
}
fs.copyFileSync(backupPath, registryPath);
}
static delete (registryPath: string): void {
if (fs.existsSync(registryPath)) {
fs.unlinkSync(registryPath);
}
}
}
@@ -1,13 +1,56 @@
import { Avatar } from '@heroui/avatar';
import { Button } from '@heroui/button';
import { Switch } from '@heroui/switch';
import { Card, CardBody, CardFooter } from '@heroui/card';
import { Chip } from '@heroui/chip';
import { useState } from 'react';
import { Switch } from '@heroui/switch';
import { Tooltip } from '@heroui/tooltip';
import { MdDeleteForever, MdSettings } from 'react-icons/md';
import clsx from 'clsx';
import { useLocalStorage } from '@uidotdev/usehooks';
import { useState } from 'react';
import DisplayCardContainer from './container';
import key from '@/const/key';
import { PluginItem } from '@/controllers/plugin_manager';
/** 提取作者头像 URL */
function getAuthorAvatar (homepage?: string, repository?: string): string | undefined {
// 1. 尝试从 repository 提取 GitHub 用户名
if (repository) {
try {
// 处理 git+https://github.com/... 或 https://github.com/...
const repoUrl = repository.replace(/^git\+/, '').replace(/\.git$/, '');
const url = new URL(repoUrl);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
}
} catch {
// 忽略解析错误
}
}
// 2. 尝试从 homepage 提取
if (homepage) {
try {
const url = new URL(homepage);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
} else {
// 如果是自定义域名,尝试获取 favicon
return `https://api.iowen.cn/favicon/${url.hostname}.png`;
}
} catch {
// 忽略解析错误
}
}
return undefined;
}
export interface PluginDisplayCardProps {
data: PluginItem;
onToggleStatus: () => Promise<void>;
@@ -23,9 +66,15 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
onConfig,
hasConfig = false,
}) => {
const { name, version, author, description, status } = data;
const { name, version, author, description, status, homepage, repository } = data;
const isEnabled = status === 'active';
const [processing, setProcessing] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [backgroundImage] = useLocalStorage<string>(key.backgroundImage, '');
const hasBackground = !!backgroundImage;
// 综合尝试提取头像,最后兜底使用 Vercel 风格头像
const avatarUrl = getAuthorAvatar(homepage, repository) || `https://avatar.vercel.sh/${encodeURIComponent(name)}`;
const handleToggle = () => {
setProcessing(true);
@@ -38,88 +87,132 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
};
return (
<DisplayCardContainer
className='w-full max-w-[420px]'
action={
<div className='flex flex-col gap-2 w-full'>
<div className='flex gap-2 w-full'>
<Button
fullWidth
<Card
className={clsx(
'group w-full backdrop-blur-md rounded-2xl overflow-hidden transition-all duration-300',
'hover:shadow-xl hover:-translate-y-1',
'border border-white/50 dark:border-white/10 hover:border-primary/50 dark:hover:border-primary/50',
hasBackground ? 'bg-white/20 dark:bg-black/10' : 'bg-white/60 dark:bg-black/30'
)}
shadow='sm'
>
<CardBody className='p-4 flex flex-col gap-3'>
{/* Header */}
<div className='flex items-start justify-between gap-3'>
<div className='flex items-center gap-3 min-w-0'>
<Avatar
src={avatarUrl}
name={author || '?'}
className='flex-shrink-0'
size='md'
isBordered
radius='full'
size='sm'
variant='flat'
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-danger/20 hover:text-danger transition-colors'
startContent={<MdDeleteForever size={16} />}
onPress={handleUninstall}
isDisabled={processing}
>
卸载
</Button>
color='default'
/>
<div className='min-w-0'>
<h3 className='text-base font-bold text-default-900 truncate' title={name}>
{name}
</h3>
<p className='text-xs text-default-500 mt-0.5 truncate'>
by <span className='font-medium'>{author || '未知'}</span>
</p>
</div>
</div>
{hasConfig && (
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-secondary/20 hover:text-secondary transition-colors'
startContent={<MdSettings size={16} />}
onPress={onConfig}
>
配置
</Button>
)}
<Chip
size='sm'
variant='flat'
color={status === 'active' ? 'success' : status === 'stopped' ? 'warning' : 'default'}
className='flex-shrink-0 font-medium h-6 px-1'
>
{status === 'active' ? '运行中' : status === 'stopped' ? '已停止' : '已禁用'}
</Chip>
</div>
}
enableSwitch={
{/* Description */}
<div
className='relative min-h-[2.5rem] cursor-pointer group/desc'
onClick={() => setIsExpanded(!isExpanded)}
>
<Tooltip
content={description}
isDisabled={!description || description.length < 50 || isExpanded}
placement='bottom'
className='max-w-[280px]'
delay={500}
>
<p className={clsx(
'text-sm text-default-600 dark:text-default-400 leading-relaxed transition-all duration-300',
isExpanded ? 'line-clamp-none' : 'line-clamp-2'
)}
>
{description || '暂无描述'}
</p>
</Tooltip>
</div>
{/* Version Badge */}
<div>
<Chip
size='sm'
variant='flat'
color='primary'
className='h-5 text-xs font-semibold px-0.5'
classNames={{ content: 'px-1' }}
>
v{version}
</Chip>
</div>
</CardBody>
<CardFooter className='px-4 pb-4 pt-0 gap-3'>
<Switch
isDisabled={processing}
isSelected={isEnabled}
onChange={handleToggle}
onValueChange={handleToggle}
size='sm'
color='success'
classNames={{
wrapper: 'group-data-[selected=true]:bg-primary-400',
wrapper: 'group-data-[selected=true]:bg-success',
}}
/>
}
title={name}
tag={
<Chip
className="ml-auto"
color={status === 'active' ? 'success' : status === 'stopped' ? 'warning' : 'default'}
size="sm"
variant="flat"
>
{status === 'active' ? '运行中' : status === 'stopped' ? '已停止' : '已禁用'}
</Chip>
}
>
<div className='grid grid-cols-2 gap-3'>
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
版本
<span className='text-xs font-medium text-default-600'>
{isEnabled ? '已启用' : '已禁用'}
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 truncate'>
{version}
</div>
</div>
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
作者
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 truncate'>
{author || '未知'}
</div>
</div>
<div className='col-span-2 flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
描述
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 break-words line-clamp-2'>
{description || '暂无描述'}
</div>
</div>
</div>
</DisplayCardContainer>
</Switch>
<div className='flex-1' />
{hasConfig && (
<Tooltip content='插件配置'>
<Button
isIconOnly
radius='full'
size='sm'
variant='light'
color='primary'
onPress={onConfig}
>
<MdSettings size={20} />
</Button>
</Tooltip>
)}
<Tooltip content='卸载插件' color='danger'>
<Button
isIconOnly
radius='full'
size='sm'
variant='light'
color='danger'
onPress={handleUninstall}
isDisabled={processing}
>
<MdDeleteForever size={20} />
</Button>
</Tooltip>
</CardFooter>
</Card>
);
};
@@ -1,17 +1,61 @@
/* eslint-disable @stylistic/indent */
import { Avatar } from '@heroui/avatar';
import { Button } from '@heroui/button';
import { Card, CardBody, CardFooter } from '@heroui/card';
import { Chip } from '@heroui/chip';
import { Tooltip } from '@heroui/tooltip';
import { IoMdCheckmarkCircle } from 'react-icons/io';
import { MdUpdate, MdOutlineGetApp } from 'react-icons/md';
import clsx from 'clsx';
import { useLocalStorage } from '@uidotdev/usehooks';
import { useState } from 'react';
import { IoMdDownload, IoMdRefresh, IoMdCheckmarkCircle } from 'react-icons/io';
import DisplayCardContainer from './container';
import key from '@/const/key';
import { PluginStoreItem } from '@/types/plugin-store';
export type InstallStatus = 'not-installed' | 'installed' | 'update-available';
/** 提取作者头像 URL */
function getAuthorAvatar (homepage?: string, downloadUrl?: string): string | undefined {
// 1. 尝试从 downloadUrl 提取 GitHub 用户名 (通常是最准确的源码仓库所有者)
if (downloadUrl) {
try {
const url = new URL(downloadUrl);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
}
} catch {
// 忽略解析错误
}
}
// 2. 尝试从 homepage 提取
if (homepage) {
try {
const url = new URL(homepage);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
} else {
// 如果是自定义域名,尝试获取 favicon。使用主流的镜像服务以保证国内访问速度
return `https://api.iowen.cn/favicon/${url.hostname}.png`;
}
} catch {
// 忽略解析错误
}
}
return undefined;
}
export interface PluginStoreCardProps {
data: PluginStoreItem;
onInstall: () => Promise<void>;
onInstall: () => void;
onViewDetail?: () => void;
installStatus?: InstallStatus;
installedVersion?: string;
}
@@ -19,159 +63,230 @@ export interface PluginStoreCardProps {
const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
data,
onInstall,
onViewDetail,
installStatus = 'not-installed',
installedVersion,
}) => {
const { name, version, author, description, tags, id, homepage } = data;
const [processing, setProcessing] = useState(false);
const { name, version, author, description, tags, homepage, downloadUrl } = data;
const [backgroundImage] = useLocalStorage<string>(key.backgroundImage, '');
const [isExpanded, setIsExpanded] = useState(false);
const hasBackground = !!backgroundImage;
const handleInstall = () => {
setProcessing(true);
onInstall().finally(() => setProcessing(false));
};
// 综合尝试提取头像,最后兜底使用 Vercel 风格头像
const avatarUrl = getAuthorAvatar(homepage, downloadUrl) || `https://avatar.vercel.sh/${encodeURIComponent(name)}`;
// 根据安装状态返回按钮配置
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: 'default' as const,
};
default:
return {
text: '安装',
icon: <IoMdDownload size={16} />,
color: 'primary' as const,
};
}
};
const buttonConfig = getButtonConfig();
const titleContent = homepage ? (
<Tooltip
content="跳转到插件主页"
placement="top"
showArrow
offset={8}
delay={200}
>
<a
href={homepage}
target="_blank"
rel="noreferrer"
className="text-inherit inline-block bg-no-repeat bg-left-bottom [background-image:repeating-linear-gradient(90deg,currentColor_0_2px,transparent_2px_5px)] [background-size:0%_2px] hover:[background-size:100%_2px] transition-[background-size] duration-200 ease-out"
>
{name}
</a>
</Tooltip>
) : (
name
// 作者链接组件
const AuthorComponent = (
<span className={clsx('font-medium transition-colors', homepage ? 'hover:text-primary hover:underline cursor-pointer' : '')}>
{author || '未知作者'}
</span>
);
return (
<DisplayCardContainer
className='w-full max-w-[420px]'
title={titleContent}
tag={
<div className="ml-auto flex items-center gap-1">
{installStatus === 'installed' && (
<Chip
color="success"
size="sm"
variant="flat"
startContent={<IoMdCheckmarkCircle size={14} />}
<Card
className={clsx(
'group w-full backdrop-blur-md rounded-2xl overflow-hidden transition-all duration-300',
'hover:shadow-xl hover:-translate-y-1',
// 降低边框粗细
'border border-white/50 dark:border-white/10 hover:border-primary/50 dark:hover:border-primary/50',
hasBackground ? 'bg-white/20 dark:bg-black/10' : 'bg-white/60 dark:bg-black/30'
)}
shadow='sm'
>
<CardBody
className={clsx('p-4 flex flex-col gap-3', onViewDetail && 'cursor-pointer')}
onClick={onViewDetail}
>
{/* Header: Avatar + Name + Author */}
<div className='flex items-start gap-3'>
<Avatar
src={avatarUrl}
name={author || '?'}
size='md'
isBordered
color='default'
radius='full' // 圆形头像
className='flex-shrink-0 transition-transform group-hover:scale-105'
/>
<div className='flex-1 min-w-0'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-1.5 min-w-0'>
{homepage
? (
<Tooltip content='访问项目主页' placement='top' delay={500}>
<a
href={homepage}
target='_blank'
rel='noreferrer'
className='text-base font-bold text-default-900 hover:text-primary transition-colors truncate'
onClick={(e) => e.stopPropagation()}
>
{name}
</a>
</Tooltip>
)
: (
<h3 className='text-base font-bold text-default-900 truncate' title={name}>
{name}
</h3>
)}
</div>
</div>
{/* 可点击的作者名称 */}
<div className='text-xs text-default-500 mt-0.5 truncate'>
by {homepage
? (
<a
href={homepage}
target='_blank'
rel='noreferrer'
onClick={(e) => e.stopPropagation()}
>
{AuthorComponent}
</a>
)
: AuthorComponent}
</div>
</div>
</div>
{/* Description */}
<div
className='relative min-h-[2.5rem] cursor-pointer group/desc'
onClick={() => setIsExpanded(!isExpanded)}
>
<Tooltip
content={description}
isDisabled={!description || description.length < 50 || isExpanded}
placement='bottom'
className='max-w-[280px]'
delay={500}
>
<p className={clsx(
'text-sm text-default-600 dark:text-default-400 leading-relaxed transition-all duration-300',
isExpanded ? 'line-clamp-none' : 'line-clamp-2'
)}
>
已安装
</Chip>
)}
{installStatus === 'update-available' && (
<Chip
color="warning"
size="sm"
variant="flat"
>
可更新
</Chip>
)}
{description || '暂无描述'}
</p>
</Tooltip>
</div>
{/* Tags & Version */}
<div className='flex items-center gap-1.5 flex-wrap'>
<Chip
color="primary"
size="sm"
variant="flat"
size='sm'
variant='flat'
color='primary'
className='h-5 text-xs font-semibold px-0.5'
classNames={{ content: 'px-1' }}
>
v{version}
</Chip>
{/* Tags with proper truncation and hover */}
{tags?.slice(0, 2).map((tag) => (
<Chip
key={tag}
size='sm'
variant='flat'
className='h-5 text-xs px-0.5 bg-default-100 dark:bg-default-50/50 text-default-600'
classNames={{ content: 'px-1' }}
>
{tag}
</Chip>
))}
{tags && tags.length > 2 && (
<Tooltip
content={
<div className='flex flex-wrap gap-1 max-w-[200px] p-1'>
{tags.map(t => (
<span key={t} className='text-xs bg-white/10 px-1.5 py-0.5 rounded-md border border-white/10'>
{t}
</span>
))}
</div>
}
delay={0}
closeDelay={0}
>
<Chip
size='sm'
variant='flat'
className='h-5 text-xs px-0.5 cursor-pointer hover:bg-default-200 transition-colors'
classNames={{ content: 'px-1' }}
>
+{tags.length - 2}
</Chip>
</Tooltip>
)}
{installStatus === 'update-available' && installedVersion && (
<Chip
size='sm'
variant='shadow'
color='warning'
className='h-5 text-xs font-semibold px-0.5 ml-auto animate-pulse'
classNames={{ content: 'px-1' }}
>
新版本
</Chip>
)}
</div>
}
enableSwitch={undefined}
action={
<Button
fullWidth
radius='full'
size='sm'
color={buttonConfig.color}
startContent={buttonConfig.icon}
onPress={handleInstall}
isLoading={processing}
isDisabled={processing}
>
{buttonConfig.text}
</Button>
}
>
<div className='grid grid-cols-2 gap-3'>
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
作者
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 truncate'>
{author || '未知'}
</div>
</div>
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
版本
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 truncate'>
v{version}
</div>
</div>
<div className='col-span-2 flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
描述
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 break-words line-clamp-2 h-10 overflow-hidden'>
{description || '暂无描述'}
</div>
</div>
{id && (
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
包名
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 break-words line-clamp-2 h-10 overflow-hidden'>
{id || '包名'}
</div>
</div>
)}
{tags && tags.length > 0 && (
<div className='flex flex-col gap-1 p-3 bg-default-100/50 dark:bg-white/10 rounded-xl border border-transparent hover:border-default-200 transition-colors'>
<span className='text-xs text-default-500 dark:text-white/50 font-medium tracking-wide'>
标签
</span>
<div className='text-sm font-medium text-default-700 dark:text-white/90 truncate'>
{tags.slice(0, 2).join(' · ')}
</div>
</div>
)}
</div>
</DisplayCardContainer>
</CardBody>
<CardFooter
className='px-4 pb-4 pt-0'
onClick={(e) => e.stopPropagation()}
>
{installStatus === 'installed'
? (
<Button
fullWidth
radius='full'
size='sm'
color='success'
variant='flat'
startContent={<IoMdCheckmarkCircle size={18} />}
className='font-medium bg-success/20 text-success dark:bg-success/20 cursor-default'
isDisabled
>
已安装
</Button>
)
: installStatus === 'update-available'
? (
<Button
fullWidth
radius='full'
size='sm'
color='warning'
variant='shadow'
className='font-medium text-white shadow-warning/30 hover:shadow-warning/50 transition-shadow'
startContent={<MdUpdate size={18} />}
onPress={onInstall}
>
更新到 v{version}
</Button>
)
: (
<Button
fullWidth
radius='full'
size='sm'
color='primary'
variant='bordered'
className='font-medium bg-white dark:bg-zinc-900 border hover:bg-primary hover:text-white transition-all shadow-sm group/btn'
startContent={<MdOutlineGetApp size={20} className='transition-transform group-hover/btn:translate-y-0.5' />}
onPress={onInstall}
>
立即安装
</Button>
)}
</CardFooter>
</Card>
);
};
@@ -0,0 +1,317 @@
import { Button } from '@heroui/button';
import { Input } from '@heroui/input';
import { Divider } from '@heroui/divider';
import { Chip } from '@heroui/chip';
import { Listbox, ListboxItem } from '@heroui/listbox';
import { Spinner } from '@heroui/spinner';
import { useEffect, useState, useCallback } from 'react';
import toast from 'react-hot-toast';
import { MdContentCopy, MdDelete, MdRefresh, MdSave, MdRestorePage, MdBackup } from 'react-icons/md';
import QQManager from '@/controllers/qq_manager';
import useDialog from '@/hooks/use-dialog';
interface GUIDManagerProps {
/** 是否显示重启按钮 */
showRestart?: boolean;
/** 紧凑模式(用于弹窗场景) */
compact?: boolean;
}
const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact = false }) => {
const dialog = useDialog();
const [currentGUID, setCurrentGUID] = useState<string>('');
const [inputGUID, setInputGUID] = useState<string>('');
const [backups, setBackups] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [restarting, setRestarting] = useState(false);
const isValidGUID = (guid: string) => /^[0-9a-fA-F]{32}$/.test(guid);
const fetchGUID = useCallback(async () => {
setLoading(true);
try {
const data = await QQManager.getDeviceGUID();
setCurrentGUID(data.guid);
setInputGUID(data.guid);
} catch (error) {
const msg = (error as Error).message;
setCurrentGUID('');
setInputGUID('');
if (!msg.includes('not found')) {
toast.error(`获取 GUID 失败: ${msg}`);
}
} finally {
setLoading(false);
}
}, []);
const fetchBackups = useCallback(async () => {
try {
const data = await QQManager.getGUIDBackups();
setBackups(data);
} catch {
// ignore
}
}, []);
useEffect(() => {
fetchGUID();
fetchBackups();
}, [fetchGUID, fetchBackups]);
const handleCopy = () => {
if (currentGUID) {
navigator.clipboard.writeText(currentGUID);
toast.success('已复制到剪贴板');
}
};
const handleSave = async () => {
if (!isValidGUID(inputGUID)) {
toast.error('GUID 格式无效,需要 32 位十六进制字符');
return;
}
setSaving(true);
try {
await QQManager.setDeviceGUID(inputGUID);
setCurrentGUID(inputGUID);
toast.success('GUID 已设置,重启后生效');
await fetchBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`设置 GUID 失败: ${msg}`);
} finally {
setSaving(false);
}
};
const handleDelete = () => {
dialog.confirm({
title: '确认删除',
content: '删除 Registry20 后,QQ 将在下次启动时生成新的设备标识。确定要删除吗?',
confirmText: '删除',
cancelText: '取消',
onConfirm: async () => {
try {
await QQManager.resetDeviceID();
setCurrentGUID('');
setInputGUID('');
toast.success('已删除,重启后生效');
await fetchBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`删除失败: ${msg}`);
}
},
});
};
const handleBackup = async () => {
try {
await QQManager.createGUIDBackup();
toast.success('备份已创建');
await fetchBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`备份失败: ${msg}`);
}
};
const handleRestore = (backupName: string) => {
dialog.confirm({
title: '确认恢复',
content: `确定要从备份 "${backupName}" 恢复吗?当前的 Registry20 将被覆盖。`,
confirmText: '恢复',
cancelText: '取消',
onConfirm: async () => {
try {
await QQManager.restoreGUIDBackup(backupName);
toast.success('已恢复,重启后生效');
await fetchGUID();
await fetchBackups();
} catch (error) {
const msg = (error as Error).message;
toast.error(`恢复失败: ${msg}`);
}
},
});
};
const handleRestart = () => {
dialog.confirm({
title: '确认重启',
content: '确定要重启 NapCat 吗?这将导致当前连接断开。',
confirmText: '重启',
cancelText: '取消',
onConfirm: async () => {
setRestarting(true);
try {
await QQManager.restartNapCat();
toast.success('重启指令已发送');
} catch (error) {
const msg = (error as Error).message;
toast.error(`重启失败: ${msg}`);
} finally {
setRestarting(false);
}
},
});
};
if (loading) {
return (
<div className='flex items-center justify-center py-8'>
<Spinner label='加载中...' />
</div>
);
}
return (
<div className={`flex flex-col gap-${compact ? '3' : '4'}`}>
{/* 当前 GUID 显示 */}
<div className='flex flex-col gap-2'>
<div className='text-sm font-medium text-default-700'>当前设备 GUID</div>
<div className='flex items-center gap-2'>
{currentGUID ? (
<Chip variant='flat' color='primary' className='font-mono text-xs max-w-full'>
{currentGUID}
</Chip>
) : (
<Chip variant='flat' color='warning' className='text-xs'>
未设置 / 不存在
</Chip>
)}
{currentGUID && (
<Button
isIconOnly
size='sm'
variant='light'
onPress={handleCopy}
aria-label='复制GUID'
>
<MdContentCopy size={16} />
</Button>
)}
<Button
isIconOnly
size='sm'
variant='light'
onPress={fetchGUID}
aria-label='刷新'
>
<MdRefresh size={16} />
</Button>
</div>
</div>
<Divider />
{/* 设置 GUID */}
<div className='flex flex-col gap-2'>
<div className='text-sm font-medium text-default-700'>设置 GUID</div>
<div className='flex items-center gap-2'>
<Input
size='sm'
variant='bordered'
placeholder='输入32位十六进制 GUID'
value={inputGUID}
onValueChange={setInputGUID}
isInvalid={inputGUID.length > 0 && !isValidGUID(inputGUID)}
errorMessage={inputGUID.length > 0 && !isValidGUID(inputGUID) ? '需要32位十六进制字符' : undefined}
classNames={{
input: 'font-mono text-sm',
}}
maxLength={32}
/>
</div>
<div className='flex items-center gap-2'>
<Button
size='sm'
color='primary'
variant='flat'
isLoading={saving}
isDisabled={!isValidGUID(inputGUID) || inputGUID === currentGUID}
onPress={handleSave}
startContent={<MdSave size={16} />}
>
保存 GUID
</Button>
<Button
size='sm'
color='danger'
variant='flat'
isDisabled={!currentGUID}
onPress={handleDelete}
startContent={<MdDelete size={16} />}
>
删除 GUID
</Button>
<Button
size='sm'
color='secondary'
variant='flat'
isDisabled={!currentGUID}
onPress={handleBackup}
startContent={<MdBackup size={16} />}
>
手动备份
</Button>
</div>
<div className='text-xs text-default-400'>
修改或删除 GUID 后需重启 NapCat 才能生效,操作前会自动备份
</div>
</div>
{/* 备份恢复 */}
{backups.length > 0 && (
<>
<Divider />
<div className='flex flex-col gap-2'>
<div className='text-sm font-medium text-default-700'>
备份列表
<span className='text-xs text-default-400 ml-2'>(点击恢复)</span>
</div>
<div className='max-h-[160px] overflow-y-auto rounded-lg border border-default-200'>
<Listbox
aria-label='备份列表'
selectionMode='none'
onAction={(key) => handleRestore(key as string)}
>
{backups.map((name) => (
<ListboxItem
key={name}
startContent={<MdRestorePage size={16} className='text-default-400' />}
className='font-mono text-xs'
>
{name}
</ListboxItem>
))}
</Listbox>
</div>
</div>
</>
)}
{/* 重启 */}
{showRestart && (
<>
<Divider />
<Button
size='sm'
color='warning'
variant='flat'
isLoading={restarting}
onPress={handleRestart}
startContent={<MdRefresh size={16} />}
>
重启 NapCat
</Button>
</>
)}
</div>
);
};
export default GUIDManager;
@@ -1,43 +1,175 @@
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
const TailwindMarkdown: React.FC<{ content: string }> = ({ content }) => {
const TailwindMarkdown: React.FC<{ content: string; }> = ({ content }) => {
return (
<Markdown
className='prose prose-sm sm:prose lg:prose-lg xl:prose-xl'
className='prose prose-sm sm:prose lg:prose-lg xl:prose-xl max-w-none'
remarkPlugins={[remarkGfm]}
components={{
h1: ({ node: _node, ...props }) => (
<h1 className='text-2xl font-bold' {...props} />
<h1
className='text-3xl font-bold mt-6 mb-4 pb-2 border-b-2 border-primary/20 text-default-900 first:mt-0'
{...props}
/>
),
h2: ({ node: _node, ...props }) => (
<h2 className='text-xl font-bold' {...props} />
<h2
className='text-2xl font-bold mt-6 mb-3 pb-2 border-b border-default-200 text-default-800'
{...props}
/>
),
h3: ({ node: _node, ...props }) => (
<h3 className='text-lg font-bold' {...props} />
<h3
className='text-xl font-semibold mt-5 mb-2 text-default-800'
{...props}
/>
),
h4: ({ node: _node, ...props }) => (
<h4
className='text-lg font-semibold mt-4 mb-2 text-default-700'
{...props}
/>
),
h5: ({ node: _node, ...props }) => (
<h5
className='text-base font-semibold mt-3 mb-2 text-default-700'
{...props}
/>
),
h6: ({ node: _node, ...props }) => (
<h6
className='text-sm font-semibold mt-3 mb-2 text-default-600'
{...props}
/>
),
p: ({ node: _node, ...props }) => (
<p
className='my-3 leading-7 text-default-700 first:mt-0 last:mb-0'
{...props}
/>
),
p: ({ node: _node, ...props }) => <p className='m-0' {...props} />,
a: ({ node: _node, ...props }) => (
<a
className='text-primary-500 inline-block hover:underline'
className='text-primary font-medium hover:text-primary-600 underline decoration-primary/30 hover:decoration-primary transition-colors'
target='_blank'
rel='noopener noreferrer'
{...props}
/>
),
ul: ({ node: _node, ...props }) => (
<ul className='list-disc list-inside' {...props} />
),
ol: ({ node: _node, ...props }) => (
<ol className='list-decimal list-inside' {...props} />
),
blockquote: ({ node: _node, ...props }) => (
<blockquote
className='border-l-4 border-default-300 pl-4 italic'
<ul
className='my-3 ml-6 space-y-2 list-disc marker:text-primary'
{...props}
/>
),
code: ({ node: _node, ...props }) => (
<code className='bg-default-100 p-1 rounded text-xs' {...props} />
ol: ({ node: _node, ...props }) => (
<ol
className='my-3 ml-6 space-y-2 list-decimal marker:text-primary marker:font-semibold'
{...props}
/>
),
li: ({ node: _node, ...props }) => (
<li
className='leading-7 text-default-700 pl-2'
{...props}
/>
),
blockquote: ({ node: _node, ...props }) => (
<blockquote
className='my-4 pl-4 pr-4 py-2 border-l-4 border-primary/50 bg-primary/5 rounded-r-lg italic text-default-600'
{...props}
/>
),
pre: ({ node: _node, ...props }) => (
<pre
className='my-4 p-4 bg-default-100 dark:bg-default-50 rounded-xl overflow-x-auto text-sm border border-default-200 shadow-sm'
{...props}
/>
),
code: ({ node: _node, inline, ...props }: any) => {
if (inline) {
return (
<code
className='px-1.5 py-0.5 mx-0.5 bg-primary/10 text-primary-700 dark:text-primary-600 rounded text-sm font-mono border border-primary/20'
{...props}
/>
);
}
return (
<code
className='text-sm font-mono text-default-800'
{...props}
/>
);
},
img: ({ node: _node, ...props }) => (
<img
className='max-w-full h-auto rounded-lg my-4 shadow-md hover:shadow-xl transition-shadow border border-default-200'
{...props}
/>
),
hr: ({ node: _node, ...props }) => (
<hr
className='my-8 border-0 h-px bg-gradient-to-r from-transparent via-default-300 to-transparent'
{...props}
/>
),
table: ({ node: _node, ...props }) => (
<div className='my-4 overflow-x-auto rounded-lg border border-default-200 shadow-sm'>
<table
className='min-w-full divide-y divide-default-200'
{...props}
/>
</div>
),
thead: ({ node: _node, ...props }) => (
<thead
className='bg-default-100'
{...props}
/>
),
tbody: ({ node: _node, ...props }) => (
<tbody
className='divide-y divide-default-200 bg-white dark:bg-default-50'
{...props}
/>
),
tr: ({ node: _node, ...props }) => (
<tr
className='hover:bg-default-50 transition-colors'
{...props}
/>
),
th: ({ node: _node, ...props }) => (
<th
className='px-4 py-3 text-left text-xs font-semibold text-default-700 uppercase tracking-wider'
{...props}
/>
),
td: ({ node: _node, ...props }) => (
<td
className='px-4 py-3 text-sm text-default-700'
{...props}
/>
),
strong: ({ node: _node, ...props }) => (
<strong
className='font-bold text-default-900'
{...props}
/>
),
em: ({ node: _node, ...props }) => (
<em
className='italic text-default-700'
{...props}
/>
),
del: ({ node: _node, ...props }) => (
<del
className='line-through text-default-500'
{...props}
/>
),
}}
>
@@ -22,6 +22,10 @@ export interface PluginItem {
hasConfig?: boolean;
/** 是否有扩展页面 */
hasPages?: boolean;
/** 主页链接 */
homepage?: string;
/** 仓库链接 */
repository?: string;
}
/** 扩展页面信息 */
@@ -101,4 +101,36 @@ export default class QQManager {
passwordMd5,
});
}
public static async resetDeviceID () {
await serverRequest.post<ServerResponse<null>>('/QQLogin/ResetDeviceID');
}
public static async restartNapCat () {
await serverRequest.post<ServerResponse<null>>('/QQLogin/RestartNapCat');
}
public static async getDeviceGUID () {
const data = await serverRequest.post<ServerResponse<{ guid: string; }>>('/QQLogin/GetDeviceGUID');
return data.data.data;
}
public static async setDeviceGUID (guid: string) {
await serverRequest.post<ServerResponse<null>>('/QQLogin/SetDeviceGUID', { guid });
}
public static async getGUIDBackups () {
const data = await serverRequest.post<ServerResponse<string[]>>('/QQLogin/GetGUIDBackups');
return data.data.data;
}
public static async restoreGUIDBackup (backupName: string) {
await serverRequest.post<ServerResponse<null>>('/QQLogin/RestoreGUIDBackup', { backupName });
}
public static async createGUIDBackup () {
const data = await serverRequest.post<ServerResponse<{ path: string; }>>('/QQLogin/CreateGUIDBackup');
return data.data.data;
}
}
@@ -1,11 +1,13 @@
import { Input } from '@heroui/input';
import { Button } from '@heroui/button';
import { Divider } from '@heroui/divider';
import { useRequest } from 'ahooks';
import { useEffect, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import toast from 'react-hot-toast';
import SaveButtons from '@/components/button/save_buttons';
import GUIDManager from '@/components/guid_manager';
import PageLoading from '@/components/page_loading';
import QQManager from '@/controllers/qq_manager';
@@ -131,6 +133,14 @@ const LoginConfigCard = () => {
重启进程将关闭当前 Worker 进程,等待 3 秒后启动新进程
</div>
</div>
<Divider className='mt-6' />
<div className='flex-shrink-0 w-full mt-4'>
<div className='mb-3 text-sm text-default-600'>设备 GUID 管理</div>
<div className='text-xs text-default-400 mb-3'>
GUID 是设备登录唯一识别码,存储在 Registry20 文件中。修改后需重启生效。
</div>
<GUIDManager showRestart={false} />
</div>
</>
);
};
@@ -18,6 +18,7 @@ interface ExtensionPage {
description?: string;
}
// eslint-disable-next-line @typescript-eslint/no-redeclare
export default function ExtensionPage () {
const [loading, setLoading] = useState(true);
const [extensionPages, setExtensionPages] = useState<ExtensionPage[]>([]);
@@ -150,28 +151,30 @@ export default function ExtensionPage () {
)}
</div>
{extensionPages.length === 0 && !loading ? (
<div className='flex-1 flex flex-col items-center justify-center text-default-400'>
<MdExtension size={64} className='mb-4 opacity-50' />
<p className='text-lg'>暂无插件扩展页面</p>
<p className='text-sm mt-2'>插件可以通过注册页面来扩展 WebUI 功能</p>
</div>
) : (
<div className='flex-1 min-h-0 bg-white/40 dark:bg-black/20 backdrop-blur-md rounded-lg overflow-hidden relative'>
{iframeLoading && (
<div className='absolute inset-0 flex items-center justify-center bg-default-100/50 z-10'>
<Spinner size='lg' />
</div>
)}
<iframe
src={currentPageUrl}
className='w-full h-full border-0'
onLoad={handleIframeLoad}
title='extension-page'
sandbox='allow-scripts allow-same-origin allow-forms allow-popups'
/>
</div>
)}
{extensionPages.length === 0 && !loading
? (
<div className='flex-1 flex flex-col items-center justify-center text-default-400'>
<MdExtension size={64} className='mb-4 opacity-50' />
<p className='text-lg'>暂无插件扩展页面</p>
<p className='text-sm mt-2'>插件可以通过注册页面来扩展 WebUI 功能</p>
</div>
)
: (
<div className='flex-1 min-h-0 bg-white/40 dark:bg-black/20 backdrop-blur-md rounded-lg overflow-hidden relative'>
{iframeLoading && (
<div className='absolute inset-0 flex items-center justify-center bg-default-100/50 z-10'>
<Spinner size='lg' />
</div>
)}
<iframe
src={currentPageUrl}
className='w-full h-full border-0'
onLoad={handleIframeLoad}
title='extension-page'
sandbox='allow-scripts allow-same-origin allow-forms allow-popups'
/>
</div>
)}
</div>
</>
);
@@ -0,0 +1,390 @@
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter } from '@heroui/modal';
import { Button } from '@heroui/button';
import { Chip } from '@heroui/chip';
import { Avatar } from '@heroui/avatar';
import { Tooltip } from '@heroui/tooltip';
import { Spinner } from '@heroui/spinner';
import { IoMdCheckmarkCircle, IoMdOpen, IoMdDownload } from 'react-icons/io';
import { MdUpdate } from 'react-icons/md';
import { useState, useEffect } from 'react';
import { PluginStoreItem } from '@/types/plugin-store';
import { InstallStatus } from '@/components/display_card/plugin_store_card';
import TailwindMarkdown from '@/components/tailwind_markdown';
interface PluginDetailModalProps {
isOpen: boolean;
onClose: () => void;
plugin: PluginStoreItem | null;
installStatus?: InstallStatus;
installedVersion?: string;
onInstall?: () => void;
}
/** 提取作者头像 URL */
function getAuthorAvatar (homepage?: string, downloadUrl?: string): string | undefined {
// 1. 尝试从 downloadUrl 提取 GitHub 用户名
if (downloadUrl) {
try {
const url = new URL(downloadUrl);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
}
} catch {
// 忽略解析错误
}
}
// 2. 尝试从 homepage 提取
if (homepage) {
try {
const url = new URL(homepage);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
} else {
return `https://api.iowen.cn/favicon/${url.hostname}.png`;
}
} catch {
// 忽略解析错误
}
}
return undefined;
}
/** 提取 GitHub 仓库信息 */
function extractGitHubRepo (url?: string): { owner: string; repo: string; } | null {
if (!url) return null;
try {
const urlObj = new URL(url);
if (urlObj.hostname === 'github.com' || urlObj.hostname === 'www.github.com') {
const parts = urlObj.pathname.split('/').filter(Boolean);
if (parts.length >= 2) {
return { owner: parts[0], repo: parts[1] };
}
}
} catch {
// 忽略解析错误
}
return null;
}
/** 从 GitHub API 获取 README */
async function fetchGitHubReadme (owner: string, repo: string): Promise<string> {
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/readme`, {
headers: {
Accept: 'application/vnd.github.v3.raw',
},
});
if (!response.ok) {
throw new Error('Failed to fetch README');
}
return response.text();
}
/** 清理 README 中的 HTML 标签,保留 Markdown */
function cleanReadmeHtml (content: string): string {
// 移除 HTML 注释
let cleaned = content.replace(/<!--[\s\S]*?-->/g, '');
// 保留常见的 Markdown 友好的 HTML 标签(img, br),其他的移除标签但保留内容
// 移除 style 和 script 标签及其内容
cleaned = cleaned.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
cleaned = cleaned.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// 将其他 HTML 标签替换为空格或换行(保留内容)
// 保留 img 标签(转为 markdown)- 尝试提取 alt 和 src 属性
cleaned = cleaned.replace(/<img[^>]*\\bsrc=["']([^"']+)["'][^>]*\\balt=["']([^"']+)["'][^>]*>/gi, '![$2]($1)');
cleaned = cleaned.replace(/<img[^>]*\\balt=["']([^"']+)["'][^>]*\\bsrc=["']([^"']+)["'][^>]*>/gi, '![$1]($2)');
cleaned = cleaned.replace(/<img[^>]+src=["']([^"']+)["'][^>]*>/gi, '![]($1)');
// 移除其他 HTML 标签,但保留内容
cleaned = cleaned.replace(/<\/?[^>]+(>|$)/g, '');
// 清理多余的空行(超过2个连续换行)
cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
return cleaned.trim();
}
export default function PluginDetailModal ({
isOpen,
onClose,
plugin,
installStatus = 'not-installed',
installedVersion,
onInstall,
}: PluginDetailModalProps) {
const [readme, setReadme] = useState<string>('');
const [readmeLoading, setReadmeLoading] = useState(false);
const [readmeError, setReadmeError] = useState(false);
// 获取 GitHub 仓库信息(需要在 hooks 之前计算)
const githubRepo = plugin ? extractGitHubRepo(plugin.homepage) : null;
// 当模态框打开且有 GitHub 链接时,获取 README
useEffect(() => {
if (!isOpen || !githubRepo) {
setReadme('');
setReadmeError(false);
return;
}
const loadReadme = async () => {
setReadmeLoading(true);
setReadmeError(false);
try {
const content = await fetchGitHubReadme(githubRepo.owner, githubRepo.repo);
// 清理 HTML 标签后再设置
setReadme(cleanReadmeHtml(content));
} catch (error) {
console.error('Failed to fetch README:', error);
setReadmeError(true);
} finally {
setReadmeLoading(false);
}
};
loadReadme();
}, [isOpen, githubRepo?.owner, githubRepo?.repo]);
if (!plugin) return null;
const { name, version, author, description, tags, homepage, downloadUrl, minVersion } = plugin;
const avatarUrl = getAuthorAvatar(homepage, downloadUrl) || `https://avatar.vercel.sh/${encodeURIComponent(name)}`;
return (
<Modal
isOpen={isOpen}
onClose={onClose}
size='4xl'
scrollBehavior='inside'
classNames={{
backdrop: 'z-[200]',
wrapper: 'z-[200]',
}}
>
<ModalContent>
{(onModalClose) => (
<>
<ModalHeader className='flex flex-col gap-3 pb-2'>
{/* 插件头部信息 */}
<div className='flex items-start gap-4'>
<Avatar
src={avatarUrl}
name={author || '?'}
size='lg'
isBordered
color='primary'
radius='lg'
className='flex-shrink-0'
/>
<div className='flex-1 min-w-0'>
<div className='flex items-center gap-2'>
<h2 className='text-2xl font-bold text-default-900'>{name}</h2>
{homepage && (
<Tooltip content='访问项目主页'>
<Button
isIconOnly
size='sm'
variant='flat'
color='primary'
as='a'
href={homepage}
target='_blank'
rel='noreferrer'
>
<IoMdOpen size={18} />
</Button>
</Tooltip>
)}
</div>
<p className='text-sm text-default-500 mt-1'>
by <span className='font-medium'>{author || '未知作者'}</span>
</p>
{/* 标签和版本信息 */}
<div className='flex items-center gap-2 mt-2 flex-wrap'>
<Chip size='sm' color='primary' variant='flat'>
v{version}
</Chip>
{tags?.map((tag) => (
<Chip
key={tag}
size='sm'
variant='flat'
className='bg-default-100 text-default-600'
>
{tag}
</Chip>
))}
{installStatus === 'update-available' && installedVersion && (
<Chip
size='sm'
color='warning'
variant='shadow'
className='animate-pulse'
>
可更新
</Chip>
)}
{installStatus === 'installed' && (
<Chip
size='sm'
color='success'
variant='flat'
startContent={<IoMdCheckmarkCircle size={14} />}
>
已安装
</Chip>
)}
</div>
</div>
</div>
</ModalHeader>
<ModalBody className='gap-4'>
{/* 插件描述 */}
<div>
<h3 className='text-sm font-semibold text-default-700 mb-2'>插件描述</h3>
<p className='text-sm text-default-600 leading-relaxed'>
{description || '暂无描述'}
</p>
</div>
{/* 插件信息 */}
<div>
<h3 className='text-sm font-semibold text-default-700 mb-3'>插件信息</h3>
<div className='grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm'>
<div className='flex justify-between items-center'>
<span className='text-default-500'>最新版本:</span>
<span className='font-medium text-default-900'>v{version}</span>
</div>
{installedVersion && (
<div className='flex justify-between items-center'>
<span className='text-default-500'>已安装版本:</span>
<span className='font-medium text-default-900'>v{installedVersion}</span>
</div>
)}
{minVersion && (
<div className='flex justify-between items-center'>
<span className='text-default-500'>最低要求版本:</span>
<span className='font-medium text-default-900'>v{minVersion}</span>
</div>
)}
<div className='flex justify-between items-center'>
<span className='text-default-500'>插件 ID:</span>
<span className='font-mono text-xs text-default-900'>{plugin.id}</span>
</div>
{downloadUrl && (
<div className='flex justify-between items-center'>
<span className='text-default-500'>下载地址:</span>
<Button
size='sm'
variant='flat'
color='primary'
as='a'
href={downloadUrl}
target='_blank'
rel='noreferrer'
startContent={<IoMdDownload size={14} />}
>
下载插件
</Button>
</div>
)}
</div>
</div>
{/* GitHub README 显示 */}
{githubRepo && (
<>
<div className='mt-2'>
<h3 className='text-sm font-semibold text-default-700 mb-3'>详情</h3>
{readmeLoading && (
<div className='flex justify-center items-center py-12'>
<Spinner size='lg' />
</div>
)}
{readmeError && (
<div className='text-center py-8'>
<p className='text-sm text-default-500 mb-3'>
无法加载 README
</p>
<Button
color='primary'
variant='flat'
as='a'
href={homepage}
target='_blank'
rel='noreferrer'
startContent={<IoMdOpen />}
>
在 GitHub 查看
</Button>
</div>
)}
{!readmeLoading && !readmeError && readme && (
<div className='rounded-lg border border-default-200 p-4 bg-default-50'>
<TailwindMarkdown content={readme} />
</div>
)}
</div>
</>
)}
</ModalBody>
<ModalFooter>
<Button variant='light' onPress={onModalClose}>
关闭
</Button>
{installStatus === 'installed'
? (
<Button
color='success'
variant='flat'
startContent={<IoMdCheckmarkCircle size={18} />}
isDisabled
>
已安装
</Button>
)
: installStatus === 'update-available'
? (
<Button
color='warning'
variant='shadow'
startContent={<MdUpdate size={18} />}
onPress={() => {
onInstall?.();
onModalClose();
}}
>
更新到 v{version}
</Button>
)
: (
<Button
color='primary'
variant='shadow'
startContent={<IoMdDownload size={18} />}
onPress={() => {
onInstall?.();
onModalClose();
}}
>
立即安装
</Button>
)}
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
);
}
@@ -1,19 +1,20 @@
import { Button } from '@heroui/button';
import { Input } from '@heroui/input';
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 { useEffect, useMemo, useState, useRef } from 'react';
import toast from 'react-hot-toast';
import { IoMdRefresh, IoMdSearch, IoMdSettings } from 'react-icons/io';
import clsx from 'clsx';
import { EventSourcePolyfill } from 'event-source-polyfill';
import { useLocalStorage } from '@uidotdev/usehooks';
import { useSearchParams } from 'react-router-dom';
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 PluginDetailModal from '@/pages/dashboard/plugin_detail_modal';
import { PluginStoreItem } from '@/types/plugin-store';
import useDialog from '@/hooks/use-dialog';
import key from '@/const/key';
@@ -42,6 +43,35 @@ export default function PluginStorePage () {
const [activeTab, setActiveTab] = useState<string>('all');
const [pluginManagerNotFound, setPluginManagerNotFound] = useState(false);
const dialog = useDialog();
const searchInputRef = useRef<HTMLInputElement>(null);
const [searchParams, setSearchParams] = useSearchParams();
// 快捷键支持: Ctrl+F 聚焦搜索框
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
e.preventDefault();
searchInputRef.current?.focus();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
// 进度条相关状态
const [installProgress, setInstallProgress] = useState<{
show: boolean;
message: string;
progress: number;
speedStr?: string;
eta?: number;
downloadedStr?: string;
totalStr?: string;
}>({
show: false,
message: '',
progress: 0,
});
// 商店列表源相关状态
const [storeSourceModalOpen, setStoreSourceModalOpen] = useState(false);
@@ -52,6 +82,10 @@ export default function PluginStorePage () {
const [pendingInstallPlugin, setPendingInstallPlugin] = useState<PluginStoreItem | null>(null);
const [selectedDownloadMirror, setSelectedDownloadMirror] = useState<string | undefined>(undefined);
// 插件详情弹窗状态
const [detailModalOpen, setDetailModalOpen] = useState(false);
const [selectedPlugin, setSelectedPlugin] = useState<PluginStoreItem | null>(null);
const loadPlugins = async (forceRefresh: boolean = false) => {
setLoading(true);
try {
@@ -73,6 +107,22 @@ export default function PluginStorePage () {
loadPlugins();
}, [currentStoreSource]);
// 处理 URL 参数中的插件 ID,自动打开详情
useEffect(() => {
const pluginId = searchParams.get('pluginId');
if (pluginId && plugins.length > 0 && !detailModalOpen) {
// 查找对应的插件
const targetPlugin = plugins.find(p => p.id === pluginId);
if (targetPlugin) {
setSelectedPlugin(targetPlugin);
setDetailModalOpen(true);
// 移除 URL 参数(可选)
// searchParams.delete('pluginId');
// setSearchParams(searchParams);
}
}
}, [plugins, searchParams, detailModalOpen]);
// 按标签分类和搜索
const categorizedPlugins = useMemo(() => {
let filtered = plugins;
@@ -103,7 +153,8 @@ export default function PluginStorePage () {
// 获取插件的安装状态和已安装版本
const getPluginInstallInfo = (plugin: PluginStoreItem): { status: InstallStatus; installedVersion?: string; } => {
// 通过 id (包名) 或 name 匹配已安装的插件
const installed = installedPlugins.find(p => p.id === plugin.id);
// 优先匹配 ID,如果 ID 匹配失败尝试匹配名称(兼容某些 ID 不一致的情况)
const installed = installedPlugins.find(p => p.id === plugin.id || p.name === plugin.name);
if (!installed) {
return { status: 'not-installed' };
@@ -167,9 +218,11 @@ export default function PluginStorePage () {
if (data.error) {
toast.error(`安装失败: ${data.error}`, { id: loadingToast });
setInstallProgress(prev => ({ ...prev, show: false }));
eventSource.close();
} else if (data.success) {
toast.success('插件安装成功!', { id: loadingToast });
setInstallProgress(prev => ({ ...prev, show: false }));
eventSource.close();
// 刷新插件列表
loadPlugins();
@@ -178,30 +231,46 @@ export default function PluginStorePage () {
dialog.confirm({
title: '插件管理器未加载',
content: (
<div className="space-y-2">
<p className="text-sm text-default-600">
<div className='space-y-2'>
<p className='text-sm text-default-600'>
插件已安装成功,但插件管理器尚未加载。
</p>
<p className="text-sm text-default-600">
<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);
}
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 });
if (typeof data.progress === 'number' && data.progress >= 0 && data.progress <= 100) {
setInstallProgress((prev) => ({
...prev,
show: true,
message: data.message,
progress: data.progress,
// 保存下载详情,避免被后续非下载步骤的消息清空
speedStr: data.speedStr || (data.message.includes('下载') ? prev.speedStr : undefined),
eta: data.eta !== undefined ? data.eta : (data.message.includes('下载') ? prev.eta : undefined),
downloadedStr: data.downloadedStr || (data.message.includes('下载') ? prev.downloadedStr : undefined),
totalStr: data.totalStr || (data.message.includes('下载') ? prev.totalStr : undefined),
}));
} else {
toast.loading(data.message, { id: loadingToast });
}
}
} catch (e) {
console.error('Failed to parse SSE message:', e);
@@ -211,6 +280,7 @@ export default function PluginStorePage () {
eventSource.onerror = (error) => {
console.error('SSE连接出错:', error);
toast.error('连接中断,安装失败', { id: loadingToast });
setInstallProgress(prev => ({ ...prev, show: false }));
eventSource.close();
};
} catch (error: any) {
@@ -233,67 +303,72 @@ export default function PluginStorePage () {
return (
<>
<title>插件商店 - NapCat WebUI</title>
<div className="p-2 md:p-4 relative">
<div className='p-2 md:p-4 relative'>
{/* 固定头部区域 */}
<div className={clsx(
'sticky top-14 z-10 backdrop-blur-sm py-4 px-4 rounded-sm mb-4 -mx-2 md:-mx-4 -mt-2 md:-mt-4 transition-colors',
'sticky top-14 z-10 backdrop-blur-md py-4 px-4 rounded-sm mb-4 -mx-2 md:-mx-4 -mt-2 md:-mt-4 transition-colors',
hasBackground
? 'bg-white/20 dark:bg-black/10'
: 'bg-transparent'
)}>
{/* 头部 */}
<div className="flex mb-4 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(true)}
isLoading={loading}
>
<IoMdRefresh size={24} />
</Button>
)}
>
{/* 头部布局:标题 + 搜索 + 工具栏 */}
<div className='flex flex-col md:flex-row mb-4 items-start md:items-center justify-between gap-4'>
<div className='flex items-center gap-3 flex-shrink-0'>
<h1 className='text-2xl font-bold'>插件商店</h1>
<Tooltip content='刷新列表'>
<Button
isIconOnly
size='sm'
variant='flat'
className='bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md'
radius='full'
onPress={() => loadPlugins(true)}
isLoading={loading}
>
<IoMdRefresh size={20} />
</Button>
</Tooltip>
</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>
{/* 顶栏搜索框与列表源 */}
<div className='flex items-center gap-3 w-full md:w-auto flex-1 justify-end'>
<Input
ref={searchInputRef}
placeholder='搜索(Ctrl+F)...'
startContent={<IoMdSearch className='text-default-400' />}
value={searchQuery}
onValueChange={setSearchQuery}
className='max-w-xs w-full'
size='sm'
isClearable
classNames={{
inputWrapper: 'bg-default-100/50 dark:bg-black/20 backdrop-blur-md border-white/20 dark:border-white/10',
}}
/>
{/* 搜索框 */}
<div className="mb-4">
<Input
placeholder="搜索插件名称、描述、作者或标签..."
startContent={<IoMdSearch className="text-default-400" />}
value={searchQuery}
onValueChange={setSearchQuery}
className="max-w-md"
/>
{/* 商店列表源简易卡片 */}
<div className='hidden sm:flex items-center gap-2 bg-default-100/50 backdrop-blur-md px-3 py-1.5 rounded-full border border-white/20 dark:border-white/10'>
<span className='text-xs text-default-500 whitespace-nowrap'>源: {getStoreSourceDisplayName()}</span>
<Tooltip content='切换列表源'>
<Button
isIconOnly
size='sm'
variant='light'
className='min-w-unit-6 w-6 h-6'
onPress={() => setStoreSourceModalOpen(true)}
>
<IoMdSettings size={14} />
</Button>
</Tooltip>
</div>
</div>
</div>
{/* 标签页导航 */}
<Tabs
aria-label="Plugin Store Categories"
className="max-w-full"
aria-label='Plugin Store Categories'
className='max-w-full'
selectedKey={activeTab}
onSelectionChange={(key) => setActiveTab(String(key))}
classNames={{
@@ -312,16 +387,16 @@ export default function PluginStorePage () {
</div>
{/* 插件列表区域 */}
<div className="relative">
<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">
<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>
)}
<EmptySection isEmpty={!categorizedPlugins[activeTab]?.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">
<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-4'>
{categorizedPlugins[activeTab]?.map((plugin) => {
const installInfo = getPluginInstallInfo(plugin);
return (
@@ -330,7 +405,11 @@ export default function PluginStorePage () {
data={plugin}
installStatus={installInfo.status}
installedVersion={installInfo.installedVersion}
onInstall={() => handleInstall(plugin)}
onInstall={() => { handleInstall(plugin); }}
onViewDetail={() => {
setSelectedPlugin(plugin);
setDetailModalOpen(true);
}}
/>
);
})}
@@ -346,7 +425,7 @@ export default function PluginStorePage () {
setCurrentStoreSource(mirror);
}}
currentMirror={currentStoreSource}
type="raw"
type='raw'
/>
{/* 下载镜像选择弹窗 */}
@@ -366,8 +445,87 @@ export default function PluginStorePage () {
}
}}
currentMirror={selectedDownloadMirror}
type="file"
type='file'
/>
{/* 插件详情弹窗 */}
<PluginDetailModal
isOpen={detailModalOpen}
onClose={() => {
setDetailModalOpen(false);
setSelectedPlugin(null);
// 清除 URL 参数
if (searchParams.has('pluginId')) {
searchParams.delete('pluginId');
setSearchParams(searchParams);
}
}}
plugin={selectedPlugin}
installStatus={selectedPlugin ? getPluginInstallInfo(selectedPlugin).status : 'not-installed'}
installedVersion={selectedPlugin ? getPluginInstallInfo(selectedPlugin).installedVersion : undefined}
onInstall={() => {
if (selectedPlugin) {
handleInstall(selectedPlugin);
}
}}
/>
{/* 插件下载进度条全局居中样式 */}
{installProgress.show && (
<div className='fixed inset-0 flex items-center justify-center z-[9999] animate-in fade-in duration-300'>
{/* 毛玻璃背景层 */}
<div className='absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md' />
<div
className={clsx(
'relative w-[90%] max-w-md bg-white/80 dark:bg-black/70 backdrop-blur-2xl shadow-2xl rounded-2xl border border-white/20 dark:border-white/10 p-8',
'ring-1 ring-black/5 dark:ring-white/5 flex flex-col gap-6'
)}
>
<div className='flex flex-col gap-1'>
<h3 className='text-lg font-bold text-default-900'>安装插件</h3>
<p className='text-sm text-default-500 font-medium'>{installProgress.message}</p>
</div>
<div className='flex flex-col gap-4'>
{/* 速度 & 百分比 */}
<div className='flex items-center justify-between'>
<div className='flex flex-col gap-0.5'>
{installProgress.speedStr && (
<p className='text-xs text-primary font-bold'>
{installProgress.speedStr}
</p>
)}
{installProgress.eta !== undefined && installProgress.eta !== null && (
<p className='text-xs text-default-400'>
剩余时间: {
installProgress.eta > 0
? (installProgress.eta < 60 ? `${installProgress.eta}s` : `${Math.floor(installProgress.eta / 60)}m ${installProgress.eta % 60}s`)
: '计算中...'
}
</p>
)}
</div>
<span className='text-2xl font-black text-primary font-mono'>{Math.round(installProgress.progress)}%</span>
</div>
{/* 进度条 */}
<div className='w-full bg-default-200/50 dark:bg-default-100/20 rounded-full h-4 overflow-hidden border border-default-300/20 dark:border-white/5'>
<div
className='bg-primary h-full rounded-full transition-all duration-500 ease-out shadow-[0_0_15px_rgba(var(--heroui-primary),0.6)]'
style={{ width: `${installProgress.progress}%` }}
/>
</div>
{/* 详细数据 (大小) - 始终显示 */}
<div className='flex items-center justify-between text-xs text-default-400 font-bold tracking-tight'>
<span>已下载 {installProgress.downloadedStr || '0.0MB'}</span>
<span>总计 {installProgress.totalStr || '获取中...'}</span>
</div>
</div>
</div>
</div>
)}
</>
);
}
@@ -6,8 +6,11 @@ import { useEffect, useRef, useState } from 'react';
import { toast } from 'react-hot-toast';
import { useNavigate } from 'react-router-dom';
import CryptoJS from 'crypto-js';
import { MdSettings } from 'react-icons/md';
import logo from '@/assets/images/logo.png';
import GUIDManager from '@/components/guid_manager';
import Modal from '@/components/modal';
import HoverEffectCard from '@/components/effect_card';
import { title } from '@/components/primitives';
@@ -174,6 +177,8 @@ export default function QQLoginPage () {
}
};
const [showGUIDManager, setShowGUIDManager] = useState(false);
useEffect(() => {
const timer = setInterval(() => {
onUpdateQrCode();
@@ -210,7 +215,12 @@ export default function QQLoginPage () {
</span>
</div>
</div>
<ThemeSwitch className='absolute right-4 top-4' />
<div className='absolute right-4 top-4 flex items-center gap-2'>
<Button isIconOnly variant="light" aria-label="Settings" onPress={() => setShowGUIDManager(true)}>
<MdSettings size={22} />
</Button>
<ThemeSwitch />
</div>
</CardHeader>
<CardBody className='flex gap-5 p-10 pt-0'>
@@ -266,6 +276,15 @@ export default function QQLoginPage () {
</HoverEffectCard>
</motion.div>
</PureLayout>
{showGUIDManager && (
<Modal
title='设备 GUID 管理'
content={<GUIDManager compact showRestart />}
size='lg'
hideFooter
onClose={() => setShowGUIDManager(false)}
/>
)}
</>
);
}
+9
View File
@@ -128,6 +128,12 @@ importers:
specifier: ^22.0.1
version: 22.19.1
packages/napcat-dpapi:
devDependencies:
'@types/node':
specifier: ^22.0.1
version: 22.19.1
packages/napcat-framework:
dependencies:
napcat-adapter:
@@ -441,6 +447,9 @@ importers:
napcat-common:
specifier: workspace:*
version: link:../napcat-common
napcat-dpapi:
specifier: workspace:*
version: link:../napcat-dpapi
napcat-pty:
specifier: workspace:*
version: link:../napcat-pty