Compare commits

..

29 Commits

Author SHA1 Message Date
手瓜一十雪
6e8adad7ca Improve layout and styling of NewVersionTip component
Added flexbox classes to center the update tip, adjusted Chip component styles for better alignment, and set a minimum width. Spinner size and alignment were also refined for consistency.
2026-01-22 13:41:01 +08:00
手瓜一十雪
0f8584b8e1 Refine update check logic and UI styling
Updated the shell's named pipe connection logic to better handle environment variables. Improved the system info component's update notification UI for better alignment and spinner sizing.
2026-01-22 13:39:44 +08:00
时瑾
37f40a2635 feat: support msg_seq parameter in reply message construction (#1529)
* feat: support msg_seq parameter in reply message construction

- Add optional 'seq' parameter to OB11MessageReply for using msg_seq
- Prioritize seq over id for querying reply messages
- Maintain backward compatibility with existing id parameter
- Update type definitions across backend and frontend
- Update validation schemas for message nodes

close #1523

* Update debug button label in NetworkDisplayCard

Changed the button label from '关闭调试'/'开启调试' to '默认'/'调试' based on the debug state for improved clarity.

---------

Co-authored-by: 手瓜一十雪 <nanaeonn@outlook.com>
2026-01-22 13:20:32 +08:00
手瓜一十雪
1b4d604e32 Add support for preloading Node Addons via env var
Introduces logic to preload a Node Addon in the worker process if the NAPCAT_PRELOAD_NODE_ADDON_PATH environment variable is set. Logs success or failure of the preload operation for better debugging and flexibility.
2026-01-22 12:55:34 +08:00
手瓜一十雪
81a0c07922 Revert "Add manual trigger to auto-release workflow"
This reverts commit d25bd65b2d.
2026-01-22 12:53:52 +08:00
手瓜一十雪
a8cb6b5865 Revert "Add support for CJS environment loader in main entry"
This reverts commit 711a060dd9.
2026-01-22 12:53:11 +08:00
手瓜一十雪
d25bd65b2d Add manual trigger to auto-release workflow
Enables the auto-release workflow to be triggered manually using workflow_dispatch, in addition to running on published releases.
2026-01-22 12:13:14 +08:00
手瓜一十雪
e510a75f0c Add workflow to trigger NapCat AppImage release
Introduces a new GitHub Actions step to trigger the Release NapCat AppImage workflow. This step uses hardcoded QQ AppImage URLs for both x86_64 and arm64 architectures and passes the latest NapCat version as input.
2026-01-22 12:12:38 +08:00
吴天一
e3c6048a7f Rename OB11MessageContext to OB11MessageContact (#1540) 2026-01-22 12:06:59 +08:00
手瓜一十雪
789c72d4cf Trigger docker-publish workflow in auto-release
Added a POST request to dispatch the docker-publish workflow alongside the release workflow in the auto-release GitHub Actions workflow. This ensures both workflows are triggered with the same input parameters.

Fix indentation for curl command in workflow

Corrected the indentation of a curl command in the auto-release GitHub Actions workflow to ensure proper execution of the job steps.
2026-01-22 12:05:40 +08:00
手瓜一十雪
711a060dd9 Add support for CJS environment loader in main entry
Checks for the NAPCAT_NODE_CJS_ENV_LOADER_PATH environment variable and loads the specified CommonJS environment loader if present. Logs success or failure and exits on error. This allows for custom environment setup before continuing with the main process.
2026-01-22 11:58:13 +08:00
手瓜一十雪
6268923f01 Fix import path for connectToNamedPipe in base.ts
Some checks failed
Build NapCat Artifacts / Build-Framework (push) Has been cancelled
Build NapCat Artifacts / Build-Shell (push) Has been cancelled
Updated the import statement for connectToNamedPipe to use a relative path instead of an alias. This resolves issues with module resolution in the napcat-shell package.
2026-01-18 14:50:34 +08:00
手瓜一十雪
f6b9017429 Enable named pipe connection with multi-process check
Restores the named pipe connection in NCoreInitShell, now gated by both NAPCAT_DISABLE_PIPE and NAPCAT_DISABLE_MULTI_PROCESS environment variables. This ensures the pipe is only connected when multi-process is enabled.
2026-01-18 14:42:00 +08:00
手瓜一十雪
178e51bbb8 Reduce mirror timeouts and use fast mirror cache
Decreased default and test timeouts for mirrors to improve responsiveness. Updated logic in getAllGitHubTags and getWorkflowRunsFromHtml to use cached fast mirror lists instead of static lists for better performance.
2026-01-18 14:34:08 +08:00
手瓜一十雪
8a232d8c68 Support preferred WebUI port via environment variable
Some checks are pending
Build NapCat Artifacts / Build-Framework (push) Waiting to run
Build NapCat Artifacts / Build-Shell (push) Waiting to run
Adds support for specifying a preferred WebUI port using the NAPCAT_WEBUI_PREFERRED_PORT environment variable. The shell and backend now coordinate to pass and honor this port during worker restarts, falling back to the default port if the preferred one is unavailable.
2026-01-18 12:19:03 +08:00
手瓜一十雪
7216755430 Refactor process management and improve shutdown logic
Removed excessive logging and streamlined process restart and shutdown flows in napcat.ts. Added isShuttingDown flag to prevent unintended worker restarts during shutdown. Improved forceKillProcess to handle Windows-specific process termination. Updated IWorkerProcess interface and implementations to include the 'off' event method for better event management.
2026-01-18 12:10:14 +08:00
手瓜一十雪
0c91f9c66b Remove retry logic from tryUsePort function
Simplified the tryUsePort function by removing the retryCurrentCount parameter and associated retry logic. Now, if a port is in use, the function increments the port number and retries up to MAX_PORT_TRY times without waiting between attempts.
2026-01-18 11:45:40 +08:00
手瓜一十雪
e8855a59b0 Improve alignment in system info and status components
Adjusted flex alignment and added 'items-baseline' and 'self-center' classes to enhance vertical alignment of icons and content in SystemInfoItem and SystemStatusItem components for better UI consistency.
2026-01-18 11:25:06 +08:00
手瓜一十雪
5de2664af4 Support passing JWT secret key on worker restart
Added the ability to pass a JWT secret key when restarting the worker process by updating environment variable handling and message passing. Improved port retry logic in the backend to allow multiple attempts on the same port before incrementing. Also refactored process API to use getter for pid property.

Ensure Electron app is ready before creating process manager

Adds a check to await electron.app.whenReady() if the Electron app is not yet ready before instantiating the ElectronProcessManager. This prevents potential issues when accessing Electron APIs before the app is fully initialized.

Add mirror selection support for version updates

Introduces the ability to specify and select GitHub mirror sources for fetching tags, releases, and action artifacts throughout the backend and frontend. Updates API endpoints, internal helper functions, and UI components to allow users to choose a mirror for version queries and updates, improving reliability in regions with limited GitHub access. Also enhances version comparison logic and improves artifact metadata display.

Refactor artifact fetching to use HTML parsing only

Removed all GitHub API dependencies for fetching workflow runs and artifacts. Now, workflow runs are parsed directly from the HTML of the Actions page, and artifact URLs are constructed using nightly.link. Also added workflow title and mirror fields to ActionArtifact, and simplified mirror list without latency comments.
2026-01-18 11:13:08 +08:00
手瓜一十雪
5284e0ac5a Update OpenRouter model in release workflow
Some checks are pending
Build NapCat Artifacts / Build-Framework (push) Waiting to run
Build NapCat Artifacts / Build-Shell (push) Waiting to run
Changed the OPENROUTER_MODEL environment variable in the release workflow to use 'copilot/gemini-3-flash-preview' instead of 'copilot/ant/gemini-3-flash-preview'.
2026-01-17 18:57:42 +08:00
手瓜一十雪
67d6cd3f2e Refactor worker restart to control quick login param
Modified the restartWorker and startWorker functions to control whether the quick login parameter (-q/--qq) is passed to the worker process. On restart, quick login is not passed, while on unexpected exits, it is preserved. This improves process management and parameter handling during worker lifecycle events.
2026-01-17 18:56:53 +08:00
手瓜一十雪
0ba5862753 Pass CLI args to worker and update login script example
The quickLoginExample.bat script was updated to use the new launcher script names and argument format. In napcat.ts, the master process now forwards its command line arguments to the worker process, enabling better parameter handling.
2026-01-17 18:54:18 +08:00
手瓜一十雪
d4478275ee Add auto-restart for unexpected worker exits
Introduces an isRestarting flag to distinguish between intentional and unexpected worker restarts. If the worker process exits unexpectedly, the system now attempts to automatically restart it and logs relevant warnings and errors.
2026-01-17 18:38:12 +08:00
手瓜一十雪
163bb88751 Remove unused isFile variable in GetPluginListHandler
Cleaned up the GetPluginListHandler by removing the unused isFile variable, as it was no longer needed for plugin list processing.
2026-01-17 16:27:24 +08:00
手瓜一十雪
ec6762d916 Add plugin enable/disable config and status management
Introduces a persistent plugins.json config to track enabled/disabled status for plugins, updates the plugin manager to respect this config when loading plugins, and adds API and frontend support for toggling plugin status. The backend now reports plugin status as 'active', 'stopped', or 'disabled', and the frontend displays these states with appropriate labels. Also updates the built-in plugin package.json with author info.
2026-01-17 16:24:46 +08:00
手瓜一十雪
ed1872a349 Add plugin management to WebUI backend and frontend
Implemented backend API and router for plugin management (list, reload, enable/disable, uninstall) and exposed corresponding frontend controller and dashboard page. Updated navigation and site config to include plugin management. Refactored plugin manager adapter for public methods and improved plugin metadata handling.
2026-01-17 16:14:46 +08:00
手瓜一十雪
a7fd70ac3a Add napcat-plugin-builtin build step to CI workflows
Updated build and release GitHub Actions workflows to include a build step for napcat-plugin-builtin. This ensures the plugin is built alongside other packages during CI processes.
2026-01-17 15:50:20 +08:00
手瓜一十雪
7e38f1d227 Add builtin plugin package and enhance action map
Introduces the napcat-plugin-builtin package with initialization, message handling, and build configuration. Also adds a type-safe 'call' helper to the action map in napcat-onebot for improved action invocation.
2026-01-17 15:48:48 +08:00
时瑾
0ca68010a5 feat: 优化离线重连机制,支持通过前端实现重新登录
* feat: 优化离线重连机制,增加前端登录错误提示与二维码刷新功能

- 增加全局掉线检测弹窗
- 增强登录错误解析,支持显示 serverErrorCode 和 message
- 优化二维码登录 UI,错误时显示详细原因并提供大按钮重新获取
- 核心层解耦,通过事件抛出 KickedOffLine 通知
- 支持前端点击刷新二维码接口

* feat: 新增看门狗汪汪汪

* cp napcat-shell-loader/launcher-win.bat

* refactor: 重构重启流程,移除旧的重启逻辑,新增基于 WebUI 的重启请求处理

* fix: 刷新二维码清楚错误信息
2026-01-17 15:38:24 +08:00
39 changed files with 1790 additions and 637 deletions

View File

@@ -80,4 +80,17 @@ jobs:
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"

View File

@@ -41,6 +41,7 @@ jobs:
pnpm test || exit 1
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:framework
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-framework/dist framework-dist
cd framework-dist
npm install --omit=dev
@@ -83,6 +84,7 @@ jobs:
pnpm test || exit 1
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:shell
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-shell/dist shell-dist
cd shell-dist
npm install --omit=dev

View File

@@ -10,7 +10,7 @@ permissions: write-all
env:
OPENROUTER_API_URL: https://91vip.futureppo.top/v1/chat/completions
OPENROUTER_MODEL: "copilot/ant/gemini-3-flash-preview"
OPENROUTER_MODEL: "copilot/gemini-3-flash-preview"
RELEASE_NAME: "NapCat"
jobs:
@@ -62,6 +62,7 @@ jobs:
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:framework
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-framework/dist framework-dist
cd framework-dist
npm install --omit=dev
@@ -91,6 +92,7 @@ jobs:
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:shell
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-shell/dist shell-dist
cd shell-dist
npm install --omit=dev

View File

@@ -220,13 +220,13 @@ export function parseAppidFromMajor (nodeMajor: string): string | undefined {
// ============== GitHub Tags 获取 ==============
// 使用 mirror 模块统一管理镜像
export async function getAllTags (): Promise<{ tags: string[], mirror: string; }> {
return getAllTagsFromMirror('NapNeko', 'NapCatQQ');
export async function getAllTags (mirror?: string): Promise<{ tags: string[], mirror: string; }> {
return getAllTagsFromMirror('NapNeko', 'NapCatQQ', mirror);
}
export async function getLatestTag (): Promise<string> {
const { tags } = await getAllTags();
export async function getLatestTag (mirror?: string): Promise<string> {
const { tags } = await getAllTags(mirror);
// 使用 SemVer 规范排序
tags.sort((a, b) => compareSemVer(a, b));

View File

@@ -23,66 +23,50 @@ import { PromiseTimer } from './helper';
* 懒加载测速:首次使用时自动测速,缓存 30 分钟
*/
export const GITHUB_FILE_MIRRORS = [
// 延迟 < 800ms 的最快镜像
'https://github.chenc.dev/', // 666ms
'https://ghproxy.cfd/', // 719ms - 支持重定向
'https://github.tbedu.top/', // 760ms
'https://ghps.cc/', // 768ms
'https://gh.llkk.cc/', // 774ms
'https://ghproxy.cc/', // 777ms
'https://gh.monlor.com/', // 779ms
'https://cdn.akaere.online/', // 784ms
// 延迟 800-1000ms 的快速镜像
'https://gh.idayer.com/', // 869ms
'https://gh-proxy.net/', // 885ms
'https://ghpxy.hwinzniej.top/', // 890ms
'https://github-proxy.memory-echoes.cn/', // 896ms
'https://git.yylx.win/', // 917ms
'https://gitproxy.mrhjx.cn/', // 950ms
'https://jiashu.1win.eu.org/', // 954ms
'https://ghproxy.cn/', // 981ms
// 延迟 1000-1500ms 的中速镜像
'https://gh.fhjhy.top/', // 1014ms
'https://gp.zkitefly.eu.org/', // 1015ms
'https://gh-proxy.com/', // 1022ms
'https://hub.gitmirror.com/', // 1027ms
'https://ghfile.geekertao.top/', // 1029ms
'https://j.1lin.dpdns.org/', // 1037ms
'https://ghproxy.imciel.com/', // 1047ms
'https://github-proxy.teach-english.tech/', // 1047ms
'https://gh.927223.xyz/', // 1071ms
'https://github.ednovas.xyz/', // 1099ms
'https://ghf.xn--eqrr82bzpe.top/',// 1122ms
'https://gh.dpik.top/', // 1131ms
'https://gh.jasonzeng.dev/', // 1139ms
'https://gh.xxooo.cf/', // 1157ms
'https://gh.bugdey.us.kg/', // 1228ms
'https://ghm.078465.xyz/', // 1289ms
'https://j.1win.ggff.net/', // 1329ms
'https://tvv.tw/', // 1393ms
'https://gh.chjina.com/', // 1446ms
'https://gitproxy.127731.xyz/', // 1458ms
// 延迟 1500-2500ms 的较慢镜像
'https://gh.inkchills.cn/', // 1617ms
'https://ghproxy.cxkpro.top/', // 1651ms
'https://gh.sixyin.com/', // 1686ms
'https://github.geekery.cn/', // 1734ms
'https://git.669966.xyz/', // 1824ms
'https://gh.5050net.cn/', // 1858ms
'https://gh.felicity.ac.cn/', // 1903ms
'https://gh.ddlc.top/', // 2056ms
'https://cf.ghproxy.cc/', // 2058ms
'https://gitproxy.click/', // 2068ms
'https://github.dpik.top/', // 2313ms
'https://gh.zwnes.xyz/', // 2434ms
'https://ghp.keleyaa.com/', // 2440ms
'https://gh.wsmdn.dpdns.org/', // 2744ms
// 延迟 > 2500ms 的慢速镜像(作为备用)
'https://ghproxy.monkeyray.net/', // 3023ms
'https://fastgit.cc/', // 3369ms
'https://cdn.gh-proxy.com/', // 3394ms
'https://gh.catmak.name/', // 4119ms
'https://gh.noki.icu/', // 5990ms
'https://github.chenc.dev/',
'https://ghproxy.cfd/',
'https://github.tbedu.top/',
'https://ghproxy.cc/',
'https://gh.monlor.com/',
'https://cdn.akaere.online/',
'https://gh.idayer.com/',
'https://gh.llkk.cc/',
'https://ghpxy.hwinzniej.top/',
'https://github-proxy.memory-echoes.cn/',
'https://git.yylx.win/',
'https://gitproxy.mrhjx.cn/',
'https://gh.fhjhy.top/',
'https://gp.zkitefly.eu.org/',
'https://gh-proxy.com/',
'https://ghfile.geekertao.top/',
'https://j.1lin.dpdns.org/',
'https://ghproxy.imciel.com/',
'https://github-proxy.teach-english.tech/',
'https://gh.927223.xyz/',
'https://github.ednovas.xyz/',
'https://ghf.xn--eqrr82bzpe.top/',
'https://gh.dpik.top/',
'https://gh.jasonzeng.dev/',
'https://gh.xxooo.cf/',
'https://gh.bugdey.us.kg/',
'https://ghm.078465.xyz/',
'https://j.1win.ggff.net/',
'https://tvv.tw/',
'https://gitproxy.127731.xyz/',
'https://gh.inkchills.cn/',
'https://ghproxy.cxkpro.top/',
'https://gh.sixyin.com/',
'https://github.geekery.cn/',
'https://git.669966.xyz/',
'https://gh.5050net.cn/',
'https://gh.felicity.ac.cn/',
'https://github.dpik.top/',
'https://ghp.keleyaa.com/',
'https://gh.wsmdn.dpdns.org/',
'https://ghproxy.monkeyray.net/',
'https://fastgit.cc/',
'https://gh.catmak.name/',
'https://gh.noki.icu/',
'', // 原始 URL无镜像
];
@@ -109,7 +93,6 @@ export const GITHUB_RAW_MIRRORS = [
// 测试确认支持 raw 文件的镜像
'https://github.chenc.dev/https://raw.githubusercontent.com',
'https://ghproxy.cfd/https://raw.githubusercontent.com',
'https://gh.llkk.cc/https://raw.githubusercontent.com',
'https://ghproxy.cc/https://raw.githubusercontent.com',
'https://gh-proxy.net/https://raw.githubusercontent.com',
];
@@ -150,7 +133,7 @@ const defaultConfig: MirrorConfig = {
apiMirrors: GITHUB_API_MIRRORS,
rawMirrors: GITHUB_RAW_MIRRORS,
nightlyLinkMirrors: NIGHTLY_LINK_MIRRORS,
timeout: 10000, // 10秒超时,平衡速度和可靠性
timeout: 5000, // 5秒超时,平衡速度和可靠性
enabled: true,
customMirror: undefined,
};
@@ -274,7 +257,7 @@ export async function getFastMirrors (forceRefresh: boolean = false): Promise<st
async function performMirrorTest (): Promise<string[]> {
// 开始镜像测速
const timeout = 8000; // 测速超时 8
const timeout = 3000; // 测速超时 3
// 并行测试所有镜像
const mirrors = currentConfig.fileMirrors.filter(m => m);
@@ -585,7 +568,7 @@ export async function findAvailableDownloadUrl (
let testedCount = 0;
for (const mirror of mirrors) {
if (!mirror) continue; // 跳过空字符串
// 特殊处理 nightly.link URL
let mirrorUrl: string;
if (originalUrl.includes('nightly.link')) {
@@ -594,7 +577,7 @@ export async function findAvailableDownloadUrl (
} else {
mirrorUrl = buildMirrorUrl(originalUrl, mirror);
}
testedCount++;
if (await testWithValidation(mirrorUrl)) {
return mirrorUrl;
@@ -650,8 +633,15 @@ function compareSemVerSimple (a: string, b: string): number {
* 从 tags 列表中获取最新的 release tag
* 不依赖 GitHub API
*/
export async function getLatestReleaseTag (owner: string, repo: string): Promise<string> {
const result = await getAllGitHubTags(owner, repo);
// Update definitions validation locally first if possible.
// I'll assume valid typescript.
// I will split this into two tool calls to avoid complexity.
// 1. Update mirror.ts
// 2. Update UpdateNapCat.ts
// This tool call: Update mirror.ts
export async function getLatestReleaseTag (owner: string, repo: string, mirror?: string): Promise<string> {
const result = await getAllGitHubTags(owner, repo, mirror);
// 过滤出符合 semver 的 tags
const releaseTags = result.tags.filter(tag => SEMVER_REGEX.test(tag));
@@ -701,6 +691,8 @@ export async function getGitHubRelease (
assetNames?: string[];
/** 是否需要获取 changelog需要调用 API */
fetchChangelog?: boolean;
/** 指定镜像 */
mirror?: string;
} = {}
): Promise<{
tag_name: string;
@@ -710,15 +702,16 @@ export async function getGitHubRelease (
}>;
body?: string;
}> {
const { assetNames = [], fetchChangelog = false } = options;
const { assetNames = [], fetchChangelog = false, mirror } = options;
// 1. 获取实际的 tag 名称
let actualTag: string;
if (tag === 'latest') {
actualTag = await getLatestReleaseTag(owner, repo);
actualTag = await getLatestReleaseTag(owner, repo, mirror);
} else {
actualTag = tag;
}
// ...
// 2. 构建 assets 列表(不需要 API
const assets = assetNames.map(name => ({
@@ -782,8 +775,8 @@ const tagsCache: Map<string, TagsCache> = new Map();
* 获取所有 GitHub tags带缓存
* 优化:并行请求多个镜像,使用第一个成功返回的结果
*/
export async function getAllGitHubTags (owner: string, repo: string): Promise<{ tags: string[], mirror: string; }> {
const cacheKey = `${owner}/${repo}`;
export async function getAllGitHubTags (owner: string, repo: string, mirror?: string): Promise<{ tags: string[], mirror: string; }> {
const cacheKey = `${owner}/${repo}/${mirror || 'auto'}`;
// 检查缓存
const cached = tagsCache.get(cacheKey);
@@ -805,7 +798,7 @@ export async function getAllGitHubTags (owner: string, repo: string): Promise<{
};
// 尝试从 URL 获取 tags
const fetchFromUrl = async (url: string, mirror: string): Promise<{ tags: string[], mirror: string; } | null> => {
const fetchFromUrl = async (url: string, usedMirror: string): Promise<{ tags: string[], mirror: string; } | null> => {
try {
const raw = await PromiseTimer(
RequestUtil.HttpGetText(url),
@@ -813,79 +806,55 @@ export async function getAllGitHubTags (owner: string, repo: string): Promise<{
);
// 检查返回内容是否有效(不是 HTML 错误页面)
if (raw.includes('<!DOCTYPE') || raw.includes('<html')) {
return null;
if (raw.includes('refs/tags')) {
return { tags: parseTags(raw), mirror: usedMirror };
}
const tags = parseTags(raw);
if (tags.length > 0) {
return { tags, mirror };
}
return null;
} catch {
return null;
// 忽略错误
}
return null;
};
// 获取快速镜像列表
let fastMirrors: string[] = [];
try {
fastMirrors = await getFastMirrors();
} catch {
// 忽略错误
// 准备镜像列表
let mirrors: string[] = [];
if (mirror) {
// 如果指定了镜像,只使用该镜像
mirrors = [mirror];
} else {
// 否则使用 auto 逻辑,利用缓存的快速镜像列表
mirrors = await getFastMirrors();
}
// 构建 URL 列表(取前 5 个快速镜像 + 原始 URL 并行请求
const topMirrors = fastMirrors.slice(0, 5);
const mirrorUrls = [
{ url: baseUrl, mirror: 'github.com' }, // 原始 URL
...topMirrors.filter(m => m).map(m => ({ url: buildMirrorUrl(baseUrl, m), mirror: m })),
];
// 并行请求
const promises = mirrors.map(m => {
const url = m ? buildMirrorUrl(baseUrl, m) : baseUrl;
return fetchFromUrl(url, m || 'https://github.com');
});
// 并行请求所有镜像,使用 Promise.any 获取第一个成功的结果
try {
const result = await Promise.any(
mirrorUrls.map(async ({ url, mirror }) => {
const res = await fetchFromUrl(url, mirror);
if (res) return res;
throw new Error('Failed');
})
);
// 缓存结果
tagsCache.set(cacheKey, { tags: result.tags, mirror: result.mirror, timestamp: Date.now() });
return result;
} catch {
// Promise.any 全部失败,回退到顺序尝试剩余镜像
}
// 回退:顺序尝试剩余镜像
const remainingMirrors = fastMirrors.slice(5).filter(m => m);
for (const mirror of remainingMirrors) {
const url = buildMirrorUrl(baseUrl, mirror);
const result = await fetchFromUrl(url, mirror);
const result = await Promise.any(promises.filter(p => p !== null) as Promise<{ tags: string[], mirror: string; } | null>[]);
if (result) {
tagsCache.set(cacheKey, { tags: result.tags, mirror: result.mirror, timestamp: Date.now() });
tagsCache.set(cacheKey, {
tags: result.tags,
mirror: result.mirror,
timestamp: Date.now(),
});
return result;
}
} catch {
// all failed
}
// 最后尝试所有镜像
const allMirrors = currentConfig.fileMirrors.filter(m => m && !fastMirrors.includes(m));
for (const mirror of allMirrors) {
const url = buildMirrorUrl(baseUrl, mirror);
const result = await fetchFromUrl(url, mirror);
if (result) {
tagsCache.set(cacheKey, { tags: result.tags, mirror: result.mirror, timestamp: Date.now() });
return result;
}
if (mirror) {
throw new Error(`指定镜像 ${mirror} 获取 tags 失败`);
}
throw new Error('无法获取 tags所有源都不可用');
throw new Error('无法获取 tags所有镜像源都不可用');
}
// ============== Action Artifacts 支持 ==============
// ActionArtifact 接口定义
export interface ActionArtifact {
id: number;
name: string;
@@ -895,12 +864,14 @@ export interface ActionArtifact {
archive_download_url: string;
workflow_run_id?: number;
head_sha?: string;
workflow_title?: string;
}
// ============== Action Artifacts 缓存 ==============
interface ArtifactsCache {
artifacts: ActionArtifact[];
mirror: string;
timestamp: number;
}
@@ -920,68 +891,116 @@ export function clearArtifactsCache (): void {
* 当 api.github.com 不可用时使用
* 页面格式: https://github.com/{owner}/{repo}/actions/workflows/{workflow}
*/
async function getWorkflowRunsFromHtml (
owner: string,
repo: string,
workflow: string = 'build.yml',
maxRuns: number = 10
): Promise<Array<{ id: number; created_at: string; }>> {
maxRuns: number = 10,
mirror?: string
): Promise<{ runs: Array<{ id: number; created_at: string; title: string; }>; mirror: string; }> {
const baseUrl = `https://github.com/${owner}/${repo}/actions/workflows/${workflow}`;
// 尝试使用镜像获取 HTML
const mirrors = ['', ...currentConfig.fileMirrors.filter(m => m)];
for (const mirror of mirrors) {
// 如果指定了 mirror则只使用该 mirror
let mirrors: string[] = [];
if (mirror) {
mirrors = [mirror];
} else {
// 使用缓存的快速镜像列表
mirrors = await getFastMirrors();
}
for (const mirrorItem of mirrors) {
try {
const url = mirror ? buildMirrorUrl(baseUrl, mirror) : baseUrl;
const html = await PromiseTimer(
RequestUtil.HttpGetText(url),
10000
);
// 从 HTML 中提取 run IDs 和时间
// 格式: href="/NapNeko/NapCatQQ/actions/runs/20676123968"
// 时间格式: <relative-time datetime="2026-01-03T10:37:29Z"
const runPattern = new RegExp(`href="/${owner}/${repo}/actions/runs/(\\d+)"`, 'gi');
const timePattern = /<relative-time\s+datetime="([^"]+)"/gi;
// 提取所有时间
const times: string[] = [];
let timeMatch;
while ((timeMatch = timePattern.exec(html)) !== null) {
times.push(timeMatch[1]);
}
const runs: Array<{ id: number; created_at: string; }> = [];
const allRuns: Array<{ id: number; created_at: string; title: string; }> = [];
const foundIds = new Set<number>();
let timeIndex = 0;
let match;
while ((match = runPattern.exec(html)) !== null && runs.length < maxRuns) {
const id = parseInt(match[1]);
if (!foundIds.has(id)) {
foundIds.add(id);
// 尝试获取对应的时间,每个 run 通常有两个时间(桌面和移动端显示)
// 所以每找到一个 run跳过两个时间
const created_at = times[timeIndex] || new Date().toISOString();
timeIndex += 2; // 跳过两个时间(桌面端和移动端各一个)
runs.push({
id,
created_at,
});
let page = 1;
const maxPages = 10; // 防止无限请求最多翻10页约250个条目
while (allRuns.length < maxRuns && page <= maxPages) {
const pageUrl = page > 1 ? `${baseUrl}?page=${page}` : baseUrl;
const url = mirrorItem ? buildMirrorUrl(pageUrl, mirrorItem) : pageUrl;
const html = await PromiseTimer(
RequestUtil.HttpGetText(url),
10000
);
// 使用 Block 分割策略,更稳健地关联 ID 和时间
const rows = html.split('<div class="Box-row');
let foundOnThisPage = 0;
for (const row of rows) {
// 提取 Run ID 和 Status
// <a href="/NapNeko/NapCatQQ/actions/runs/20799940346" ... aria-label="completed successfully: ...">
const runMatch = new RegExp(`href="/${owner}/${repo}/actions/runs/(\\d+)"[^>]*aria-label="([^"]*)"`, 'i').exec(row);
if (!runMatch || !runMatch[1] || !runMatch[2]) continue;
const id = parseInt(runMatch[1]);
const ariaLabel = runMatch[2];
const ariaLabelLower = ariaLabel.toLowerCase();
// 只需要判断 completed
if (ariaLabelLower.includes('completed')) {
if (!foundIds.has(id)) {
// 提取时间 (取 Block 内的第一个 relative-time)
const timeMatch = /<relative-time\s+datetime="([^"]+)"/.exec(row);
if (timeMatch && timeMatch[1]) {
foundIds.add(id);
foundOnThisPage++;
// 优先从 markdown-title class 提取标题
let title = '';
const titleMatch = /class="[^"]*markdown-title[^"]*"[^>]*>([\s\S]*?)<\/span>/i.exec(row);
if (titleMatch && titleMatch[1]) {
title = titleMatch[1].trim();
}
// 如果没找到,回退到 aria-label 逻辑
if (!title) {
title = ariaLabel;
const prefixMatch = /^(completed successfully:\s*)/i.exec(title);
if (prefixMatch) {
title = title.substring(prefixMatch[0].length);
}
}
allRuns.push({
id,
created_at: timeMatch[1],
title: title.trim()
});
}
}
}
}
// 如果本页没有找到任何 completed 的 run但页面可能不为空或者页面内容太少可能是最后一页或错误
// 这里简化判断: 如果本页没提取到任何有效数据,就认为没有更多数据了
if (foundOnThisPage === 0) {
// 也要考虑到可能是页面解析失败或者全是 failed 状态
// 检查是否有翻页按钮可能更复杂,暂时假设如果一整页都没有 successful run可能后面也没有了或者我们已经获取够多了
// 为了稳健,如果本页没找到,且 allRuns 还没满,尝试下一页 (除非页面很小说明是空页)
if (rows.length < 2) { // 只有 split 的第一个空元素
break;
}
}
// 分页逻辑:总是尝试下一页,直到满足 maxRuns
page++;
}
if (runs.length > 0) {
return runs;
if (allRuns.length > 0) {
return { runs: allRuns, mirror: mirrorItem || 'https://github.com' };
}
} catch {
continue;
}
}
return [];
return { runs: [], mirror: '' };
}
/**
@@ -996,122 +1015,49 @@ async function getArtifactsFromNightlyLink (
owner: string,
repo: string,
workflow: string = 'build.yml',
branch: string = 'main',
maxRuns: number = 10
): Promise<ActionArtifact[]> {
let workflowRuns: Array<{ id: number; head_sha?: string; created_at: string; }> = [];
// 策略1: 优先尝试 GitHub API
_branch: string = 'main',
maxRuns: number = 10,
mirror?: string
): Promise<{ artifacts: ActionArtifact[], mirror: string; }> {
// 策略: 优先使用 nightly.link更稳定无需认证+ HTML 解析
try {
const endpoint = `https://api.github.com/repos/${owner}/${repo}/actions/workflows/${workflow}/runs?branch=${branch}&status=success&per_page=${maxRuns}`;
const runsResponse = await PromiseTimer(
RequestUtil.HttpGetJson<{
workflow_runs: Array<{ id: number; head_sha: string; created_at: string; }>;
}>(endpoint, 'GET', undefined, {
'User-Agent': 'NapCat',
'Accept': 'application/vnd.github.v3+json',
}),
10000
);
// 以前尝试使用 GitHub API现在弃用完全使用 HTML 解析逻辑
// 并获取 workflow // 直接从 HTML 页面解析
const { runs: workflowRuns, mirror: runsMirror } = await getWorkflowRunsFromHtml(owner, repo, workflow, maxRuns, mirror);
if (runsResponse.workflow_runs && runsResponse.workflow_runs.length > 0) {
workflowRuns = runsResponse.workflow_runs;
if (workflowRuns.length === 0) {
return { artifacts: [], mirror: runsMirror };
}
} catch {
// API 请求失败,继续尝试 HTML 解析
}
// 策略2: API 失败时,从 HTML 页面解析
if (workflowRuns.length === 0) {
workflowRuns = await getWorkflowRunsFromHtml(owner, repo, workflow, maxRuns);
}
// 直接拼接 nightly.link URL
// 格式: https://nightly.link/{owner}/{repo}/actions/runs/{run_id}/{artifact_name}.zip
const artifacts: ActionArtifact[] = [];
const artifactNames = ['NapCat.Framework', 'NapCat.Shell']; // 已知的 artifact 名称
if (workflowRuns.length === 0) {
return [];
}
// 如果 HTML 解析使用的 mirror 是 github.com则 nightly.link 使用默认配置
// 如果使用了镜像,可能需要特殊的 nightly.link 镜像,或者这里仅记录 HTML 来源镜像
// 实际上 nightly.link 本身就是一个服务,我们使用配置中的 nightlyLinkMirrors
const baseNightlyMirror = currentConfig.nightlyLinkMirrors[0] || 'https://nightly.link';
// 直接拼接 nightly.link URL
// 格式: https://nightly.link/{owner}/{repo}/actions/runs/{run_id}/{artifact_name}.zip
const artifacts: ActionArtifact[] = [];
const artifactNames = ['NapCat.Framework', 'NapCat.Shell']; // 已知的 artifact 名称
for (const run of workflowRuns) {
for (const artifactName of artifactNames) {
const mirror = currentConfig.nightlyLinkMirrors[0] || 'https://nightly.link';
artifacts.push({
id: run.id,
name: artifactName,
size_in_bytes: 0,
created_at: run.created_at,
expires_at: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString(),
archive_download_url: `${mirror}/${owner}/${repo}/actions/runs/${run.id}/${artifactName}.zip`,
workflow_run_id: run.id,
head_sha: run.head_sha,
});
}
}
return artifacts;
}
/**
* 通过 GitHub API 获取 artifacts主要方案
*/
async function getArtifactsFromAPI (
owner: string,
repo: string,
workflow: string = 'build.yml',
branch: string = 'main',
maxRuns: number = 10
): Promise<ActionArtifact[]> {
const endpoint = `https://api.github.com/repos/${owner}/${repo}/actions/workflows/${workflow}/runs?branch=${branch}&status=success&per_page=${maxRuns}`;
const runsResponse = await PromiseTimer(
RequestUtil.HttpGetJson<{
workflow_runs: Array<{ id: number; head_sha: string; created_at: string; }>;
}>(endpoint, 'GET', undefined, {
'User-Agent': 'NapCat',
'Accept': 'application/vnd.github.v3+json',
}),
10000
);
const workflowRuns = runsResponse.workflow_runs;
if (!workflowRuns || workflowRuns.length === 0) {
throw new Error('No successful workflow runs found');
}
// 获取所有 runs 的 artifacts
const allArtifacts: ActionArtifact[] = [];
for (const run of workflowRuns) {
try {
const artifactsEndpoint = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${run.id}/artifacts`;
const artifactsResponse = await PromiseTimer(
RequestUtil.HttpGetJson<{
artifacts: ActionArtifact[];
}>(artifactsEndpoint, 'GET', undefined, {
'User-Agent': 'NapCat',
'Accept': 'application/vnd.github.v3+json',
}),
10000
);
if (artifactsResponse.artifacts) {
// 为每个 artifact 添加 run 信息
for (const artifact of artifactsResponse.artifacts) {
artifact.workflow_run_id = run.id;
artifact.head_sha = run.head_sha;
allArtifacts.push(artifact);
}
for (const run of workflowRuns) {
for (const artifactName of artifactNames) {
artifacts.push({
id: run.id,
name: artifactName,
size_in_bytes: 0,
created_at: run.created_at,
expires_at: new Date(new Date(run.created_at).getTime() + 3 * 24 * 60 * 60 * 1000).toISOString(),
archive_download_url: `${baseNightlyMirror}/${owner}/${repo}/actions/runs/${run.id}/${artifactName}.zip`,
workflow_run_id: run.id,
workflow_title: run.title,
});
}
} catch {
// 单个 run 获取失败,继续下一个
}
}
return { artifacts, mirror: runsMirror };
return allArtifacts;
} catch {
return { artifacts: [], mirror: '' };
}
}
/**
@@ -1121,48 +1067,41 @@ async function getArtifactsFromAPI (
* 策略:
* 1. 检查缓存10分钟有效
* 2. 优先尝试从 nightly.link 获取(无需认证,更稳定)
* 3. 如果失败,回退到 GitHub API
* 3. 这里的实现已经完全移除了对 GitHub API 的依赖,直接解析 HTML
*/
export async function getLatestActionArtifacts (
owner: string,
repo: string,
workflow: string = 'build.yml',
branch: string = 'main',
maxRuns: number = 10
): Promise<ActionArtifact[]> {
const cacheKey = `${owner}/${repo}/${workflow}/${branch}`;
maxRuns: number = 10,
mirror?: string
): Promise<{ artifacts: ActionArtifact[], mirror: string; }> {
const cacheKey = `${owner}/${repo}/${workflow}/${branch}/${mirror || 'auto'}`;
// 检查缓存
const cached = artifactsCache.get(cacheKey);
if (cached && (Date.now() - cached.timestamp) < ARTIFACTS_CACHE_TTL) {
return cached.artifacts;
return { artifacts: cached.artifacts, mirror: cached.mirror };
}
let artifacts: ActionArtifact[] = [];
let result: { artifacts: ActionArtifact[], mirror: string; } = { artifacts: [], mirror: '' };
// 策略1: 优先使用 nightly.link更稳定无需认证
// 策略: 优先使用 nightly.link更稳定无需认证+ HTML 解析
try {
artifacts = await getArtifactsFromNightlyLink(owner, repo, workflow, branch, maxRuns);
result = await getArtifactsFromNightlyLink(owner, repo, workflow, branch, maxRuns, mirror);
} catch {
// nightly.link 获取失败
}
// 策略2: 回退到 GitHub API
if (artifacts.length === 0) {
try {
artifacts = await getArtifactsFromAPI(owner, repo, workflow, branch, maxRuns);
} catch {
// API 获取失败
}
// 获取失败
}
// 缓存结果(即使为空也缓存,避免频繁请求)
if (artifacts.length > 0) {
if (result.artifacts.length > 0) {
artifactsCache.set(cacheKey, {
artifacts,
artifacts: result.artifacts,
mirror: result.mirror,
timestamp: Date.now(),
});
}
return artifacts;
return result;
}

View File

@@ -65,9 +65,11 @@ export function compareSemVer (v1: string, v2: string): -1 | 0 | 1 {
const a = parseSemVer(v1);
const b = parseSemVer(v2);
if (!a.valid || !b.valid) {
return 0;
if (!a.valid && !b.valid) {
return v1.localeCompare(v2) as -1 | 0 | 1;
}
if (!a.valid) return -1;
if (!b.valid) return 1;
// 比较主版本号
if (a.major !== b.major) return a.major > b.major ? 1 : -1;

View File

@@ -67,6 +67,8 @@ import GoCQHTTPUploadPrivateFile from './go-cqhttp/UploadPrivateFile';
import { FetchEmojiLike } from './extends/FetchEmojiLike';
import { NapCatCore } from 'napcat-core';
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
import type { NetworkAdapterConfig } from '../config/config';
import { OneBotAction } from './OneBotAction';
import { SetInputStatus } from './extends/SetInputStatus';
import { GetCSRF } from './system/GetCSRF';
import { DelGroupNotice } from './group/DelGroupNotice';
@@ -322,6 +324,30 @@ export function createActionMap (obContext: NapCatOneBot11Adapter, core: NapCatC
function get<K extends keyof MapType> (key: K): MapType[K] | undefined {
return _map.get(key as keyof MapType) as MapType[K] | undefined;
}
return { get };
/**
* 类型安全的 action 调用辅助函数
* 根据 action 名称自动推导返回类型
*/
async function call<K extends keyof MapType> (
actionName: K,
params: unknown,
adapter: string,
config: NetworkAdapterConfig
): Promise<MapType[K] extends OneBotAction<any, infer R> ? R : never> {
const action = _map.get(actionName);
if (!action) {
throw new Error(`Action ${String(actionName)} not found`);
}
const result = await (action as any).handle(params, adapter, config);
if (result.status !== 'ok' || !result.data) {
throw new Error(`Action ${String(actionName)} failed: ${result.message || 'No data returned'}`);
}
return result.data;
}
return { get, call };
}
export type ActionMap = ReturnType<typeof createActionMap>;

View File

@@ -587,15 +587,33 @@ export class OneBotMsgApi {
return at(atQQ, uid, NTMsgAtType.ATTYPEONE, info.nick || '');
},
[OB11MessageDataType.reply]: async ({ data: { id } }) => {
const replyMsgM = MessageUnique.getMsgIdAndPeerByShortId(parseInt(id));
if (!replyMsgM) {
this.core.context.logger.logWarn('回复消息不存在', id);
[OB11MessageDataType.reply]: async ({ data: { id, seq } }, context) => {
let replyMsg: RawMessage | undefined;
let replyMsgPeer: Peer | undefined;
// 优先使用 seq
if (seq) {
const msgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(
context.peer, seq.toString(), 1, true, true
)).msgList;
replyMsg = msgList[0];
replyMsgPeer = context.peer;
} else if (id) {
// 降级使用 id
const replyMsgM = MessageUnique.getMsgIdAndPeerByShortId(parseInt(id));
if (!replyMsgM) {
this.core.context.logger.logWarn('回复消息不存在', id);
return undefined;
}
replyMsg = (await this.core.apis.MsgApi.getMsgsByMsgId(
replyMsgM.Peer, [replyMsgM.MsgId])).msgList[0];
replyMsgPeer = replyMsgM.Peer;
} else {
this.core.context.logger.logWarn('回复消息缺少id或seq参数');
return undefined;
}
const replyMsg = (await this.core.apis.MsgApi.getMsgsByMsgId(
replyMsgM.Peer, [replyMsgM.MsgId])).msgList[0];
return replyMsg
return replyMsg && replyMsgPeer
? {
elementType: ElementType.REPLY,
elementId: '',
@@ -605,7 +623,7 @@ export class OneBotMsgApi {
senderUin: replyMsg.senderUin,
senderUinStr: replyMsg.senderUin,
replyMsgClientSeq: replyMsg.clientSeq,
_replyMsgPeer: replyMsgM.Peer,
_replyMsgPeer: replyMsgPeer,
},
}
: undefined;

View File

@@ -49,10 +49,11 @@ import {
OneBotConfigSchema,
} from './config/config';
import { OB11Message } from './types';
import { existsSync } from 'node:fs';
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
import { OB11HttpSSEServerAdapter } from './network/http-server-sse';
import { OB11PluginMangerAdapter } from './network/plugin-manger';
import { existsSync } from 'node:fs';
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { OneBotFileApi } from './api/file';
@@ -160,6 +161,7 @@ export class NapCatOneBot11Adapter {
// this.networkManager.registerAdapter(
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
// );
// 检查插件目录是否存在,不存在则不加载插件管理器
if (existsSync(this.context.pathWrapper.pluginPath)) {
this.context.logger.log('[Plugins] 插件目录存在,开始加载插件');
this.networkManager.registerAdapter(

View File

@@ -1,9 +1,9 @@
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
import { NapCatCore } from 'napcat-core';
import { PluginConfig } from '../config/config';
import { ActionMap } from '../action';
import { NapCatCore } from 'napcat-core';
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
import { PluginConfig } from '../config/config';
import fs from 'fs';
import path from 'path';
@@ -11,13 +11,39 @@ export interface PluginPackageJson {
name?: string;
version?: string;
main?: string;
description?: string;
author?: string;
}
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
plugin_init: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_onmessage?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: OB11Message, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_onevent?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: T, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_cleanup?: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_init: (
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
plugin_onmessage?: (
adapter: string,
core: NapCatCore,
obCtx: NapCatOneBot11Adapter,
event: OB11Message,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
plugin_onevent?: (
adapter: string,
core: NapCatCore,
obCtx: NapCatOneBot11Adapter,
event: T,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
plugin_cleanup?: (
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
}
export interface LoadedPlugin {
@@ -29,16 +55,25 @@ export interface LoadedPlugin {
module: PluginModule;
}
export interface PluginStatusConfig {
[key: string]: boolean; // key: pluginName, value: enabled
}
export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
private readonly pluginPath: string;
private readonly configPath: string;
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
declare config: PluginConfig;
override get isActive (): boolean {
return this.isEnable && this.loadedPlugins.size > 0;
}
constructor (
name: string, core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap
name: string,
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap
) {
const config = {
name,
@@ -49,24 +84,60 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
};
super(name, config, core, obContext, actions);
this.pluginPath = this.core.context.pathWrapper.pluginPath;
this.configPath = path.join(this.core.context.pathWrapper.configPath, 'plugins.json');
}
private loadPluginConfig (): PluginStatusConfig {
if (fs.existsSync(this.configPath)) {
try {
return JSON.parse(fs.readFileSync(this.configPath, 'utf-8'));
} catch (e) {
this.logger.logWarn('[Plugin Adapter] Error parsing plugins.json', e);
}
}
return {};
}
private savePluginConfig (config: PluginStatusConfig) {
try {
fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), 'utf-8');
} catch (e) {
this.logger.logError('[Plugin Adapter] Error saving plugins.json', e);
}
}
/**
* 扫描并加载插件
*/
* 扫描并加载插件
*/
private async loadPlugins (): Promise<void> {
try {
// 确保插件目录存在
if (!fs.existsSync(this.pluginPath)) {
this.logger.logWarn(`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`);
this.logger.logWarn(
`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`
);
fs.mkdirSync(this.pluginPath, { recursive: true });
return;
}
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
const pluginConfig = this.loadPluginConfig();
// 扫描文件和目录
for (const item of items) {
let pluginName = '';
if (item.isFile()) {
pluginName = path.parse(item.name).name;
} else if (item.isDirectory()) {
pluginName = item.name;
}
// Check if plugin is disabled in config
if (pluginConfig[pluginName] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} is disabled in config, skipping`);
continue;
}
if (item.isFile()) {
// 处理单文件插件
await this.loadFilePlugin(item.name);
@@ -76,16 +147,18 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
}
this.logger.log(`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`);
this.logger.log(
`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`
);
} catch (error) {
this.logger.logError('[Plugin Adapter] Error loading plugins:', error);
}
}
/**
* 加载单文件插件 (.mjs, .js)
*/
private async loadFilePlugin (filename: string): Promise<void> {
* 加载单文件插件 (.mjs, .js)
*/
public async loadFilePlugin (filename: string): Promise<void> {
// 只处理支持的文件类型
if (!this.isSupportedFile(filename)) {
return;
@@ -93,11 +166,20 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
const filePath = path.join(this.pluginPath, filename);
const pluginName = path.parse(filename).name;
const pluginConfig = this.loadPluginConfig();
// Check if plugin is disabled in config
if (pluginConfig[pluginName] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} is disabled by user`);
return;
}
try {
const module = await this.importModule(filePath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
this.logger.logWarn(
`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`
);
return;
}
@@ -110,15 +192,31 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
this.logger.logError(
`[Plugin Adapter] Error loading file plugin ${filename}:`,
error
);
}
}
/**
* 加载目录插件
*/
private async loadDirectoryPlugin (dirname: string): Promise<void> {
* 加载目录插件
*/
public async loadDirectoryPlugin (dirname: string): Promise<void> {
const pluginDir = path.join(this.pluginPath, dirname);
const pluginConfig = this.loadPluginConfig();
// Ideally we'd get the name from package.json first, but we can use dirname as a fallback identifier initially.
// However, the list scan uses item.name (dirname) as the key. Let's stick to using dirname/filename as the config key for simplicity and consistency.
// Wait, package.json name might override. But for management, consistent ID is better.
// Let's check config after parsing package.json?
// User expects to disable 'plugin-name'. But if multiple folders have same name? Not handled.
// Let's use dirname as the key for config to be consistent with file system.
if (pluginConfig[dirname] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${dirname} is disabled by user`);
return;
}
try {
// 尝试读取 package.json
@@ -130,14 +228,22 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
packageJson = JSON.parse(packageContent);
} catch (error) {
this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
this.logger.logWarn(
`[Plugin Adapter] Invalid package.json in ${dirname}:`,
error
);
}
}
// Check if disabled by package name IF package.json exists?
// No, file system name is more reliable ID for resource management here.
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
if (!entryFile) {
this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
this.logger.logWarn(
`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`
);
return;
}
@@ -145,7 +251,9 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
const module = await this.importModule(entryPath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
this.logger.logWarn(
`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`
);
return;
}
@@ -160,14 +268,20 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
this.logger.logError(
`[Plugin Adapter] Error loading directory plugin ${dirname}:`,
error
);
}
}
/**
* 查找插件目录的入口文件
*/
private findEntryFile (pluginDir: string, packageJson?: PluginPackageJson): string | null {
* 查找插件目录的入口文件
*/
private findEntryFile (
pluginDir: string,
packageJson?: PluginPackageJson
): string | null {
// 优先级package.json main > 默认文件名
const possibleEntries = [
packageJson?.main,
@@ -188,53 +302,69 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
/**
* 检查是否为支持的文件类型
*/
* 检查是否为支持的文件类型
*/
private isSupportedFile (filename: string): boolean {
const ext = path.extname(filename).toLowerCase();
return ['.mjs', '.js'].includes(ext);
}
/**
* 动态导入模块
*/
* 动态导入模块
*/
private async importModule (filePath: string): Promise<any> {
const fileUrl = `file://${filePath.replace(/\\/g, '/')}`;
return await import(fileUrl);
// Add timestamp to force reload cache if supported or just import
// Note: dynamic import caching is tricky in ESM. Adding query param might help?
const fileUrlWithQuery = `${fileUrl}?t=${Date.now()}`;
return await import(fileUrlWithQuery);
}
/**
* 检查模块是否为有效的插件模块
*/
* 检查模块是否为有效的插件模块
*/
private isValidPluginModule (module: any): module is PluginModule {
return module && typeof module.plugin_init === 'function';
}
/**
* 注册插件
*/
* 注册插件
*/
private async registerPlugin (plugin: LoadedPlugin): Promise<void> {
// 检查名称冲突
if (this.loadedPlugins.has(plugin.name)) {
this.logger.logWarn(`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`);
this.logger.logWarn(
`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`
);
return;
}
this.loadedPlugins.set(plugin.name, plugin);
this.logger.log(`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''}`);
this.logger.log(
`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''
}`
);
// 调用插件初始化方法(必须存在)
try {
await plugin.module.plugin_init(this.core, this.obContext, this.actions, this);
await plugin.module.plugin_init(
this.core,
this.obContext,
this.actions,
this
);
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error initializing plugin ${plugin.name}:`, error);
this.logger.logError(
`[Plugin Adapter] Error initializing plugin ${plugin.name}:`,
error
);
}
}
/**
* 卸载插件
*/
* 卸载插件
*/
private async unloadPlugin (pluginName: string): Promise<void> {
const plugin = this.loadedPlugins.get(pluginName);
if (!plugin) {
@@ -244,10 +374,18 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
// 调用插件清理方法
if (typeof plugin.module.plugin_cleanup === 'function') {
try {
await plugin.module.plugin_cleanup(this.core, this.obContext, this.actions, this);
await plugin.module.plugin_cleanup(
this.core,
this.obContext,
this.actions,
this
);
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`, error);
this.logger.logError(
`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`,
error
);
}
}
@@ -255,6 +393,69 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
}
public async unregisterPlugin (pluginName: string): Promise<void> {
return this.unloadPlugin(pluginName);
}
public getPluginPath (): string {
return this.pluginPath;
}
public getPluginConfig (): PluginStatusConfig {
return this.loadPluginConfig();
}
public setPluginStatus (pluginName: string, enable: boolean): void {
const config = this.loadPluginConfig();
config[pluginName] = enable;
this.savePluginConfig(config);
// If disabling, unload immediately if loaded
if (!enable) {
// Note: pluginName passed here might be the package name or the filename/dirname
// But our registerPlugin uses plugin.name which comes from package.json or dirname.
// This mismatch is tricky.
// Ideally, we should use a consistent ID.
// Let's assume pluginName passed here effectively matches the ID used in loadedPlugins.
// But wait, loadDirectoryPlugin logic: name = packageJson.name || dirname.
// config key = dirname.
// If packageJson.name != dirname, we have a problem.
// To fix this properly:
// 1. We need to know which LoadedPlugin corresponds to the enabled/disabled item.
// 2. Or we iterate loadedPlugins and find match.
for (const [_, loaded] of this.loadedPlugins.entries()) {
const dirOrFile = path.basename(loaded.pluginPath === this.pluginPath ? loaded.entryPath : loaded.pluginPath);
const ext = path.extname(dirOrFile);
const simpleName = ext ? path.parse(dirOrFile).name : dirOrFile; // filename without ext
// But wait, config key is the FILENAME (with ext for files?).
// In Scan loop:
// pluginName = path.parse(item.name).name (for file)
// pluginName = item.name (for dir)
// config[pluginName] check.
// So if file is "test.js", pluginName is "test". Config key "test".
// If dir is "test-plugin", pluginName is "test-plugin". Config key "test-plugin".
// loadedPlugin.name might be distinct.
// So we need to match loadedPlugin back to its fs source to unload it?
// loadedPlugin.entryPath or pluginPath helps.
// If it's a file plugin: loaded.entryPath ends with pluginName + ext.
// If it's a dir plugin: loaded.pluginPath ends with pluginName.
if (pluginName === simpleName) {
this.unloadPlugin(loaded.name).catch(e => this.logger.logError('Error unloading', e));
}
}
}
// If enabling, we need to load it.
// But we can just rely on the API handler to call loadFile/DirectoryPlugin which now checks config.
// Wait, if I call loadFilePlugin("test.js") and config says enable=true, it loads.
// API handler needs to change to pass filename/dirname.
}
async onEvent<T extends OB11EmitEventContent> (event: T) {
if (!this.isEnable) {
return;
@@ -273,21 +474,44 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
/**
* 调用插件的事件处理方法
*/
private async callPluginEventHandler (plugin: LoadedPlugin, event: OB11EmitEventContent): Promise<void> {
* 调用插件的事件处理方法
*/
private async callPluginEventHandler (
plugin: LoadedPlugin,
event: OB11EmitEventContent
): Promise<void> {
try {
// 优先使用 plugin_onevent 方法
if (typeof plugin.module.plugin_onevent === 'function') {
await plugin.module.plugin_onevent(this.name, this.core, this.obContext, event, this.actions, this);
await plugin.module.plugin_onevent(
this.name,
this.core,
this.obContext,
event,
this.actions,
this
);
}
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
if ((event as any).message_type && typeof plugin.module.plugin_onmessage === 'function') {
await plugin.module.plugin_onmessage(this.name, this.core, this.obContext, event as OB11Message, this.actions, this);
if (
(event as any).message_type &&
typeof plugin.module.plugin_onmessage === 'function'
) {
await plugin.module.plugin_onmessage(
this.name,
this.core,
this.obContext,
event as OB11Message,
this.actions,
this
);
}
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
this.logger.logError(
`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`,
error
);
}
}
@@ -302,7 +526,9 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
// 加载所有插件
await this.loadPlugins();
this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
this.logger.log(
`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`
);
}
async close () {
@@ -334,22 +560,22 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
/**
* 获取已加载的插件列表
*/
* 获取已加载的插件列表
*/
public getLoadedPlugins (): LoadedPlugin[] {
return Array.from(this.loadedPlugins.values());
}
/**
* 获取插件信息
*/
* 获取插件信息
*/
public getPluginInfo (pluginName: string): LoadedPlugin | undefined {
return this.loadedPlugins.get(pluginName);
}
/**
* 重载指定插件
*/
* 重载指定插件
*/
public async reloadPlugin (pluginName: string): Promise<boolean> {
const plugin = this.loadedPlugins.get(pluginName);
if (!plugin) {
@@ -362,8 +588,10 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
await this.unloadPlugin(pluginName);
// 重新加载插件
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
plugin.pluginPath !== this.pluginPath;
// Use logic to re-determine if it is directory or file based on original paths
// Note: we can't fully trust fs status if it's gone.
const isDirectory =
plugin.pluginPath !== this.pluginPath; // Simple check: if path is nested, it's a dir plugin
if (isDirectory) {
const dirname = path.basename(plugin.pluginPath);
@@ -373,10 +601,15 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
await this.loadFilePlugin(filename);
}
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
this.logger.log(
`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`
);
return true;
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
this.logger.logError(
`[Plugin Adapter] Error reloading plugin ${pluginName}:`,
error
);
return false;
}
}

View File

@@ -103,7 +103,7 @@ export interface OB11MessageText {
}
// 联系人消息接口定义
export interface OB11MessageContext {
export interface OB11MessageContact {
type: OB11MessageDataType.contact;
data: {
type: 'qq' | 'group';
@@ -159,7 +159,8 @@ export interface OB11MessageAt {
export interface OB11MessageReply {
type: OB11MessageDataType.reply;
data: {
id: string;
id?: string; // msg_id 的短ID映射
seq?: number; // msg_seq优先使用
};
}
@@ -260,7 +261,7 @@ export type OB11MessageData =
OB11MessageAt | OB11MessageReply |
OB11MessageImage | OB11MessageRecord | OB11MessageFile | OB11MessageVideo |
OB11MessageNode | OB11MessageIdMusic | OB11MessageCustomMusic | OB11MessageJson |
OB11MessageDice | OB11MessageRPS | OB11MessageMarkdown | OB11MessageForward | OB11MessageContext | OB11MessagePoke;
OB11MessageDice | OB11MessageRPS | OB11MessageMarkdown | OB11MessageForward | OB11MessageContact | OB11MessagePoke;
// 发送消息接口定义
export interface OB11PostSendMsg {

View File

@@ -0,0 +1,84 @@
import type { ActionMap } from 'napcat-onebot/action';
import { EventType } from 'napcat-onebot/event/OneBotEvent';
import type { PluginModule } from 'napcat-onebot/network/plugin';
import type { OB11Message, OB11PostSendMsg } from 'napcat-onebot/types/message';
let actions: ActionMap | undefined = undefined;
/**
* 插件初始化
*/
const plugin_init: PluginModule['plugin_init'] = async (_core, _obContext, _actions, _instance) => {
console.log('[Plugin: builtin] NapCat 内置插件已初始化');
actions = _actions;
};
/**
* 消息处理
* 当收到包含 #napcat 的消息时,回复版本信息
*/
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (adapter, _core, _obCtx, event, _actions, instance) => {
if (event.post_type !== EventType.MESSAGE || !event.raw_message.startsWith('#napcat')) {
return;
}
try {
const versionInfo = await getVersionInfo(adapter, instance.config);
if (!versionInfo) return;
const message = formatVersionMessage(versionInfo);
await sendMessage(event, message, adapter, instance.config);
console.log('[Plugin: builtin] 已回复版本信息');
} catch (error) {
console.error('[Plugin: builtin] 处理消息时发生错误:', error);
}
};
/**
* 获取版本信息(完美的类型推导,无需 as 断言)
*/
async function getVersionInfo (adapter: string, config: any) {
if (!actions) return null;
try {
const data = await actions.call('get_version_info', void 0, adapter, config);
return {
appName: data.app_name,
appVersion: data.app_version,
protocolVersion: data.protocol_version,
};
} catch (error) {
console.error('[Plugin: builtin] 获取版本信息失败:', error);
return null;
}
}
/**
* 格式化版本信息消息
*/
function formatVersionMessage (info: { appName: string; appVersion: string; protocolVersion: string; }) {
return `NapCat 信息\n版本: ${info.appVersion}\n平台: ${process.platform}${process.arch === 'x64' ? ' (64-bit)' : ''}`;
}
/**
* 发送消息(完美的类型推导)
*/
async function sendMessage (event: OB11Message, message: string, adapter: string, config: any) {
if (!actions) return;
const params: OB11PostSendMsg = {
message,
message_type: event.message_type,
...(event.message_type === 'group' && event.group_id ? { group_id: String(event.group_id) } : {}),
...(event.message_type === 'private' && event.user_id ? { user_id: String(event.user_id) } : {}),
};
try {
await actions.call('send_msg', params, adapter, config);
} catch (error) {
console.error('[Plugin: builtin] 发送消息失败:', error);
}
}
export { plugin_init, plugin_onmessage };

View File

@@ -0,0 +1,17 @@
{
"name": "napcat-plugin-builtin",
"version": "1.0.0",
"type": "module",
"main": "index.mjs",
"description": "NapCat 内置插件",
"author": "NapNeko",
"dependencies": {
"napcat-onebot": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.1"
},
"scripts": {
"build": "vite build"
}
}

View File

@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"include": [
"*.ts",
"**/*.ts"
],
"exclude": [
"node_modules",
"dist"
]
}

View File

@@ -0,0 +1,77 @@
import { defineConfig } from 'vite';
import { resolve } from 'path';
import nodeResolve from '@rollup/plugin-node-resolve';
import { builtinModules } from 'module';
import fs from 'fs';
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
// 构建后拷贝插件
function copyToShellPlugin () {
return {
name: 'copy-to-shell',
closeBundle () {
try {
const sourceDir = resolve(__dirname, 'dist');
const targetDir = resolve(__dirname, '../napcat-shell/dist/plugins/builtin');
const packageJsonSource = resolve(__dirname, 'package.json');
// 确保目标目录存在
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
console.log(`[copy-to-shell] Created directory: ${targetDir}`);
}
// 拷贝 dist 目录下的所有文件
const files = fs.readdirSync(sourceDir);
let copiedCount = 0;
files.forEach(file => {
const sourcePath = resolve(sourceDir, file);
const targetPath = resolve(targetDir, file);
if (fs.statSync(sourcePath).isFile()) {
fs.copyFileSync(sourcePath, targetPath);
copiedCount++;
}
});
// 拷贝 package.json
if (fs.existsSync(packageJsonSource)) {
const packageJsonTarget = resolve(targetDir, 'package.json');
fs.copyFileSync(packageJsonSource, packageJsonTarget);
copiedCount++;
}
console.log(`[copy-to-shell] Successfully copied ${copiedCount} file(s) to ${targetDir}`);
} catch (error) {
console.error('[copy-to-shell] Failed to copy files:', error);
throw error;
}
},
};
}
export default defineConfig({
resolve: {
conditions: ['node', 'default'],
alias: {
'@/napcat-core': resolve(__dirname, '../napcat-core'),
'@': resolve(__dirname, '../'),
},
},
build: {
sourcemap: false,
target: 'esnext',
minify: false,
lib: {
entry: 'index.ts',
formats: ['es'],
fileName: () => 'index.mjs',
},
rollupOptions: {
external: [...nodeModules],
},
},
plugins: [nodeResolve(), copyToShellPlugin()],
});

View File

@@ -3,5 +3,5 @@ REM 快速登录示例脚本
REM -q 参数是可选的,不传则使用二维码登录
REM
REM 使用方法(删掉对应系统那行的 REM
REM ./launcher.bat -q 123456
REM ./launcher-win10.bat -q 123456
REM ./launcher-user.bat 123456
REM ./launcher-win10-user.bat 123456

View File

@@ -35,6 +35,7 @@ import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
import { statusHelperSubscription } from '@/napcat-core/helper/status';
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
import { connectToNamedPipe } from './pipe';
// NapCat Shell App ES 入口文件
async function handleUncaughtExceptions (logger: LogWrapper) {
process.on('uncaughtException', (err) => {
@@ -342,9 +343,9 @@ export async function NCoreInitShell () {
// 初始化 FFmpeg 服务
await FFmpegService.init(pathWrapper.binaryPath, logger);
// if (process.env['NAPCAT_DISABLE_PIPE'] !== '1') {
// await connectToNamedPipe(logger).catch(e => logger.logError('命名管道连接失败', e));
// }
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 });
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVersion());
const nativePacketHandler = new NativePacketHandler({ logger }); // 初始化 NativePacketHandler 用于后续使用

View File

@@ -3,6 +3,8 @@ import { NapCatPathWrapper } from '@/napcat-common/src/path';
import { LogWrapper } from '@/napcat-core/helper/log';
import { connectToNamedPipe } from './pipe';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { AuthHelper } from '@/napcat-webui-backend/src/helper/SignToken';
import { webUiRuntimePort } from '@/napcat-webui-backend/index';
import { createProcessManager, type IProcessManager, type IWorkerProcess } from './process-api';
import path from 'path';
import { fileURLToPath } from 'url';
@@ -18,6 +20,13 @@ const ENV = {
isPipeDisabled: process.env['NAPCAT_DISABLE_PIPE'] === '1',
} as const;
// Worker 消息类型
interface WorkerMessage {
type: 'restart' | 'restart-prepare' | 'shutdown';
secretKey?: string;
port?: number;
}
// 初始化日志
const pathWrapper = new NapCatPathWrapper();
const logger = new LogWrapper(pathWrapper.logsPath);
@@ -26,6 +35,8 @@ const logger = new LogWrapper(pathWrapper.logsPath);
let processManager: IProcessManager | null = null;
let currentWorker: IWorkerProcess | null = null;
let isElectron = false;
let isRestarting = false;
let isShuttingDown = false;
/**
* 获取进程类型名称(用于日志)
@@ -61,26 +72,34 @@ function isProcessAlive (pid: number): boolean {
function forceKillProcess (pid: number): void {
try {
process.kill(pid, 'SIGKILL');
logger.log(`[NapCat] [Process] 已强制终止进程 ${pid}`);
} catch (error) {
logger.logError(`[NapCat] [Process] 强制终止进程失败:`, error);
// SIGKILL 失败,在 Windows 上使用 taskkill 兜底
if (process.platform === 'win32') {
try {
require('child_process').execSync(`taskkill /F /PID ${pid}`, { stdio: 'ignore' });
} catch {
logger.logError(`[NapCat] [Process] 强制终止进程失败: PID ${pid}`);
}
} else {
logger.logError(`[NapCat] [Process] 强制终止进程失败:`, error);
}
}
}
/**
* 重启 Worker 进程
*/
export async function restartWorker (): Promise<void> {
logger.log('[NapCat] [Process] 正在重启Worker进程...');
export async function restartWorker (secretKey?: string, port?: number): Promise<void> {
isRestarting = true;
if (!currentWorker) {
logger.logWarn('[NapCat] [Process] 没有运行中的Worker进程');
await startWorker();
await startWorker(false);
isRestarting = false;
return;
}
const workerPid = currentWorker.pid;
logger.log(`[NapCat] [Process] 准备关闭Worker进程PID: ${workerPid}`);
// 1. 通知旧进程准备重启(旧进程会自行退出)
currentWorker.postMessage({ type: 'restart-prepare' });
@@ -101,45 +120,35 @@ export async function restartWorker (): Promise<void> {
currentWorker?.once('exit', () => {
clearTimeout(timeout);
logger.log('[NapCat] [Process] Worker进程已正常退出');
resolve();
});
});
// 3. 二次确认进程是否真的被终止(兜底检查)
if (workerPid) {
logger.log(`[NapCat] [Process] 检查进程 ${workerPid} 是否已终止...`);
if (workerPid && isProcessAlive(workerPid)) {
logger.logWarn(`[NapCat] [Process] 进程 ${workerPid} 仍在运行,尝试强制杀掉`);
forceKillProcess(workerPid);
await new Promise(resolve => setTimeout(resolve, 1000));
if (isProcessAlive(workerPid)) {
logger.logWarn(`[NapCat] [Process] 进程 ${workerPid} 仍在运行,尝试强制杀掉(兜底)`);
forceKillProcess(workerPid);
// 等待 1 秒后再次检查
await new Promise(resolve => setTimeout(resolve, 1000));
if (isProcessAlive(workerPid)) {
logger.logError(`[NapCat] [Process] 进程 ${workerPid} 无法终止,可能需要手动处理`);
} else {
logger.log(`[NapCat] [Process] 进程 ${workerPid} 已被强制终止`);
}
} else {
logger.log(`[NapCat] [Process] 进程 ${workerPid} 已确认终止`);
logger.logError(`[NapCat] [Process] 进程 ${workerPid} 无法终止,可能需要手动处理`);
}
}
// 4. 等待 3 秒后启动新进程
logger.log('[NapCat] [Process] Worker进程已关闭等待 3 秒后启动新进程...');
// 4. 等待后启动新进程
await new Promise(resolve => setTimeout(resolve, 3000));
// 5. 启动新进程
await startWorker();
logger.log('[NapCat] [Process] Worker进程重启完成');
// 5. 启动新进程(重启模式不传递快速登录参数,传递密钥和端口)
await startWorker(false, secretKey, port);
isRestarting = false;
}
/**
* 启动 Worker 进程
* @param passQuickLogin 是否传递快速登录参数,默认为 true重启时为 false
* @param secretKey WebUI JWT 密钥
* @param preferredPort 优先使用的 WebUI 端口
*/
async function startWorker (): Promise<void> {
async function startWorker (passQuickLogin: boolean = true, secretKey?: string, preferredPort?: number): Promise<void> {
if (!processManager) {
throw new Error('进程管理器未初始化');
}
@@ -147,10 +156,26 @@ async function startWorker (): Promise<void> {
const workerScript = getWorkerScriptPath();
const processType = getProcessTypeName();
const child = processManager.createWorker(workerScript, [], {
// 只在首次启动时传递 -q 或 --qq 参数给 worker 进程
const workerArgs: string[] = [];
if (passQuickLogin) {
const args = process.argv.slice(2);
const qIndex = args.findIndex(arg => arg === '-q' || arg === '--qq');
if (qIndex !== -1 && qIndex + 1 < args.length) {
const qFlag = args[qIndex];
const qValue = args[qIndex + 1];
if (qFlag && qValue) {
workerArgs.push(qFlag, qValue);
}
}
}
const child = processManager.createWorker(workerScript, workerArgs, {
env: {
...process.env,
NAPCAT_WORKER_PROCESS: '1',
...(secretKey ? { NAPCAT_WEBUI_JWT_SECRET_KEY: secretKey } : {}),
...(preferredPort ? { NAPCAT_WEBUI_PREFERRED_PORT: String(preferredPort) } : {}),
},
stdio: isElectron ? 'pipe' : ['inherit', 'pipe', 'pipe', 'ipc'],
});
@@ -173,14 +198,14 @@ async function startWorker (): Promise<void> {
// 监听子进程消息
child.on('message', (msg: unknown) => {
logger.log(`[NapCat] [${processType}] 收到Worker消息:`, msg);
// 处理重启请求
if (typeof msg === 'object' && msg !== null && 'type' in msg && msg.type === 'restart') {
logger.log(`[NapCat] [${processType}] 收到重启请求正在重启Worker进程...`);
restartWorker().catch(e => {
logger.logError(`[NapCat] [${processType}] 重启Worker进程失败:`, e);
});
if (typeof msg === 'object' && msg !== null && 'type' in msg) {
const message = msg as WorkerMessage;
if (message.type === 'restart') {
restartWorker(message.secretKey, message.port).catch(e => {
logger.logError(`[NapCat] [${processType}] 重启Worker进程失败:`, e);
});
}
}
});
@@ -189,13 +214,30 @@ async function startWorker (): Promise<void> {
const exitCode = typeof code === 'number' ? code : 0;
if (exitCode !== 0) {
logger.logError(`[NapCat] [${processType}] Worker进程退出退出码: ${exitCode}`);
} else {
logger.log(`[NapCat] [${processType}] Worker进程正常退出`);
}
// 如果不是由于主动重启或关闭引起的退出,尝试自动重新拉起
if (!isRestarting && !isShuttingDown) {
logger.logWarn(`[NapCat] [${processType}] Worker进程意外退出正在尝试重新拉起...`);
startWorker(true).catch(e => {
logger.logError(`[NapCat] [${processType}] 重新拉起Worker进程失败:`, e);
});
}
});
child.on('spawn', () => {
logger.log(`[NapCat] [${processType}] Worker进程已生成`);
// 等待进程成功 spawn
await new Promise<void>((resolve, reject) => {
const onSpawn = () => {
child.off('error', onError);
resolve();
};
const onError = (...args: unknown[]) => {
const err = args[0] as Error;
logger.logError(`[NapCat] [${processType}] Worker进程启动失败:`, err);
child.off('spawn', onSpawn);
reject(err);
};
child.once('spawn', onSpawn);
child.once('error', onError);
});
}
@@ -203,25 +245,19 @@ async function startWorker (): Promise<void> {
* 启动 Master 进程
*/
async function startMasterProcess (): Promise<void> {
const processType = getProcessTypeName();
logger.log(`[NapCat] [${processType}] Master进程启动PID: ${process.pid}`);
// 连接命名管道(可通过环境变量禁用)
if (!ENV.isPipeDisabled) {
await connectToNamedPipe(logger).catch(e =>
logger.logError('命名管道连接失败', e)
);
} else {
logger.log(`[NapCat] [${processType}] 命名管道已禁用 (NAPCAT_DISABLE_PIPE=1)`);
}
// 启动 Worker 进程
await startWorker();
// 优雅关闭处理
const shutdown = (signal: string) => {
logger.log(`[NapCat] [Process] 收到${signal}信号,正在关闭...`);
const shutdown = () => {
isShuttingDown = true;
if (currentWorker) {
currentWorker.postMessage({ type: 'shutdown' });
setTimeout(() => {
@@ -233,8 +269,8 @@ async function startMasterProcess (): Promise<void> {
}
};
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown());
process.on('SIGTERM', () => shutdown());
}
/**
@@ -245,20 +281,25 @@ async function startWorkerProcess (): Promise<void> {
throw new Error('进程管理器未初始化');
}
const processType = getProcessTypeName();
logger.log(`[NapCat] [${processType}] Worker进程启动PID: ${process.pid}`);
// 预加载 Node Addon如果设置了环境变量
const preloadAddonPath = process.env['NAPCAT_PRELOAD_NODE_ADDON_PATH'];
if (preloadAddonPath) {
try {
const os = await import('os');
process.dlopen({ exports: {} }, preloadAddonPath, os.constants.dlopen.RTLD_NOW | os.constants.dlopen.RTLD_GLOBAL);
logger.log(`[NapCat] [Worker] 已预加载 Node Addon: ${preloadAddonPath}`);
} catch (error) {
logger.logError(`[NapCat] [Worker] 预加载 Node Addon 失败: ${preloadAddonPath}`, error);
}
}
// 监听来自父进程的消息
processManager.onParentMessage((msg: unknown) => {
if (typeof msg === 'object' && msg !== null && 'type' in msg) {
if (msg.type === 'restart-prepare') {
logger.log(`[NapCat] [${processType}] 收到重启准备信号,正在主动退出...`);
if (msg.type === 'restart-prepare' || msg.type === 'shutdown') {
setTimeout(() => {
process.exit(0);
}, 100);
} else if (msg.type === 'shutdown') {
logger.log(`[NapCat] [${processType}] 收到关闭信号,正在退出...`);
process.exit(0);
}
}
});
@@ -266,7 +307,11 @@ async function startWorkerProcess (): Promise<void> {
// 注册重启进程函数到 WebUI
WebUiDataRuntime.setRestartProcessCall(async () => {
try {
const success = processManager!.sendToParent({ type: 'restart' });
const success = processManager!.sendToParent({
type: 'restart',
secretKey: AuthHelper.getSecretKey(),
port: webUiRuntimePort,
});
if (success) {
return { result: true, message: '进程重启请求已发送' };
@@ -292,7 +337,6 @@ async function startWorkerProcess (): Promise<void> {
async function main (): Promise<void> {
// 单进程模式:直接启动核心
if (ENV.isMultiProcessDisabled) {
logger.log('[NapCat] [SingleProcess] 多进程模式已禁用,直接启动核心');
await NCoreInitShell();
return;
}
@@ -302,8 +346,6 @@ async function main (): Promise<void> {
processManager = result.manager;
isElectron = result.isElectron;
logger.log(`[NapCat] [Process] 检测到 ${isElectron ? 'Electron' : 'Node.js'} 环境`);
// 根据进程类型启动
if (ENV.isWorkerProcess) {
await startWorkerProcess();

View File

@@ -25,6 +25,7 @@ export interface IWorkerProcess {
kill (): boolean;
on (event: string, listener: (...args: unknown[]) => void): void;
once (event: string, listener: (...args: unknown[]) => void): void;
off (event: string, listener: (...args: unknown[]) => void): void;
}
/**
@@ -60,7 +61,7 @@ class ElectronProcessManager implements IProcessManager {
const child: any = this.utilityProcess.fork(modulePath, args, options);
return {
pid: child.pid as number | undefined,
get pid () { return child.pid as number | undefined; },
stdout: child.stdout as Readable | null,
stderr: child.stderr as Readable | null,
@@ -79,6 +80,10 @@ class ElectronProcessManager implements IProcessManager {
once (event: string, listener: (...args: unknown[]) => void): void {
child.once(event, listener);
},
off (event: string, listener: (...args: unknown[]) => void): void {
child.off(event, listener);
},
};
}
@@ -113,7 +118,7 @@ class NodeProcessManager implements IProcessManager {
const child = this.forkFn(modulePath, args, options as any);
return {
pid: child.pid,
get pid () { return child.pid; },
stdout: child.stdout,
stderr: child.stderr,
@@ -134,6 +139,10 @@ class NodeProcessManager implements IProcessManager {
once (event: string, listener: (...args: unknown[]) => void): void {
child.once(event, listener);
},
off (event: string, listener: (...args: unknown[]) => void): void {
child.off(event, listener);
},
};
}
@@ -164,6 +173,9 @@ export async function createProcessManager (): Promise<{
if (isElectron) {
// @ts-ignore - electron 运行时存在但类型声明可能缺失
const electron = await import('electron');
if (electron.app && !electron.app.isReady()) {
await electron.app.whenReady();
}
return {
manager: new ElectronProcessManager(electron.utilityProcess),
isElectron: true,

View File

@@ -72,7 +72,19 @@ export function setPendingTokenToSend (token: string | null) {
export async function InitPort (parsedConfig: WebUiConfigType): Promise<[string, number, string]> {
try {
await tryUseHost(parsedConfig.host);
const port = await tryUsePort(parsedConfig.port, parsedConfig.host);
const preferredPort = parseInt(process.env['NAPCAT_WEBUI_PREFERRED_PORT'] || '', 10);
let port: number;
if (preferredPort > 0) {
try {
port = await tryUsePort(preferredPort, parsedConfig.host, 0, true);
} catch {
port = await tryUsePort(parsedConfig.port, parsedConfig.host);
}
} else {
port = await tryUsePort(parsedConfig.port, parsedConfig.host);
}
return [parsedConfig.host, port, parsedConfig.token];
} catch (error) {
console.log('host或port不可用', error);
@@ -356,7 +368,7 @@ async function tryUseHost (host: string): Promise<string> {
});
}
async function tryUsePort (port: number, host: string, tryCount: number = 0): Promise<number> {
async function tryUsePort (port: number, host: string, tryCount: number = 0, singleTry: boolean = false): Promise<number> {
return new Promise((resolve, reject) => {
try {
const server = net.createServer();
@@ -367,9 +379,12 @@ async function tryUsePort (port: number, host: string, tryCount: number = 0): Pr
server.on('error', (err: any) => {
if (err.code === 'EADDRINUSE') {
if (tryCount < MAX_PORT_TRY) {
// 使用循环代替递归
resolve(tryUsePort(port + 1, host, tryCount + 1));
if (singleTry) {
// 只尝试一次,端口被占用则直接失败
reject(new Error(`端口 ${port} 已被占用`));
} else if (tryCount < MAX_PORT_TRY) {
// 递归尝试下一个端口
resolve(tryUsePort(port + 1, host, tryCount + 1, false));
} else {
reject(new Error(`端口尝试失败,达到最大尝试次数: ${MAX_PORT_TRY}`));
}

View File

@@ -4,7 +4,7 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { WebUiConfig } from '@/napcat-webui-backend/index';
import { getLatestTag, getAllTags, compareSemVer } from 'napcat-common/src/helper';
import { getLatestActionArtifacts } from '@/napcat-common/src/mirror';
import { getLatestActionArtifacts, getMirrorConfig } from '@/napcat-common/src/mirror';
import { NapCatCoreWorkingEnv } from '@/napcat-webui-backend/src/types';
export const GetNapCatVersion: RequestHandler = (_, res) => {
@@ -35,6 +35,7 @@ export interface VersionInfo {
size?: number;
workflowRunId?: number;
headSha?: string;
workflowTitle?: string;
}
/**
@@ -47,11 +48,17 @@ export const getAllReleasesHandler: RequestHandler = async (req, res) => {
const pageSize = parseInt(req.query['pageSize'] as string) || 20;
const typeFilter = req.query['type'] as string | undefined; // 'release' | 'action' | 'all'
const searchQuery = (req.query['search'] as string || '').toLowerCase().trim();
const mirror = req.query['mirror'] as string | undefined;
let versions: VersionInfo[] = [];
let actionVersions: VersionInfo[] = [];
let usedMirror = '';
// If mirror is specified, report it as used (will be confirmed by actual fetching response)
if (mirror) {
usedMirror = mirror;
}
// 懒加载:只获取需要的版本类型
const needReleases = !typeFilter || typeFilter === 'all' || typeFilter === 'release';
const needActions = typeFilter === 'action' || typeFilter === 'all';
@@ -59,9 +66,12 @@ export const getAllReleasesHandler: RequestHandler = async (req, res) => {
// 获取正式版本(仅当需要时)
if (needReleases) {
try {
const result = await getAllTags();
usedMirror = result.mirror;
const result = await getAllTags(mirror);
// 如果没有指定镜像,使用实际上使用的镜像
if (!mirror) {
usedMirror = result.mirror;
}
versions = result.tags.map(tag => {
const isPrerelease = /-(alpha|beta|rc|dev|pre|snapshot)/i.test(tag);
return {
@@ -81,14 +91,19 @@ export const getAllReleasesHandler: RequestHandler = async (req, res) => {
// 获取 Action Artifacts仅当需要时
if (needActions) {
try {
const artifacts = await getLatestActionArtifacts('NapNeko', 'NapCatQQ', 'build.yml', 'main');
const { artifacts, mirror: actionMirror } = await getLatestActionArtifacts('NapNeko', 'NapCatQQ', 'build.yml', 'main', 10, mirror);
// 根据当前工作环境自动过滤对应的 artifact 类型
const isFramework = WebUiDataRuntime.getWorkingEnv() === NapCatCoreWorkingEnv.Framework;
const targetArtifactName = isFramework ? 'NapCat.Framework' : 'NapCat.Shell';
// 如果没有指定镜像,且 action 实际上用了一个镜像(自动选择的),更新 usedMirror
if (!mirror && actionMirror) {
usedMirror = actionMirror;
}
actionVersions = artifacts
.filter(a => a.name === targetArtifactName)
.filter(a => a && a.name === targetArtifactName)
.map(a => ({
tag: `action-${a.id}`,
type: 'action' as const,
@@ -99,6 +114,7 @@ export const getAllReleasesHandler: RequestHandler = async (req, res) => {
size: a.size_in_bytes,
workflowRunId: a.workflow_run_id,
headSha: a.head_sha,
workflowTitle: a.workflow_title,
}));
} catch {
// 获取失败时返回空列表
@@ -114,7 +130,9 @@ export const getAllReleasesHandler: RequestHandler = async (req, res) => {
allVersions = allVersions.filter(v => {
const tagMatch = v.tag.toLowerCase().includes(searchQuery);
const nameMatch = v.artifactName?.toLowerCase().includes(searchQuery);
return tagMatch || nameMatch;
const titleMatch = v.workflowTitle?.toLowerCase().includes(searchQuery);
const shaMatch = v.headSha?.toLowerCase().includes(searchQuery);
return tagMatch || nameMatch || titleMatch || shaMatch;
});
}
@@ -155,3 +173,8 @@ export const SetThemeConfigHandler: RequestHandler = async (req, res) => {
await WebUiConfig.UpdateTheme(theme);
sendSuccess(res, { message: '更新成功' });
};
export const GetMirrorsHandler: RequestHandler = (_, res) => {
const config = getMirrorConfig();
sendSuccess(res, { mirrors: config.fileMirrors });
};

View File

@@ -0,0 +1,225 @@
import { RequestHandler } from 'express';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
import { OB11PluginMangerAdapter } from '@/napcat-onebot/network/plugin-manger';
import path from 'path';
import fs from 'fs';
// Helper to get the plugin manager adapter
const getPluginManager = (): OB11PluginMangerAdapter | null => {
const ob11 = WebUiDataRuntime.getOneBotContext() as NapCatOneBot11Adapter;
if (!ob11) return null;
return ob11.networkManager.findSomeAdapter('plugin_manager') as OB11PluginMangerAdapter;
};
export const GetPluginListHandler: RequestHandler = async (_req, res) => {
const pluginManager = getPluginManager();
if (!pluginManager) {
return sendError(res, 'Plugin Manager not found');
}
// 辅助函数:根据文件名/路径生成唯一ID作为配置键
const getPluginId = (fsName: string, isFile: boolean): string => {
if (isFile) {
return path.parse(fsName).name;
}
return fsName;
};
const loadedPlugins = pluginManager.getLoadedPlugins();
const loadedPluginMap = new Map<string, any>(); // Map ID -> Loaded Info
// 1. 整理已加载的插件
for (const p of loadedPlugins) {
// 计算 ID需要回溯到加载时的入口信息
// 对于已加载的插件,我们通过判断 pluginPath 是否等于根 pluginPath 来判断它是单文件还是目录
const isFilePlugin = p.pluginPath === pluginManager.getPluginPath();
const fsName = isFilePlugin ? path.basename(p.entryPath) : path.basename(p.pluginPath);
const id = getPluginId(fsName, isFilePlugin);
loadedPluginMap.set(id, {
name: p.packageJson?.name || p.name, // 优先使用 package.json 的 name
id: id,
version: p.version || '0.0.0',
description: p.packageJson?.description || '',
author: p.packageJson?.author || '',
status: 'active',
filename: fsName, // 真实文件/目录名
loadedName: p.name // 运行时注册的名称,用于重载/卸载
});
}
const pluginPath = pluginManager.getPluginPath();
const pluginConfig = pluginManager.getPluginConfig();
const allPlugins: any[] = [];
// 2. 扫描文件系统,合并状态
if (fs.existsSync(pluginPath)) {
const items = fs.readdirSync(pluginPath, { withFileTypes: true });
for (const item of items) {
let id = '';
if (item.isFile()) {
if (!['.js', '.mjs'].includes(path.extname(item.name))) continue;
id = getPluginId(item.name, true);
} else if (item.isDirectory()) {
id = getPluginId(item.name, false);
} else {
continue;
}
const isActiveConfig = pluginConfig[id] !== false; // 默认为 true
if (loadedPluginMap.has(id)) {
// 已加载,使用加载的信息
const loadedInfo = loadedPluginMap.get(id);
allPlugins.push(loadedInfo);
} else {
// 未加载 (可能是被禁用,或者加载失败,或者新增未运行)
let version = '0.0.0';
let description = '';
let author = '';
// 默认显示名称为 ID (文件名/目录名)
let name = id;
try {
// 尝试读取 package.json 获取信息
if (item.isDirectory()) {
const packageJsonPath = path.join(pluginPath, item.name, 'package.json');
if (fs.existsSync(packageJsonPath)) {
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
version = pkg.version || version;
description = pkg.description || description;
author = pkg.author || author;
// 如果 package.json 有 name优先使用
name = pkg.name || name;
}
}
} catch (e) { }
allPlugins.push({
name: name,
id: id,
version,
description,
author,
// 如果配置是 false则为 disabled否则是 stopped (应启动但未启动)
status: isActiveConfig ? 'stopped' : 'disabled',
filename: item.name
});
}
}
}
return sendSuccess(res, allPlugins);
};
export const ReloadPluginHandler: RequestHandler = async (req, res) => {
const { name } = req.body;
// Note: we should probably accept ID or Name. But ReloadPlugin uses valid loaded name.
// Let's stick to name for now, but be aware of ambiguity.
if (!name) return sendError(res, 'Plugin Name is required');
const pluginManager = getPluginManager();
if (!pluginManager) {
return sendError(res, 'Plugin Manager not found');
}
const success = await pluginManager.reloadPlugin(name);
if (success) {
return sendSuccess(res, { message: 'Reloaded successfully' });
} else {
return sendError(res, 'Failed to reload plugin');
}
};
export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
const { enable, filename } = req.body;
// We Use filename / id to control config
// Front-end should pass the 'filename' or 'id' as the key identifier
if (!filename) return sendError(res, 'Plugin Filename/ID is required');
const pluginManager = getPluginManager();
if (!pluginManager) {
return sendError(res, 'Plugin Manager not found');
}
// Calculate ID from filename (remove ext if file)
// Or just use the logic consistent with loadPlugins
let id = filename;
// If it has extension .js/.mjs, remove it to get the ID used in config
if (filename.endsWith('.js') || filename.endsWith('.mjs')) {
id = path.parse(filename).name;
}
try {
pluginManager.setPluginStatus(id, enable);
// If enabling, trigger load
if (enable) {
const pluginPath = pluginManager.getPluginPath();
const fullPath = path.join(pluginPath, filename);
if (fs.statSync(fullPath).isDirectory()) {
await pluginManager.loadDirectoryPlugin(filename);
} else {
await pluginManager.loadFilePlugin(filename);
}
} else {
// Disabling is handled inside setPluginStatus usually if implemented,
// OR we can explicitly unload here using the loaded name.
// The Manager's setPluginStatus implementation (if added) might logic this out.
// But our current Manager implementation just saves config.
// Wait, I updated Manager to try to unload.
// Let's rely on Manager's setPluginStatus or do it here?
// I implemented a basic unload loop in Manager.setPluginStatus.
}
return sendSuccess(res, { message: 'Status updated successfully' });
} catch (e: any) {
return sendError(res, 'Failed to update status: ' + e.message);
}
};
export const UninstallPluginHandler: RequestHandler = async (req, res) => {
const { name, filename } = req.body;
// If it's loaded, we use name. If it's disabled, we might use filename.
const pluginManager = getPluginManager();
if (!pluginManager) {
return sendError(res, 'Plugin Manager not found');
}
// Check if loaded
const plugin = pluginManager.getPluginInfo(name);
let fsPath = '';
if (plugin) {
// Active plugin
await pluginManager.unregisterPlugin(name);
if (plugin.pluginPath === pluginManager.getPluginPath()) {
fsPath = plugin.entryPath;
} else {
fsPath = plugin.pluginPath;
}
} else {
// Disabled or not loaded
if (filename) {
fsPath = path.join(pluginManager.getPluginPath(), filename);
} else {
return sendError(res, 'Plugin not found, provide filename if disabled');
}
}
try {
if (fs.existsSync(fsPath)) {
fs.rmSync(fsPath, { recursive: true, force: true });
}
return sendSuccess(res, { message: 'Uninstalled successfully' });
} catch (e: any) {
return sendError(res, 'Failed to uninstall: ' + e.message);
}
};

View File

@@ -20,6 +20,8 @@ interface UpdateRequestBody {
targetVersion?: string;
/** 是否强制更新(即使是降级也更新) */
force?: boolean;
/** 指定使用的镜像 */
mirror?: string;
}
// 更新配置文件接口
@@ -124,7 +126,7 @@ async function downloadFile (url: string, dest: string): Promise<void> {
export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
try {
// 从请求体获取目标版本(可选)
const { targetVersion, force } = req.body as UpdateRequestBody;
const { targetVersion, force, mirror } = req.body as UpdateRequestBody;
// 确定要下载的文件名
const ReleaseName = WebUiDataRuntime.getWorkingEnv() === NapCatCoreWorkingEnv.Framework ? 'NapCat.Framework.zip' : 'NapCat.Shell.zip';
@@ -150,20 +152,21 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
// 根据当前工作环境确定 artifact 名称
const artifactName = ReleaseName.replace('.zip', ''); // NapCat.Framework 或 NapCat.Shell
// Action artifacts 通过 nightly.link 下载
// 格式https://nightly.link/{owner}/{repo}/actions/runs/{run_id}/{artifact_name}.zip
const baseUrl = `https://nightly.link/NapNeko/NapCatQQ/actions/runs/${runId}/${artifactName}.zip`;
actualVersion = targetTag;
webUiLogger?.log(`[NapCat Update] Action artifact URL: ${baseUrl}`);
// 使用 mirror 模块查找可用的 nightly.link 镜像
try {
downloadUrl = await findAvailableDownloadUrl(baseUrl, {
validateContent: true,
minFileSize: 1024 * 1024,
timeout: 10000,
customMirror: mirror,
});
webUiLogger?.log(`[NapCat Update] Using download URL: ${downloadUrl}`);
} catch (error) {
@@ -178,6 +181,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
const release = await getGitHubRelease('NapNeko', 'NapCatQQ', targetTag, {
assetNames: [ReleaseName, 'NapCat.Framework.zip', 'NapCat.Shell.zip'],
fetchChangelog: false, // 不需要 changelog避免 API 调用
mirror,
});
const shellZipAsset = release.assets.find(asset => asset.name === ReleaseName);
@@ -193,6 +197,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
validateContent: true, // 验证 Content-Type 和状态码
minFileSize: 1024 * 1024, // 最小 1MB确保不是错误页面
timeout: 10000, // 10秒超时
customMirror: mirror,
});
}

View File

@@ -4,6 +4,10 @@ import type { WebUiCredentialJson, WebUiCredentialInnerJson } from '@/napcat-web
export class AuthHelper {
private static readonly secretKey = process.env['NAPCAT_WEBUI_JWT_SECRET_KEY'] || Math.random().toString(36).slice(2);
public static getSecretKey (): string {
return AuthHelper.secretKey;
}
/**
* 签名凭证方法。
* @param hash 待签名的凭证字符串。

View File

@@ -1,5 +1,5 @@
import { Router } from 'express';
import { GetThemeConfigHandler, GetNapCatVersion, QQVersionHandler, SetThemeConfigHandler, getLatestTagHandler, getAllReleasesHandler } from '../api/BaseInfo';
import { GetThemeConfigHandler, GetNapCatVersion, QQVersionHandler, SetThemeConfigHandler, getLatestTagHandler, getAllReleasesHandler, GetMirrorsHandler } from '../api/BaseInfo';
import { StatusRealTimeHandler } from '@/napcat-webui-backend/src/api/Status';
import { GetProxyHandler } from '../api/Proxy';
@@ -9,6 +9,7 @@ router.get('/QQVersion', QQVersionHandler);
router.get('/GetNapCatVersion', GetNapCatVersion);
router.get('/getLatestTag', getLatestTagHandler);
router.get('/getAllReleases', getAllReleasesHandler);
router.get('/getMirrors', GetMirrorsHandler);
router.get('/GetSysStatusRealTime', StatusRealTimeHandler);
router.get('/proxy', GetProxyHandler);
router.get('/Theme', GetThemeConfigHandler);

View File

@@ -0,0 +1,11 @@
import { Router } from 'express';
import { GetPluginListHandler, ReloadPluginHandler, SetPluginStatusHandler, UninstallPluginHandler } from '@/napcat-webui-backend/src/api/Plugin';
const router = Router();
router.get('/List', GetPluginListHandler);
router.post('/Reload', ReloadPluginHandler);
router.post('/SetStatus', SetPluginStatusHandler);
router.post('/Uninstall', UninstallPluginHandler);
export { router as PluginRouter };

View File

@@ -17,6 +17,7 @@ import { WebUIConfigRouter } from './WebUIConfig';
import { UpdateNapCatRouter } from './UpdateNapCat';
import DebugRouter from '@/napcat-webui-backend/src/api/Debug';
import { ProcessRouter } from './Process';
import { PluginRouter } from './Plugin';
const router = Router();
@@ -47,5 +48,7 @@ router.use('/UpdateNapCat', UpdateNapCatRouter);
router.use('/Debug', DebugRouter);
// router:进程管理相关路由
router.use('/Process', ProcessRouter);
// router:插件管理相关路由
router.use('/Plugin', PluginRouter);
export { router as ALLRouter };

View File

@@ -25,6 +25,7 @@ const FileManagerPage = lazy(() => import('@/pages/dashboard/file_manager'));
const LogsPage = lazy(() => import('@/pages/dashboard/logs'));
const NetworkPage = lazy(() => import('@/pages/dashboard/network'));
const TerminalPage = lazy(() => import('@/pages/dashboard/terminal'));
const PluginPage = lazy(() => import('@/pages/dashboard/plugin'));
function App () {
return (
@@ -42,7 +43,7 @@ function App () {
);
}
function AuthChecker ({ children }: { children: React.ReactNode }) {
function AuthChecker ({ children }: { children: React.ReactNode; }) {
const { isAuth } = useAuth();
const navigate = useNavigate();
@@ -76,6 +77,7 @@ function AppRoutes () {
</Route>
<Route path='file_manager' element={<FileManagerPage />} />
<Route path='terminal' element={<TerminalPage />} />
<Route path='plugins' element={<PluginPage />} />
<Route path='about' element={<AboutPage />} />
</Route>
<Route path='/qq_login' element={<QQLoginPage />} />

View File

@@ -93,7 +93,7 @@ const NetworkDisplayCard = <T extends keyof NetworkType> ({
onPress={handleEnableDebug}
isDisabled={editing}
>
{debug ? '关闭调试' : '开启调试'}
{debug ? '默认' : '调试'}
</Button>
<Button
fullWidth

View File

@@ -0,0 +1,127 @@
import { Button } from '@heroui/button';
import { Switch } from '@heroui/switch';
import { Chip } from '@heroui/chip';
import { useState } from 'react';
import { MdDeleteForever, MdPublishedWithChanges } from 'react-icons/md';
import DisplayCardContainer from './container';
import { PluginItem } from '@/controllers/plugin_manager';
export interface PluginDisplayCardProps {
data: PluginItem;
onReload: () => Promise<void>;
onToggleStatus: () => Promise<void>;
onUninstall: () => Promise<void>;
}
const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
data,
onReload,
onToggleStatus,
onUninstall,
}) => {
const { name, version, author, description, status } = data;
const isEnabled = status !== 'disabled';
const [processing, setProcessing] = useState(false);
const handleToggle = () => {
setProcessing(true);
onToggleStatus().finally(() => setProcessing(false));
};
const handleReload = () => {
setProcessing(true);
onReload().finally(() => setProcessing(false));
};
const handleUninstall = () => {
setProcessing(true);
onUninstall().finally(() => setProcessing(false));
};
return (
<DisplayCardContainer
className='w-full max-w-[420px]'
action={
<div className='flex gap-2 w-full'>
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-primary/20 hover:text-primary transition-colors'
startContent={<MdPublishedWithChanges size={16} />}
onPress={handleReload}
isDisabled={!isEnabled || processing}
>
</Button>
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-danger/20 hover:text-danger transition-colors'
startContent={<MdDeleteForever size={16} />}
onPress={handleUninstall}
isDisabled={processing}
>
</Button>
</div>
}
enableSwitch={
<Switch
isDisabled={processing}
isSelected={isEnabled}
onChange={handleToggle}
classNames={{
wrapper: 'group-data-[selected=true]:bg-primary-400',
}}
/>
}
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>
<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>
);
};
export default PluginDisplayCard;

View File

@@ -45,7 +45,7 @@ const SystemInfoItem: React.FC<SystemInfoItemProps> = ({
return (
<div
className={clsx(
'flex text-sm gap-3 py-2 items-center transition-colors',
'flex text-sm gap-3 py-2 items-baseline transition-colors',
hasBackground
? 'text-white/90'
: 'text-default-600 dark:text-gray-300',
@@ -53,13 +53,13 @@ const SystemInfoItem: React.FC<SystemInfoItemProps> = ({
)}
onClick={onClick}
>
<div className="text-lg opacity-70">{icon}</div>
<div className="text-lg opacity-70 self-center">{icon}</div>
<div className='w-24 font-medium'>{title}</div>
<div className={clsx(
'text-xs font-mono flex-1',
hasBackground ? 'text-white/80' : 'text-default-500'
)}>{value}</div>
<div>{endContent}</div>
<div className="self-center">{endContent}</div>
</div>
);
};
@@ -84,9 +84,11 @@ const UpdateDialogContent: React.FC<{
<div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-6 py-8 bg-default-50 dark:bg-default-100/5 rounded-xl border border-default-100 dark:border-default-100/10">
<div className="flex flex-col items-center gap-2 min-w-0 w-full sm:w-auto">
<span className="text-xs text-default-500 font-medium uppercase tracking-wider"></span>
<Chip size="lg" variant="flat" color="default" classNames={{ content: "font-mono font-bold text-base sm:text-lg break-all whitespace-normal text-center h-auto py-1" }}>
v{currentVersion}
</Chip>
<Tooltip content={`v${currentVersion}`}>
<Chip size="md" variant="flat" color="default" classNames={{ content: "font-mono font-bold text-sm truncate max-w-[120px] sm:max-w-[160px]" }}>
v{currentVersion}
</Chip>
</Tooltip>
</div>
<div className="flex flex-col items-center text-primary-500 px-4 shrink-0">
@@ -99,9 +101,11 @@ const UpdateDialogContent: React.FC<{
<div className="flex flex-col items-center gap-2 min-w-0 w-full sm:w-auto">
<span className="text-xs text-primary-500 font-medium uppercase tracking-wider"></span>
<Chip size="lg" color="primary" variant="shadow" classNames={{ content: "font-mono font-bold text-base sm:text-lg break-all whitespace-normal text-center h-auto py-1" }}>
v{latestVersion}
</Chip>
<Tooltip content={`v${latestVersion}`}>
<Chip size="md" color="primary" variant="shadow" classNames={{ content: "font-mono font-bold text-sm truncate max-w-[120px] sm:max-w-[160px]" }}>
v{latestVersion}
</Chip>
</Tooltip>
</div>
</div>
@@ -136,13 +140,21 @@ const UpdateDialogContent: React.FC<{
</p>
</div>
<div className='mt-2 p-3 rounded-lg bg-warning-50/50 dark:bg-warning-900/20 border border-warning-200/50 dark:border-warning-700/30'>
<p className='text-xs text-warning-700 dark:text-warning-400 flex items-center gap-1'>
<p className='text-xs text-warning-700 dark:text-warning-400 flex items-center gap-1 justify-center'>
<svg className='w-4 h-4' fill='none' viewBox='0 0 24 24' stroke='currentColor'>
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z' />
</svg>
<span> NapCat</span>
<span> NapCat </span>
</p>
</div>
<div className='flex gap-3 justify-center mt-2 w-full'>
<button
className='px-4 py-2 text-sm rounded-lg bg-primary-500 hover:bg-primary-600 text-white shadow-sm transition-colors shadow-primary-500/20 w-full'
onClick={() => WebUIManager.restart()}
>
</button>
</div>
</div>
)}
@@ -241,17 +253,17 @@ const NewVersionTip = (props: NewVersionTipProps) => {
return (
<Tooltip content='有新版本可用'>
<div className="cursor-pointer" onClick={updateStatus === 'updating' ? undefined : showUpdateDialog}>
<div className="cursor-pointer flex items-center justify-center" onClick={updateStatus === 'updating' ? undefined : showUpdateDialog}>
<Chip
size="sm"
color="danger"
variant="flat"
classNames={{
content: "font-bold text-[10px] px-1",
base: "h-5 min-h-5"
content: "font-bold text-[10px] px-1 flex items-center justify-center",
base: "h-5 min-h-5 min-w-[42px]"
}}
>
{updateStatus === 'updating' ? <Spinner size="sm" color="danger" /> : 'New'}
{updateStatus === 'updating' ? <Spinner size="sm" color="danger" classNames={{ wrapper: "w-3 h-3" }} /> : 'New'}
</Chip>
</div>
</Tooltip>
@@ -269,6 +281,7 @@ interface VersionInfo {
size?: number;
workflowRunId?: number;
headSha?: string;
workflowTitle?: string;
}
// 版本选择对话框内容
@@ -290,6 +303,14 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
const [activeTab, setActiveTab] = useState<'release' | 'action'>('release');
const [searchQuery, setSearchQuery] = useState('');
const debouncedSearch = useDebounce(searchQuery, 300);
const [selectedMirror, setSelectedMirror] = useState<string | undefined>(undefined);
const { data: mirrorsData } = useRequest(WebUIManager.getMirrors, {
cacheKey: 'napcat-mirrors',
staleTime: 60 * 60 * 1000,
});
const mirrors = mirrorsData?.mirrors || [];
const pageSize = 15;
// 获取所有可用版本(带分页、过滤和搜索)
@@ -299,15 +320,16 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
page: currentPage,
pageSize,
type: activeTab,
search: debouncedSearch
search: debouncedSearch,
mirror: selectedMirror
}),
{
refreshDeps: [currentPage, activeTab, debouncedSearch],
refreshDeps: [currentPage, activeTab, debouncedSearch, selectedMirror],
}
);
// 版本列表已在后端过滤,直接使用
const filteredVersions = releasesData?.versions || [];
const filteredVersions = (releasesData?.versions || []) as VersionInfo[];
// 检查是否是降级(使用语义化版本比较)
const isDowngrade = useCallback((targetTag: string): boolean => {
@@ -320,6 +342,22 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
const selectedVersionTag = selectedVersion?.tag || '';
const isSelectedDowngrade = isDowngrade(selectedVersionTag);
const performUpdate = async (force: boolean) => {
if (!selectedVersion) return;
setUpdateStatus('updating');
setErrorMessage('');
try {
await WebUIManager.UpdateNapCatToVersion(selectedVersionTag, force, selectedMirror);
setUpdateStatus('success');
} catch (err) {
console.error('Update failed:', err);
const errMsg = err instanceof Error ? err.message : '未知错误';
setErrorMessage(errMsg);
setUpdateStatus('error');
}
};
const handleUpdate = async () => {
if (!selectedVersion) return;
@@ -346,22 +384,6 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
await performUpdate(forceUpdate);
};
const performUpdate = async (force: boolean) => {
if (!selectedVersion) return;
setUpdateStatus('updating');
setErrorMessage('');
try {
await WebUIManager.UpdateNapCatToVersion(selectedVersionTag, force);
setUpdateStatus('success');
} catch (err) {
console.error('Update failed:', err);
const errMsg = err instanceof Error ? err.message : '未知错误';
setErrorMessage(errMsg);
setUpdateStatus('error');
}
};
// 处理分页变化
const handlePageChange = (page: number) => {
setCurrentPage(page);
@@ -375,13 +397,30 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M5 13l4 4L19 7' />
</svg>
</div>
<div className='text-center'>
<div className='text-center w-full'>
<p className='text-sm font-medium text-success-600 dark:text-success-400'>
{selectedVersionTag}
</p>
<p className='text-xs text-default-500 mt-1'>
<p className='text-xs text-default-500 mt-1 mb-6'>
NapCat
</p>
<div className='flex gap-3 justify-center'>
<button
className='px-4 py-2 text-sm rounded-lg bg-default-100 hover:bg-default-200 transition-colors text-default-700'
onClick={onClose}
>
</button>
<button
className='px-4 py-2 text-sm rounded-lg bg-primary-500 hover:bg-primary-600 text-white shadow-sm transition-colors shadow-primary-500/20'
onClick={async () => {
await WebUIManager.restart();
onClose();
}}
>
</button>
</div>
</div>
</div>
);
@@ -463,23 +502,46 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
<Tab key='action' title='临时版本 (Action)' />
</Tabs>
{/* 搜索框 */}
<Input
placeholder='搜索版本号...'
size='sm'
value={searchQuery}
onValueChange={(value) => {
setSearchQuery(value);
setCurrentPage(1);
setSelectedVersion(null);
}}
startContent={<IoSearch className='text-default-400' />}
isClearable
onClear={() => setSearchQuery('')}
classNames={{
inputWrapper: 'h-9',
}}
/>
<div className="flex gap-2">
{/* 搜索框 */}
<Input
placeholder='搜索版本号...'
size='sm'
value={searchQuery}
onValueChange={(value) => {
setSearchQuery(value);
setCurrentPage(1);
setSelectedVersion(null);
}}
startContent={<IoSearch className='text-default-400' />}
isClearable
onClear={() => setSearchQuery('')}
classNames={{
inputWrapper: 'h-9',
base: 'flex-1'
}}
/>
{/* 镜像选择 */}
<Select
placeholder="自动选择 (默认)"
selectedKeys={selectedMirror ? [selectedMirror] : ['default']}
onSelectionChange={(keys) => {
const m = Array.from(keys)[0] as string;
setSelectedMirror(m === 'default' ? undefined : m);
}}
size="sm"
className="w-48"
classNames={{ trigger: 'h-9 min-h-9' }}
aria-label="选择镜像源"
>
{['default', ...mirrors].map(m => (
<SelectItem key={m} textValue={m === 'default' ? '自动选择' : m}>
{m === 'default' ? '自动选择 (默认)' : m}
</SelectItem>
))}
</Select>
</div>
{/* 版本选择 */}
<div className='space-y-2'>
@@ -528,7 +590,12 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
>
<div className='flex flex-col gap-0.5'>
<div className='flex items-center gap-2'>
<span>{version.type === 'action' && version.artifactName ? version.artifactName : version.tag}</span>
<span className="truncate max-w-[300px]">
{version.type === 'action'
? (version.workflowTitle || version.artifactName || version.tag)
: version.tag
}
</span>
{version.type === 'prerelease' && (
<Chip size='sm' color='secondary' variant='flat'></Chip>
)}
@@ -543,10 +610,11 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
)}
</div>
{version.type === 'action' && (
<div className='text-xs text-default-400'>
{version.headSha && <span className='font-mono'>{version.headSha.slice(0, 7)}</span>}
{version.createdAt && <span className='ml-2'>{new Date(version.createdAt).toLocaleString()}</span>}
{version.size && <span className='ml-2'>{(version.size / 1024 / 1024).toFixed(1)} MB</span>}
<div className='text-xs text-default-400 flex items-center gap-2'>
<span className='font-mono bg-default-100 dark:bg-default-100/10 px-1 rounded'>{version.tag}</span>
{version.headSha && <span className='font-mono' title={version.headSha}>{version.headSha.slice(0, 7)}</span>}
{version.createdAt && <span>{new Date(version.createdAt).toLocaleString()}</span>}
{version.size && <span>{(version.size / 1024 / 1024).toFixed(1)} MB</span>}
</div>
)}
</div>
@@ -568,6 +636,7 @@ const VersionSelectDialogContent: React.FC<VersionSelectDialogProps> = ({
</span>
)}
</p>
</div>
)}

View File

@@ -29,7 +29,7 @@ const SystemStatusItem: React.FC<SystemStatusItemProps> = ({
<div
className={clsx(
'py-1.5 text-sm transition-colors',
size === 'lg' ? 'col-span-2' : 'col-span-1 flex justify-between',
size === 'lg' ? 'col-span-2' : 'col-span-1 flex justify-between items-center',
)}
>
<div className={clsx(

View File

@@ -8,6 +8,7 @@ import {
LuSignal,
LuTerminal,
LuZap,
LuPackage,
} from 'react-icons/lu';
export type SiteConfig = typeof siteConfig;
@@ -59,6 +60,11 @@ export const siteConfig = {
icon: <LuFolderOpen className='w-5 h-5' />,
href: '/file_manager',
},
{
label: '插件管理',
icon: <LuPackage className='w-5 h-5' />,
href: '/plugins',
},
{
label: '系统终端',
icon: <LuTerminal className='w-5 h-5' />,

View File

@@ -61,7 +61,8 @@ const messageNode = z.union([
.object({
type: z.literal('reply'),
data: z.object({
id: z.number(),
id: z.number().optional(),
seq: z.number().optional(),
}),
})
.describe('回复消息'),

View File

@@ -0,0 +1,35 @@
import { serverRequest } from '@/utils/request';
export interface PluginItem {
name: string;
version: string;
description: string;
author: string;
status: 'active' | 'disabled' | 'stopped';
filename?: string;
}
export interface ServerResponse<T> {
code: number;
message: string;
data: T;
}
export default class PluginManager {
public static async getPluginList () {
const { data } = await serverRequest.get<ServerResponse<PluginItem[]>>('/Plugin/List');
return data.data;
}
public static async reloadPlugin (name: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Reload', { name });
}
public static async setPluginStatus (name: string, enable: boolean, filename?: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/SetStatus', { name, enable, filename });
}
public static async uninstallPlugin (name: string, filename?: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { name, filename });
}
}

View File

@@ -72,8 +72,9 @@ export default class WebUIManager {
pageSize?: number;
type?: 'release' | 'action' | 'all';
search?: string;
mirror?: string;
} = {}) {
const { page = 1, pageSize = 20, type = 'release', search = '' } = options;
const { page = 1, pageSize = 20, type = 'release', search = '', mirror } = options;
const { data } = await serverRequest.get<ServerResponse<{
versions: Array<{
tag: string;
@@ -94,15 +95,21 @@ export default class WebUIManager {
};
mirror?: string;
}>>('/base/getAllReleases', {
params: { page, pageSize, type, search },
params: { page, pageSize, type, search, mirror },
});
return data.data;
}
public static async UpdateNapCat () {
public static async getMirrors () {
const { data } =
await serverRequest.get<ServerResponse<{ mirrors: string[]; }>>('/base/getMirrors');
return data.data;
}
public static async UpdateNapCat (mirror?: string) {
const { data } = await serverRequest.post<ServerResponse<any>>(
'/UpdateNapCat/update',
{},
{ mirror },
{ timeout: 120000 } // 2分钟超时
);
return data;
@@ -112,11 +119,12 @@ export default class WebUIManager {
* 更新到指定版本
* @param targetVersion 目标版本 tag如 "v4.9.9" 或 "action-123456"
* @param force 是否强制更新(允许降级)
* @param mirror 指定使用的镜像
*/
public static async UpdateNapCatToVersion (targetVersion: string, force: boolean = false) {
public static async UpdateNapCatToVersion (targetVersion: string, force: boolean = false, mirror?: string) {
const { data } = await serverRequest.post<ServerResponse<any>>(
'/UpdateNapCat/update',
{ targetVersion, force },
{ targetVersion, force, mirror },
{ timeout: 120000 } // 2分钟超时
);
return data;
@@ -142,6 +150,16 @@ export default class WebUIManager {
return data.data;
}
public static async restart () {
const { data } = await serverRequest.post<ServerResponse<any>>('/Process/Restart');
return data.data;
}
public static async getAllUsers (): Promise<any> {
const { data } = await serverRequest.get<ServerResponse<any>>('/QQLogin/GetAllUsers');
return data.data;
}
public static async getLogList () {
const { data } =
await serverRequest.get<ServerResponse<string[]>>('/Log/GetLogList');

View File

@@ -0,0 +1,115 @@
import { Button } from '@heroui/button';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { IoMdRefresh } from 'react-icons/io';
import PageLoading from '@/components/page_loading';
import PluginDisplayCard from '@/components/display_card/plugin_card';
import PluginManager, { PluginItem } from '@/controllers/plugin_manager';
import useDialog from '@/hooks/use-dialog';
export default function PluginPage () {
const [plugins, setPlugins] = useState<PluginItem[]>([]);
const [loading, setLoading] = useState(false);
const dialog = useDialog();
const loadPlugins = async () => {
setLoading(true);
try {
const data = await PluginManager.getPluginList();
setPlugins(data);
} catch (e: any) {
toast.error(e.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadPlugins();
}, []);
const handleReload = async (name: string) => {
const loadingToast = toast.loading('重载中...');
try {
await PluginManager.reloadPlugin(name);
toast.success('重载成功', { id: loadingToast });
loadPlugins();
} catch (e: any) {
toast.error(e.message, { id: loadingToast });
}
};
const handleToggle = async (plugin: PluginItem) => {
const isEnable = plugin.status !== 'active';
const actionText = isEnable ? '启用' : '禁用';
const loadingToast = toast.loading(`${actionText}中...`);
try {
await PluginManager.setPluginStatus(plugin.name, isEnable, plugin.filename);
toast.success(`${actionText}成功`, { id: loadingToast });
loadPlugins();
} catch (e: any) {
toast.error(e.message, { id: loadingToast });
}
};
const handleUninstall = async (plugin: PluginItem) => {
return new Promise<void>((resolve, reject) => {
dialog.confirm({
title: '卸载插件',
content: `确定要卸载插件「${plugin.name}」吗? 此操作不可恢复。`,
onConfirm: async () => {
const loadingToast = toast.loading('卸载中...');
try {
await PluginManager.uninstallPlugin(plugin.name, plugin.filename);
toast.success('卸载成功', { id: loadingToast });
loadPlugins();
resolve();
} catch (e: any) {
toast.error(e.message, { id: loadingToast });
reject(e);
}
},
onCancel: () => {
resolve();
}
});
});
};
return (
<>
<title> - NapCat WebUI</title>
<div className='p-2 md:p-4 relative'>
<PageLoading loading={loading} />
<div className='flex mb-6 items-center gap-4'>
<h1 className="text-2xl font-bold"></h1>
<Button
isIconOnly
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
radius='full'
onPress={loadPlugins}
>
<IoMdRefresh size={24} />
</Button>
</div>
{plugins.length === 0 ? (
<div className="text-default-400"></div>
) : (
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 justify-start items-stretch gap-x-2 gap-y-4'>
{plugins.map(plugin => (
<PluginDisplayCard
key={plugin.name}
data={plugin}
onReload={() => handleReload(plugin.name)}
onToggleStatus={() => handleToggle(plugin)}
onUninstall={() => handleUninstall(plugin)}
/>
))}
</div>
)}
</div>
</>
);
}

View File

@@ -24,196 +24,197 @@ export type OB11SegmentType =
| 'file';
export interface Segment {
type: OB11SegmentType
type: OB11SegmentType;
}
/** 纯文本 */
export interface TextSegment extends Segment {
type: 'text'
type: 'text';
data: {
text: string
}
text: string;
};
}
/** QQ表情 */
export interface FaceSegment extends Segment {
type: 'face'
type: 'face';
data: {
id: string
}
id: string;
};
}
/** 图片消息段 */
export interface ImageSegment extends Segment {
type: 'image'
type: 'image';
data: {
file: string
type?: 'flash'
url?: string
cache?: 0 | 1
proxy?: 0 | 1
timeout?: number
}
file: string;
type?: 'flash';
url?: string;
cache?: 0 | 1;
proxy?: 0 | 1;
timeout?: number;
};
}
/** 语音消息段 */
export interface RecordSegment extends Segment {
type: 'record'
type: 'record';
data: {
file: string
magic?: 0 | 1
url?: string
cache?: 0 | 1
proxy?: 0 | 1
timeout?: number
}
file: string;
magic?: 0 | 1;
url?: string;
cache?: 0 | 1;
proxy?: 0 | 1;
timeout?: number;
};
}
/** 短视频消息段 */
export interface VideoSegment extends Segment {
type: 'video'
type: 'video';
data: {
file: string
url?: string
cache?: 0 | 1
proxy?: 0 | 1
timeout?: number
}
file: string;
url?: string;
cache?: 0 | 1;
proxy?: 0 | 1;
timeout?: number;
};
}
/** @某人消息段 */
export interface AtSegment extends Segment {
type: 'at'
type: 'at';
data: {
qq: string | 'all'
name?: string
}
qq: string | 'all';
name?: string;
};
}
/** 猜拳魔法表情消息段 */
export interface RpsSegment extends Segment {
type: 'rps'
type: 'rps';
}
/** 掷骰子魔法表情消息段 */
export interface DiceSegment extends Segment {
type: 'dice'
type: 'dice';
}
/** 窗口抖动(戳一戳)消息段 */
export interface ShakeSegment extends Segment {
type: 'shake'
data: object
type: 'shake';
data: object;
}
/** 戳一戳消息段 */
export interface PokeSegment extends Segment {
type: 'poke'
type: 'poke';
data: {
type: string
id: string
name?: string
}
type: string;
id: string;
name?: string;
};
}
/** 匿名发消息消息段 */
export interface AnonymousSegment extends Segment {
type: 'anonymous'
type: 'anonymous';
data: {
ignore?: 0 | 1
}
ignore?: 0 | 1;
};
}
/** 链接分享消息段 */
export interface ShareSegment extends Segment {
type: 'share'
type: 'share';
data: {
url: string
title: string
content?: string
image?: string
}
url: string;
title: string;
content?: string;
image?: string;
};
}
/** 推荐好友/群消息段 */
export interface ContactSegment extends Segment {
type: 'contact'
type: 'contact';
data: {
type: 'qq' | 'group'
id: string
}
type: 'qq' | 'group';
id: string;
};
}
/** 位置消息段 */
export interface LocationSegment extends Segment {
type: 'location'
type: 'location';
data: {
lat: string
lon: string
title?: string
content?: string
}
lat: string;
lon: string;
title?: string;
content?: string;
};
}
/** 音乐分享消息段 */
export interface MusicSegment extends Segment {
type: 'music'
type: 'music';
data: {
type: 'qq' | '163' | 'xm'
id: string
}
type: 'qq' | '163' | 'xm';
id: string;
};
}
/** 音乐自定义分享消息段 */
export interface CustomMusicSegment extends Segment {
type: 'music'
type: 'music';
data: {
type: 'custom'
url: string
audio: string
title: string
content?: string
image?: string
}
type: 'custom';
url: string;
audio: string;
title: string;
content?: string;
image?: string;
};
}
/** 回复消息段 */
export interface ReplySegment extends Segment {
type: 'reply'
type: 'reply';
data: {
id: string
}
id?: string; // msg_id 的短ID映射
seq?: number; // msg_seq优先使用
};
}
export interface FileSegment extends Segment {
type: 'file'
type: 'file';
data: {
file: string
}
file: string;
};
}
/** 合并转发消息段 */
export interface ForwardSegment extends Segment {
type: 'forward'
type: 'forward';
data: {
id: string
}
id: string;
};
}
/** XML消息段 */
export interface XmlSegment extends Segment {
type: 'xml'
type: 'xml';
data: {
data: string
}
data: string;
};
}
/** JSON消息段 */
export interface JsonSegment extends Segment {
type: 'json'
type: 'json';
data: {
data: string
}
data: string;
};
}
/** OneBot11消息段 */
@@ -242,23 +243,23 @@ export type OB11SegmentBase =
/** 合并转发已有消息节点消息段 */
export interface DirectNodeSegment extends Segment {
type: 'node'
type: 'node';
data: {
id: string
}
id: string;
};
}
/** 合并转发自定义节点消息段 */
export interface CustomNodeSegments extends Segment {
type: 'node'
type: 'node';
data: {
user_id: string
nickname: string
content: OB11Segment[]
prompt?: string
summary?: string
source?: string
}
user_id: string;
nickname: string;
content: OB11Segment[];
prompt?: string;
summary?: string;
source?: string;
};
}
/** 合并转发消息段 */

10
pnpm-lock.yaml generated
View File

@@ -220,6 +220,16 @@ importers:
specifier: ^22.0.1
version: 22.19.1
packages/napcat-plugin-builtin:
dependencies:
napcat-onebot:
specifier: workspace:*
version: link:../napcat-onebot
devDependencies:
'@types/node':
specifier: ^22.0.1
version: 22.19.1
packages/napcat-protobuf:
dependencies:
'@protobuf-ts/runtime':