Compare commits

..
67 Commits
Author SHA1 Message Date
五加一5plus1 c75d2f7f86 fix(webui): recover QR login after forced logout (#2030)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-09-14 11:46:32 +08:00
手瓜一十雪 fa3fe9fdb2 Use pnpm setup in release workflow
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
The release publishing workflow now installs pnpm via pnpm/action-setup instead of globally via npm, and applies the same improvement to the APIFox update job. This keeps the workflow consistent and avoids relying on the environment's global pnpm installation.
2026-09-14 11:43:29 +08:00
手瓜一十雪 464bc3d4a7 Revert "Disable npm install scripts"
This reverts commit 3c03b162f5.
2026-09-14 11:38:46 +08:00
手瓜一十雪 3c03b162f5 Disable npm install scripts
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add a project-level .npmrc so npm does not skip package lifecycle scripts during installation. This ensures dependency setup and initialization continue to run as expected.
2026-09-14 11:03:09 +08:00
Shxiao 4079214dc5 fix: Rkey 服务响应缺少必要字段时输出明确错误 (#2044)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
部分内置 Rkey 服务返回 HTTP 200 但响应缺少 group_rkey/private_rkey,
refreshRkey 直接执行 temp.group_rkey.slice(6) 触发
TypeError: Cannot read properties of undefined (reading 'slice'),
报错信息看不出是服务返回结构变化。

在解析前校验响应结构:非对象响应(如 JSON null)不再走 'retcode' in
temp 的原始 TypeError 路径;group_rkey/private_rkey 须为可截去 6 字符
前缀的非空字符串,expired_time 须为正数,无效时按现有失败计数逻辑
禁用该 URL 并抛出明确错误,与其他服务的异常路径保持一致。

Fixes #2010
2026-09-14 10:54:08 +08:00
Shxiao 109d0c1dff fix: 仅当 fork 子进程完整引导 Chromium 时注入 --no-sandbox (#2045)
纯 Node 环境(如 NapCat.Shell.Windows.Node)下 child_process.fork 的
execArgv 会直接传给 node.exe;--no-sandbox 是 Chromium 开关,Node 不识别,
Worker 以退出码 9 (bad option) 启动失败并触发三次重启后主进程退出。

#1984 在非 Electron 路径无条件注入该参数,同样影响以 ELECTRON_RUN_AS_NODE
驱动 Electron 二进制的容器环境:node 模式与上游 Node 一致拒绝未知开关
(该变量存在即触发 node 模式,与取值无关)。

将注入条件从 !isElectron 收窄为「fork 路径 && 宿主为 Electron 二进制 &&
未设 ELECTRON_RUN_AS_NODE」:QQNT 主进程 fork 出的子进程不带
ELECTRON_RUN_AS_NODE、完整引导 Chromium,由 Chromium 解析该参数以规避
proot 沙箱 SIGSEGV,#1984 行为保持不变;纯 Node 路径不再传入,Worker
正常启动,并恢复 fork 对 process.execArgv 的默认继承。

Fixes #2040
2026-09-09 13:38:46 +08:00
Shxiao 96de2314b0 style: 修复主分支现存的 ESLint 错误 (#2046)
- 修复 7 个文件中全部 21 个 ESLint 错误(缩进、注释空格、引号、函数括号空格、三元表达式换行、JSX 缩进)
- dashboard/config/index.tsx 中写在 JSX children 里的 // 注释会被当作文本节点渲染到 WebUI 配置页,改为 JSX 注释
- 验证:npx eslint . 退出码 0;pnpm run typecheck 全部包通过
2026-09-08 18:18:46 +08:00
Darf eecb02140f feat: add get_group_share_link action (NTQQ getJoinGroupLink) (#2041) 2026-09-04 19:25:36 +08:00
yibai 3ac54c181b 更换稳定签名服务器 (#2034)
更换稳定签名服务器,这次更新就不会再动了

Signed-off-by: yibai <160130578+yibainb@users.noreply.github.com>
2026-08-29 21:16:50 +08:00
yibai 0c4c371eee fix: Update music card signature URL
由于思思的音卡签名可能出现问题,测试时已无法使用,特此自建签名api并替换。同时加入备选思思api逻辑

Signed-off-by: yibai <160130578+yibainb@users.noreply.github.com>
2026-08-27 03:48:52 +08:00
手瓜一十雪 af07479351 Add missing QQ face config entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
This update adds the missing QQ face definitions for QSid 450-484 (EMCode 10450-10484) to the external face configuration. It covers newer emoji entries such as /撇嘴, /微笑, /无语, and /学习, aligning the config with the current face set.
2026-08-14 18:58:40 +08:00
手瓜一十雪 c59a47a5a7 Add 9.9.32-55230 appid and napi2native entries
Add support for release 9.9.32-55230: update packages/napcat-core/external/appid.json with Windows appid 537379411 and QUA, and add x64 send/recv mappings to packages/napcat-core/external/napi2native.json to support the new Win x64 build.
2026-08-14 18:36:05 +08:00
手瓜一十雪 49ea8d5624 Strip control & ANSI sequences from logs && fix #1961
Sanitize formatted log messages by removing control characters and ANSI escape sequences when creating the message. Consolidates ANSI/control stripping into the initial message and removes the redundant replace in the file-only logging branch to prevent control/ANSI codes from polluting console or file logs.
2026-08-14 18:25:21 +08:00
DogeCN fe7a1f053a fix: 修复 WebUI 白屏与 arm64/proot 下 Worker SIGSEGV (#1984)
* fix(webui): 合并 react/react-dom/scheduler 到 react-vendor chunk

codemirror-core chunk 从 react-dom chunk 导入 forwardRef(r),
但 react-dom 被 manualChunks 单独拆块后未导出该绑定,
forwardRef 为 undefined 导致 React 初始化崩溃、整页白屏。

将 react/react-dom/scheduler 合并为 react-vendor 块,
消除 React 19 下 chunk 间 forwardRef 跨块断裂。

* fix: Worker 改走 child_process.fork 并传 --no-sandbox(arm64/proot 下避免 UtilityProcess SIGSEGV)

- process-api.ts: ProcessOptions 增加 execArgv 选项;isElectron 增加 NAPCAT_FORCE_NODE_PROCESS 环境变量判断,可强制走 Node 进程管理器
- napcat.ts: Node 进程路径下为 Worker 注入 execArgv: ['--no-sandbox'],规避 arm64/proot 环境 Electron UtilityProcess 崩溃(退出码 11)
- 注:未包含原 commit 中 scripts/install.sh 的 Termux 特定补丁(该文件为 fork 私有,上游不存在)
2026-08-10 11:15:04 +08:00
手瓜一十雪 0fcd0e80e0 Revert "添加自动登录 | feat(login): automatically restore last logged-in account (#1980)"
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
This reverts commit 31c45bf18e.
2026-08-07 17:47:00 +08:00
Chace 624ecf5b9a fix: restore PNG thumbnails for direct video sends (#2000) 2026-08-07 17:47:00 +08:00
叫我饼干ちゃん 63a349d119 添加自动登录 | feat(login): automatically restore last logged-in account (#1980)
* feat(login): automatically restore last logged-in account

* docs(shell): correct quick login argument examples
2026-08-07 17:47:00 +08:00
Leslie Lau 56549cd0f2 fix: report non-latest private message recalls (#1998) 2026-08-07 17:47:00 +08:00
Zizheng Guo ead24423b5 feat(group): add group management APIs (#1996) 2026-08-07 17:46:59 +08:00
Chace f0e045df35 fix: 修复合并转发视频过期及移动端延迟显示问题 (#1983)
* fix: 修复合并转发视频过期问题

* fix: 修复移动端合并转发内容延迟显示问题

* fix: 同步 ffmpegAddon 视频封面处理产物
2026-08-07 17:46:59 +08:00
Airline233 33ee94ab0f feat(qzone): add QQ space message deletion functionality (#1978)
- Add deleteQzoneMsg API method to NTQQWebApi for deleting Qzone posts by tid
- Implement buildQzoneDeleteBody to construct form-encoded request payload
- Implement parseQzoneDeleteResponse to validate deletion API response
- Add QzoneDeleteResponse and QzoneDeleteParams type definitions
- Create DeleteQzoneMsg OneBot action handler with payload validation
- Register delete_qzone_msg action in router and action handlers
- Add example payload and response for DeleteQzoneMsg action
- Add comprehensive unit tests for delete body construction and response parsing
- Fix indentation inconsistency in createAlbumCommentRequest call
2026-08-07 17:46:59 +08:00
Airline233 cbec362ed1 feat(qzone): add QQ space message publishing and image upload (#1965)
- Add QzonePublishResponse interface and parsing logic for publish API responses
- Add buildQzonePublishBody function to construct publish request parameters
- Add buildQzoneUploadImageBody function to construct image upload request parameters
- Add parseQzoneUploadImageResponseText function to parse upload API responses
- Add toQzoneRichval function to format image data for publish requests
- Add publishQzoneMsg method to NTQQWebApi for publishing space messages with optional images
- Add uploadImageToQzone method to NTQQWebApi for uploading images to QQ space
- Add getQzoneAuth private method to retrieve authentication tokens (skey, pskey, g_tk)
- Add SendQzoneMsg action handler to expose QQ space publishing via OneBot API
- Add comprehensive unit tests for all Qzone data construction and parsing functions
- Update action router to register SendQzoneMsg action
- Update action examples to demonstrate Qzone publishing usage
2026-08-07 17:46:58 +08:00
手瓜一十雪 766ca6e071 Update QQNT release download URLs
Refresh the downstream release workflow to use the newer QQNT 3.2.30-50969 AppImage URLs for both x86_64 and arm64 builds.

Update release note prompt and AI model

Clarifies the release note prompt to require strict output format without wrapping the result in a code block. Also updates the release publish workflow to use `google/gemma-4-26b-a4b-it:free` instead of the previous OpenAI model endpoint setting.

Update QQNT installer URL in release workflow

Switches the release publish workflow to download a newer QQNT x64 installer (9.9.32.50969) from the updated qqdl.gtimg.cn source instead of the previous dldir1v6.qq.com link.

Add mappings for QQ 50969 builds

Add appid/QUA entries and native/packet send-recv offsets for the new 9.9.32-50969 Windows build and 3.2.30-50969 Linux x64/arm64 builds. Also normalize the existing 3.2.30-50828 x64 native recv offset format by removing the leading zero.
2026-08-07 17:46:36 +08:00
colGem 7c2514be6c fix: 将显式 group_id 优先级提升至 getTempChatInfo 缓存之前 (#1963)
## 问题
调用 send_private_msg 时,即使显式传入了 group_id 参数以指定通过某个群发起临时会话,由于 createContext() 中 getTempChatInfo(查询旧的临时会话缓存)的优先级高于显式 group_id,导致实际使用的是旧缓存所在群,而非调用方指定的群。

当缓存所在群不允许临时会话时(QQ 错误码 103),即使传入的 group_id 对应的群已开启临时会话,消息发送仍然失败。

## 根因
createContext() 的判断顺序为:
  1. 是好友 → C2C
  2. 不是好友 → getTempChatInfo 命中缓存 → 用缓存群
  3. 缓存未命中且传了 group_id → 用显式群

第 2 步应该在第 3 步之后:调用方显式指定的 group_id 是主动意图,应优先于内部缓存。

## 修复
将 if (payload.group_id) 判断移至 getTempChatInfo 之前,使优先级变为:
  1. 是好友 → C2C
  2. 不是好友且传了 group_id → 用显式群
  3. 缓存命中 → 用缓存群(兜底)

未传入 group_id 时的行为完全不变。

## 测试

已通过 patch 编译产物 napcat.mjs 在生产环境验证,确认 group_id 参数现在可以
正确指定临时会话来源群。

Signed-off-by: colGem <62532175+colGem-ga@users.noreply.github.com>
2026-07-19 20:20:11 +08:00
738e272d2c fix(onebot): 引用回复解析中 quick_reply 形参未解构导致 reply 段丢失 (#1952)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* fix(onebot): destructure quick_reply in replyElement converter

parseMessageSegments passes the whole RecvMessageContext object as the
4th argument to element converters, but replyElement declared the
parameter as `quick_reply` without destructuring. The object is always
truthy, so every reply element took the quick-reply branch and skipped
lookup methods 2/3 whenever method 1 found no match, dropping the reply
segment from the reported OneBot message (it degrades to at + text).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(onebot): fall back to msgSeq match when msgRandom mismatches in reply lookup

All three reply lookup methods matched candidates only by msgRandom
whenever records.msgRandom was present. When the recorded msgRandom is
stale or inconsistent with the message database, the quoted message
returned by a seq-based query was discarded even though its msgSeq
matched exactly. Match by msgRandom first and fall back to an exact
msgSeq match.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: xulang <xuxiaolang2003@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 09:46:59 +08:00
Yahoo f7edbfd8d9 fix(onebot): relax packet status check for send poke (#1945) 2026-07-06 12:41:49 +08:00
墨梓柒 74dc33fee6 fix: return real used_space/total_space for get_group_file_system_info (#1944)
The action hardcoded used_space=0 and total_space=10GiB. The kernel's
getGroupFileList call already returns the group's space usage in its
groupSpaceResult, so read it (a single-item fetch) instead of the
placeholders. Falls back to the previous constants when the field is
absent, so there is no regression.

Also relax the empty-count guard from `!groupFileCount` to `=== undefined`
so a group with zero files is not mistaken for "Group not found".
2026-07-05 11:10:44 +08:00
mitsukina c95dd3d030 Add mappings for 9.9.32 and 3.2.30 builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Update external version metadata to support new QQ releases. Added appid/qua entries for 9.9.32-50828 and 3.2.30-50828, plus corresponding send/recv native and packet offsets across x64 and arm64 targets.
2026-07-03 19:21:27 +08:00
Bluemangoo 68e6a9bff9 fix: 修复如[CQ:face,id=*,raw=[object Object]]的问题。 (#1932) 2026-06-24 15:38:47 +08:00
手瓜一十雪 5c18a62530 add .claude to gitignore 2026-06-20 12:46:49 +08:00
手瓜一十雪 a82a5d5203 chore: .claude delete 2026-06-20 12:46:08 +08:00
手瓜一十雪 93efce86ca feat: re
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-06-20 12:41:32 +08:00
Ryokuryuneko 091c012427 feat(webui): 添加双重登录验证(2FA)功能 (#1920)
* feat(webui): 添加双重登录验证(2FA)功能

* fix: 修复 store.delete 类型错误,添加完整项目文件

* feat(webui): 添加双重登录验证(2FA)功能

- 后端:实现 TOTP 验证码生成和验证
- 后端:添加 enable2FA 和 totpSecret 配置项
- 后端:登录处理器支持 2FA 验证
- 前端:添加 2FA 登录流程和配置页面

* feat(webui): 添加双重登录验证(2FA)功能

- 后端:实现 TOTP 验证码生成和验证 (TotpHelper.ts)
- 后端:添加 enable2FA 和 totpSecret 配置项 (config.ts)
- 后端:登录处理器支持 2FA 验证,添加 2FA 管理 API (Auth.ts)
- 后端:注册 2FA 相关路由 (auth.ts)
- 前端:登录页面添加 2FA 验证步骤 (web_login.tsx)
- 前端:添加 2FA 相关 API 调用方法 (webui_manager.ts)
- 前端:添加 2FA 配置页面 (webui.tsx)

* fix: 更新 AuthResponse 类型定义以支持 2FA

* fix: 修复 setLocalToken 类型错误

* fix: 修复 TotpHelper.ts 类型错误

* fix: address PR review feedback

- Remove database files from tracking
- Use local QRCodeSVG instead of third-party API
- Remove unused verify2FACode method
- Remove IP-based challenge storage (password already validated)
- Require TOTP code to disable 2FA
- Remove duplicate loginWithTokenAndTotp method
- Remove unused generateTotp method
- Use consistent English error messages

* fix: remove unused store import

* chore: translate 2FA UI to Chinese
2026-06-20 09:56:54 +08:00
tzhd427 8a3faf64f9 对WebUI布局的修改 (#1906)
* 把“系统设置-修改密码”移动到“系统设置-WebUI配置”中

* 修正语法错误

* 把修改密码移动到上方
2026-06-17 01:01:10 +08:00
cc10143 fbd70bbb04 fix: reset QQLoginStatus on KickedOffLine to prevent WebUI re-login block (#1896)
When QQ kicks the bot offline, the WebUI incorrectly shows the account as still
logged in, blocking users from re-login via QR code or password until NapCat is
restarted.

Root cause: The KickedOffLine event handlers in both the shell (base.ts) and
framework (napcat.ts) only set the error message without resetting
QQLoginStatus. The QQGetQRcodeHandler and other login endpoints check
getQQLoginStatus() and reject all re-login attempts when it remains true.

Fix: Set QQLoginStatus to false in both event handlers, ensuring the WebUI
state syncs with the actual account status when kicked offline.

Two changes:
- napcat-shell/base.ts: add setQQLoginStatus(false) before setQQLoginError()
- napcat-framework/napcat.ts: register a KickedOffLine listener that resets
  the login status (the framework previously had no KickedOffLine listener)

Fixes: #508, #1818
2026-06-11 14:43:16 +08:00
MliKiowa c405b6d0a4 docs: 社区进一步限制
Signed-off-by: MliKiowa <nanaeonn@outlook.com>
2026-06-09 23:45:19 +08:00
手瓜一十雪 3a4b335062 feat
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-06-08 20:01:03 +08:00
Qiao 9aa11fd7c4 fix: 校验群名片设置结果 (#1880) 2026-06-04 23:56:45 +08:00
手瓜一十雪 8ae11bfdca Add 49738 build metadata to external JSONs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Register new builds and architecture-specific offsets/IDs for 9.9.31-49738 and 3.2.29-49738. Updated packages/napcat-core/external/appid.json to add appid/qua entries, and napi2native.json and packet.json to add send/recv offsets for x64 (and arm64 where applicable). These additions track the new builds and their native mappings.
2026-06-03 12:13:20 +08:00
Qiao 6acf350613 feat(onebot): add custom face management actions (#1879) 2026-06-02 22:51:27 +08:00
liuwanwan 0af6445d5a fix: 修复 lint 校验失败 (#1867) 2026-05-28 14:14:50 +08:00
liuwanwan a716a1a185 fix: correct HTTP method case comparison in httpApiRequest (#1865)
Express req.method returns uppercase strings ('GET', 'POST', etc.),
so `req.method === 'get'` never matches. This caused GET requests
to fall through to the else-if branch instead of directly using
req.query as the payload.

Closes NapNeko/NapCatQQ#1864
2026-05-26 22:41:33 +08:00
手瓜一十雪 8c9fc7edf4 README: suggest SnowLuma as GUI replacement
Replace the previous "New Feature" section with a short suggestion to try SnowLuma as a NapCat GUI alternative. Removes the v4.8.115+ notes about Stream API and recommending string IDs, simplifying the README and pointing users to the SnowLuma GitHub repository.
2026-05-26 18:23:23 +08:00
idranme 1abad76ac9 feat: 新增获取群组今日打卡列表功能 (#1855)
* feat: add group signed list API and OneBot action

* feat: register GetGroupSignedList action handler
2026-05-24 20:16:14 +08:00
手瓜一十雪 484c181050 Set rootDir in package tsconfigs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add compilerOptions.rootDir = ".." to tsconfig.json for napcat-onebot, napcat-shell, and napcat-webui-backend to ensure the TypeScript compiler uses the monorepo package root for source resolution. Also remove an extraneous blank line in theme.tsx near FileManager.uploadWebUIFont (minor formatting cleanup).
2026-05-22 22:31:11 +08:00
手瓜一十雪 9d652be35d fix: #1774 2026-05-22 22:27:19 +08:00
手瓜一十雪 f226c83595 Skip pnpm install scripts; defer QR code fetch & fix #1804
CI: use `pnpm i --ignore-scripts` in release-publish workflow to avoid running package install scripts during CI.

Shell: defer showing the QR code until after attempting WebUi quick-login/password fallback. Adds checks for NAPCAT_QUICK_ACCOUNT and quick-password env vars (and WebUi quick-login list), runs WebUi quick config, and only calls getQRCodePicture() if no fallback was attempted and the user is not logged in. Includes error handling for the quick-login attempt.
2026-05-22 22:23:45 +08:00
手瓜一十雪 b565f876c5 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2026-05-22 22:12:05 +08:00
手瓜一十雪 19a5febb1a fix: #1827 2026-05-22 22:06:00 +08:00
Copilotandsj817 bbf822035f fix: restart HTTP server when host changes (#1836)
* Initial plan

* fix: restart HTTP server when host changes

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/0ead0c47-df0d-4666-8877-775c9c641ed8

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-05-22 22:05:23 +08:00
手瓜一十雪 a2b0ac10a0 fix: #1843 2026-05-22 22:02:38 +08:00
手瓜一十雪 279b3ea4eb Add 9.9.30 & 9.9.31 x64 external entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add external mappings for Windows x64 versions 9.9.30-48762 and 9.9.31-49599 across appid, napi2native, and packet files. appid.json: add appid 537352525 (9.9.30-48762) and 537355779 (9.9.31-49599) with QUA strings. napi2native.json: add send/recv hashes for 9.9.30-48762-x64 (0A9B1BC / 1F0324D) and 9.9.31-49599-x64 (0AF885C / 20058E1). packet.json: add send/recv offsets for 9.9.30-48762-x64 (2F3B960 / 2F3EEE0) and 9.9.31-49599-x64 (3082C40 / 30861C8).
2026-05-22 21:58:30 +08:00
手瓜一十雪 33cc11ba84 Update tsconfig: bundler resolution & path mappings
Switch moduleResolution to "bundler" in base and package tsconfigs and consolidate path aliases for monorepo packages. Remove several package-level baseUrl entries and update package paths to reference ../../packages/* (add explicit napcat-common/src and napcat-image-size/src mappings). Also add a rootDir override for napcat-core. These changes unify module resolution and path aliases so TypeScript and bundlers resolve workspace packages consistently.
2026-05-21 19:16:44 +08:00
手瓜一十雪 b058604077 PR build: add dispatch script & secure workflow
Introduce a safe PR build dispatch flow and related helpers.

- Add GitHubAPI.createWorkflowDispatch to .github/scripts/lib/github.ts and tighten getRepository nullability.
- Add .github/scripts/pr-build-dispatch.ts to dispatch an untrusted workflow_run (workflow_dispatch) for PR builds.
- Rewrite .github/workflows/build-pr.yml to split privileged checks (pull_request_target / issue_comment) from untrusted execution (workflow_dispatch):
  - Add workflow_dispatch inputs for PR metadata.
  - Ensure privileged jobs only check conditions, post comments and dispatch the untrusted build.
  - Untrusted build jobs (framework/shell/publish) run under workflow_dispatch, checkout PR code into a separate workspace, clear GITHUB_TOKEN in build steps, and set stricter permissions and persist-credentials:false where appropriate.
  - Adjust concurrency, outputs, and inter-job dependencies to work with inputs rather than passing sensitive data between privileged and untrusted contexts.
- Update trigger-docker and result-comment flows to rely on workflow_dispatch inputs and only run in the untrusted run where appropriate.

- Change packages/napcat-vite/vite-plugin-version.js to read NAPCAT_GITHUB_TOKEN (instead of GITHUB_TOKEN) to avoid exposing Actions write tokens in untrusted builds.

These changes aim to improve security by preventing execution of PR-controlled code with elevated repo permissions and by isolating token usage.
2026-05-19 15:52:47 +08:00
H3CoF6 1c703a60ed fix(album): refactor group album like payload and implement cancel like action (#1844) 2026-05-19 09:54:15 +08:00
时瑾 285ba9cf2d ci: pin pnpm to v9 via pnpm/action-setup
pnpm 10 exits non-zero on [ERR_PNPM_IGNORED_BUILDS] by default, which
broke CI after the global pnpm version on GitHub runners bumped.

Replace ad-hoc `npm i -g pnpm` calls with pnpm/action-setup@v4 pinned to
version 9 across build-ci.yml, build-pr.yml, and drop the redundant
Install pnpm step from pr-build-run.ts.
2026-05-16 14:07:11 +08:00
Copilotandsj817 b253fd82c4 Fix WebUI login page stuck when navigating via token URL (#1835)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* Initial plan

* Fix: set isPasskeyLoading=false when token is in URL to prevent permanently disabled input on login failure

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/fa88593a-3466-40e5-80ff-82c47e1c56e6

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-05-13 10:34:26 +08:00
Ventiの酒 8996b35dd1 fix: enable wss connections and add certificate verification toggle in WebSocket Client (#1823)
* fix: enable wss connections and add certificate verification toggle in WebSocket Client

Previous behavior: the WebSocket Client only supported unencrypted ws:// connections; wss:// URLs were not handled and would fail to connect, providing no option to disable TLS certificate validation for development or self-signed certificates.
Fixed behavior: secure WebSocket connections (wss://) are now fully supported. A verifyCertificate configuration option has been introduced, defaulting to true. When set to false, certificate errors (e.g., self-signed certificates) are ignored, enabling safe local testing while maintaining strict validation by default for production.

* fix: improve wss certificate verification and add tests

Previous behavior: wsOptions used 'any' type without type safety, verifyCertificate was added to napcat-protocol without implementation, and no tests existed for the new config option.

Fixed behavior: wsOptions now uses proper WebSocket.ClientOptions type for compile-time safety, verifyCertificate removed from napcat-protocol (no WebSocket client implementation exists there), and comprehensive tests added to validate config loading and default values.
2026-05-13 10:33:47 +08:00
Bluemangoo 25db6f0835 add ptt to text (#1837) 2026-05-13 10:31:07 +08:00
手瓜一十雪 2c8f9743da Add 9.9.30-48517 appid and napi2native entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add mappings for version 9.9.30-48517: update packages/napcat-core/external/appid.json with appid 537352474 and qua "V1_WIN_NQ_9.9.30_48517_GW_B", and update packages/napcat-core/external/napi2native.json with the x64 mapping (send: "0A9B1BC", recv: "1F0324D"). These entries add support for the new 9.9.30-48517 release.
2026-04-26 18:10:40 +08:00
手瓜一十雪 fc26077283 fix: #1793 2026-04-26 17:26:53 +08:00
手瓜一十雪 e9bbc82f37 fix: #1801 2026-04-26 17:21:16 +08:00
时瑾 600f2a4518 fix: replace nclatest proxy with ghfast.top, add dual install commands 2026-04-18 01:29:58 +08:00
时瑾 abf57e688c feat: add proxy prefix to install URL, change TTL to 5 days
- comment.ts: Add PROXY_BASE constant (https://nclatest.znin.net);
  install curl command now uses proxy URL for CN users;
  '24小时' -> '5天'; Docker '7天' -> '5天'
- pr-publish-release.ts: Import PROXY_BASE, use proxy URL in release body,
  '24小时' -> '5天'
2026-04-18 00:31:40 +08:00
时瑾 d92a4cff8d fix: zip absolute path, publish failure comment, pass publish_status
- pr-publish-release.ts: Use resolve() for releaseDir to get absolute path;
  zip command runs with cwd=artifactDir so relative path was resolving wrong
- build-pr.yml: Expose steps.publish.outcome as publish_status job output;
  pass PUBLISH_STATUS env to update-comment-result job
- pr-build-result.ts: Read PUBLISH_STATUS, pass publishFailed to comment
- comment.ts: Show '⚠️ Release 发布失败' section in PR comment when
  publish failed but installInfo is absent
2026-04-18 00:18:46 +08:00
时瑾 e195aee5d2 fix: remove TS overloads incompatible with --experimental-strip-types, fix 204 response, fix retention-days
- lib/github.ts: Remove getEnv overload signatures (Node.js experimental-strip-types
  does not support TS function overloads, causes SyntaxError at parse time)
- lib/github.ts: Handle 204 No Content in request<T> (DELETE returns 204,
  calling response.json() on empty body throws)
- build-pr.yml: retention-days 7->5 (repo max is 5)
2026-04-18 00:08:12 +08:00
时瑾 014a32533d feat: add PR release publish, Docker dispatch and comment system 2026-04-17 23:51:30 +08:00
127 changed files with 5679 additions and 1772 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@
- **控制数量**:最终保持 5-15 条更新要点
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
## 输出模板 - 必须严格遵守以下格式
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
```
# {VERSION}
+188 -1
View File
@@ -3,6 +3,16 @@
*/
export const COMMENT_MARKER = '<!-- napcat-pr-build -->';
export const DOCKER_COMMENT_MARKER = '<!-- napcat-pr-docker -->';
// 默认代理前缀(加速中国大陆访问 GitHub Release)
// 格式:https://ghfast.top/{full-github-url}
export const PROXY_BASE = 'https://gh.llkk.cc';
/** 将 GitHub 直链转换为 ghfast.top 加速链接 */
export function toProxyUrl (directUrl: string): string {
return `${PROXY_BASE}/${directUrl}`;
}
export type BuildStatus = 'success' | 'failure' | 'cancelled' | 'pending' | 'unknown';
@@ -105,12 +115,19 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
// ============== 构建结果评论 ==============
export interface InstallInfo {
installUrl: string;
releaseUrl: string;
}
export function generateResultComment (
targets: BuildTarget[],
prSha: string,
runId: string,
repository: string,
version?: string
version?: string,
installInfo?: InstallInfo,
publishFailed?: boolean
): string {
const runUrl = `https://github.com/${repository}/actions/runs/${runId}`;
const shortSha = formatSha(prSha);
@@ -173,6 +190,41 @@ export function generateResultComment (
`| 🕐 完成时间 | ${time} |`,
];
// 添加快速安装命令
if (installInfo) {
const directUrl = installInfo.installUrl;
const proxyInstallUrl = toProxyUrl(directUrl);
lines.push(
'',
'---',
'',
'## 🚀 快速安装 (Linux)',
'',
'**直连(需要能访问 GitHub)**',
'```bash',
`curl -sSL ${directUrl} | bash`,
'```',
'',
'**加速(国内推荐,ghfast.top)**',
'```bash',
`curl -sSL ${proxyInstallUrl} | bash`,
'```',
'',
`> 📦 [查看 Release 页面](${installInfo.releaseUrl})`,
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。'
);
} else if (publishFailed) {
lines.push(
'',
'---',
'',
'## ⚠️ Release 发布失败',
'',
'> ❌ PR Release 发布过程中出现错误,无法提供快速安装命令。',
`> 🔗 [查看构建日志](${runUrl}) 了解详情。`
);
}
// 添加错误详情
const failedTargets = targets.filter(t => t.status === 'failure' && t.error);
if (failedTargets.length > 0) {
@@ -228,3 +280,138 @@ export function generateResultComment (
return lines.join('\n');
}
// ============== Docker 构建评论 ==============
export function generateDockerBuildingComment (prNumber: string, prSha: string): string {
const time = getTimeString();
const shortSha = formatSha(prSha);
const lines: string[] = [
DOCKER_COMMENT_MARKER,
'',
'<div align="center">',
'',
'# 🐳 Docker 测试镜像构建中',
'',
'![Building](https://img.shields.io/badge/Docker-构建中-yellow?style=for-the-badge&logo=docker&logoColor=white)',
'',
'</div>',
'',
'---',
'',
'## 📋 构建信息',
'',
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 PR | #${prNumber} |`,
`| 🕐 触发时间 | ${time} |`,
'',
'---',
'',
'<div align="center">',
'',
'> ⏳ **Docker 镜像正在构建中,请稍候...**',
'>',
'> 构建完成后将自动更新此评论',
'',
'</div>',
];
return lines.join('\n');
}
export function generateDockerResultComment (
prNumber: string,
prSha: string,
success: boolean,
dockerImage?: string,
error?: string
): string {
const time = getTimeString();
const shortSha = formatSha(prSha);
const statusBadge = success
? '![Success](https://img.shields.io/badge/Docker-构建成功-success?style=for-the-badge&logo=docker&logoColor=white)'
: '![Failed](https://img.shields.io/badge/Docker-构建失败-critical?style=for-the-badge&logo=docker&logoColor=white)';
const headerTitle = success ? '# ✅ Docker 测试镜像就绪' : '# ❌ Docker 测试镜像构建失败';
const lines: string[] = [
DOCKER_COMMENT_MARKER,
'',
'<div align="center">',
'',
headerTitle,
'',
statusBadge,
'',
'</div>',
'',
'---',
'',
'## 📋 构建信息',
'',
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 PR | #${prNumber} |`,
`| 🕐 完成时间 | ${time} |`,
];
if (success && dockerImage) {
lines.push(
'',
'---',
'',
'## 🚀 快速使用',
'',
'```bash',
`docker pull ${dockerImage}`,
'```',
'',
'> ⚠️ 此为 PR 测试镜像,保留 5 天后自动清理。'
);
}
if (!success && error) {
lines.push(
'',
'---',
'',
'<details>',
'<summary>🔴 <b>错误详情</b></summary>',
'',
'```',
escapeCodeBlock(error),
'```',
'',
'</details>'
);
}
lines.push('', '---', '');
if (success) {
lines.push(
'<div align="center">',
'',
'> 🎉 **Docker 测试镜像已就绪!**',
'>',
'> 使用上方命令拉取镜像进行测试',
'',
'</div>'
);
} else {
lines.push(
'<div align="center">',
'',
'> ⚠️ **Docker 镜像构建失败**',
'>',
'> 请检查错误详情',
'',
'</div>'
);
}
return lines.join('\n');
}
+135 -3
View File
@@ -31,6 +31,21 @@ export interface Artifact {
archive_download_url: string;
}
export interface Release {
id: number;
tag_name: string;
name: string;
upload_url: string;
html_url: string;
created_at: string;
}
export interface ReleaseAsset {
id: number;
name: string;
browser_download_url: string;
}
// ============== GitHub API Client ==========================
export class GitHubAPI {
@@ -56,6 +71,11 @@ export class GitHubAPI {
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
}
// 204 No Content(DELETE 等)不解析 body
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
@@ -150,6 +170,119 @@ export class GitHubAPI {
console.log('✓ Created new comment');
}
}
// ============== Release API ==============
async getReleaseByTag (owner: string, repo: string, tag: string): Promise<Release | null> {
try {
return await this.request<Release>(`/repos/${owner}/${repo}/releases/tags/${tag}`);
} catch {
return null;
}
}
async deleteRelease (owner: string, repo: string, releaseId: number): Promise<void> {
await this.request(`/repos/${owner}/${repo}/releases/${releaseId}`, { method: 'DELETE' });
}
async deleteRef (owner: string, repo: string, ref: string): Promise<void> {
try {
await this.request(`/repos/${owner}/${repo}/git/refs/${ref}`, { method: 'DELETE' });
} catch {
// ref may not exist, ignore
}
}
async createRelease (
owner: string,
repo: string,
tag: string,
name: string,
body: string,
prerelease = true
): Promise<Release> {
return this.request<Release>(`/repos/${owner}/${repo}/releases`, {
method: 'POST',
body: JSON.stringify({ tag_name: tag, name, body, prerelease }),
headers: { 'Content-Type': 'application/json' },
});
}
async uploadReleaseAsset (
uploadUrl: string,
fileName: string,
data: Buffer,
contentType = 'application/octet-stream'
): Promise<ReleaseAsset> {
const url = uploadUrl.replace(/\{[^}]*\}/g, '') + `?name=${encodeURIComponent(fileName)}`;
const response = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'Content-Type': contentType,
'X-GitHub-Api-Version': '2022-11-28',
},
body: data,
});
if (!response.ok) {
throw new Error(`Upload ${fileName} failed: ${response.status} ${response.statusText}`);
}
return response.json() as Promise<ReleaseAsset>;
}
// ============== Dispatch API ==============
async repositoryDispatch (
owner: string,
repo: string,
eventType: string,
clientPayload: Record<string, string>
): Promise<void> {
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/dispatches`, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Content-Type': 'application/json',
},
body: JSON.stringify({ event_type: eventType, client_payload: clientPayload }),
});
if (!response.ok && response.status !== 204) {
throw new Error(`Dispatch failed: ${response.status} ${response.statusText}`);
}
}
async createWorkflowDispatch (
owner: string,
repo: string,
workflowFile: string,
ref: string,
inputs: Record<string, string>
): Promise<void> {
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/actions/workflows/${workflowFile}/dispatches`, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Content-Type': 'application/json',
},
body: JSON.stringify({ ref, inputs }),
});
if (!response.ok && response.status !== 204) {
throw new Error(`Workflow dispatch failed: ${response.status} ${response.statusText}`);
}
}
// ============== Release Cleanup API ==============
async listReleases (owner: string, repo: string, perPage = 100, page = 1): Promise<Release[]> {
return this.request<Release[]>(
`/repos/${owner}/${repo}/releases?per_page=${perPage}&page=${page}`
);
}
}
// ============== Output 工具 ==============
@@ -172,8 +305,7 @@ export function setMultilineOutput (name: string, value: string): void {
// ============== 环境变量工具 ==============
export function getEnv (name: string, required: true): string;
export function getEnv (name: string, required?: false): string | undefined;
// Note: 不使用函数重载——Node.js --experimental-strip-types 不支持 TS overload signatures
export function getEnv (name: string, required = false): string | undefined {
const value = process.env[name];
if (required && !value) {
@@ -183,7 +315,7 @@ export function getEnv (name: string, required = false): string | undefined {
}
export function getRepository (): { owner: string, repo: string; } {
const repository = getEnv('GITHUB_REPOSITORY', true);
const repository = getEnv('GITHUB_REPOSITORY', true)!;
const [owner, repo] = repository.split('/');
return { owner, repo };
}
+50
View File
@@ -0,0 +1,50 @@
/**
* PR Build - Dispatch untrusted build workflow
*
* 环境变量:
* - GITHUB_TOKEN: GitHub API Token
* - PR_NUMBER: PR 编号
* - PR_SHA: PR HEAD SHA
* - PR_HEAD_REPO: PR 源仓库
* - PR_HEAD_REF: PR 源分支
* - WORKFLOW_FILE: 工作流文件名,默认 build-pr.yml
* - DISPATCH_REF: 触发分支,默认当前分支
*/
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
declare const process: { exit(code?: number): never; };
async function main (): Promise<void> {
console.log('🚀 Dispatching PR build workflow\n');
const token = getEnv('GITHUB_TOKEN', true)!;
const prNumber = getEnv('PR_NUMBER', true)!;
const prSha = getEnv('PR_SHA', true)!;
const prHeadRepo = getEnv('PR_HEAD_REPO', true)!;
const prHeadRef = getEnv('PR_HEAD_REF') || '';
const workflowFile = getEnv('WORKFLOW_FILE') || 'build-pr.yml';
const dispatchRef = getEnv('DISPATCH_REF') || getEnv('GITHUB_REF_NAME') || 'main';
const { owner, repo } = getRepository();
console.log(`PR: #${prNumber}`);
console.log(`SHA: ${prSha}`);
console.log(`Head repo: ${prHeadRepo}`);
console.log(`Workflow: ${workflowFile}`);
console.log(`Ref: ${dispatchRef}\n`);
const github = new GitHubAPI(token);
await github.createWorkflowDispatch(owner, repo, workflowFile, dispatchRef, {
pr_number: prNumber,
pr_sha: prSha,
pr_head_repo: prHeadRepo,
pr_head_ref: prHeadRef,
});
console.log('✅ Dispatch created');
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+19 -2
View File
@@ -11,11 +11,13 @@
* - FRAMEWORK_ERROR: Framework 构建错误信息
* - SHELL_STATUS: Shell 构建状态
* - SHELL_ERROR: Shell 构建错误信息
* - INSTALL_URL: PR Release 安装脚本 URL (可选)
* - RELEASE_URL: PR Release 页面 URL (可选)
*/
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
import { generateResultComment, COMMENT_MARKER } from './lib/comment.ts';
import type { BuildTarget, BuildStatus } from './lib/comment.ts';
import type { BuildTarget, BuildStatus, InstallInfo } from './lib/comment.ts';
function parseStatus (value: string | undefined): BuildStatus {
if (value === 'success' || value === 'failure' || value === 'cancelled') {
@@ -46,6 +48,21 @@ async function main (): Promise<void> {
console.log(`Framework: ${frameworkStatus}${frameworkError ? ` (${frameworkError})` : ''}`);
console.log(`Shell: ${shellStatus}${shellError ? ` (${shellError})` : ''}\n`);
// PR Release 信息(由 publish-pr-release job 传入)
const installUrl = getEnv('INSTALL_URL');
const releaseUrl = getEnv('RELEASE_URL');
const publishStatus = getEnv('PUBLISH_STATUS'); // 'success' | 'failure' | 'skipped' | ''
const installInfo: InstallInfo | undefined =
installUrl && releaseUrl ? { installUrl, releaseUrl } : undefined;
const publishFailed = publishStatus === 'failure';
if (installInfo) {
console.log(`Install URL: ${installUrl}`);
console.log(`Release URL: ${releaseUrl}\n`);
} else if (publishFailed) {
console.log('Publish status: FAILED\n');
}
const github = new GitHubAPI(token);
const repository = `${owner}/${repo}`;
@@ -79,7 +96,7 @@ async function main (): Promise<void> {
},
];
const comment = generateResultComment(targets, prSha, runId, repository, version);
const comment = generateResultComment(targets, prSha, runId, repository, version, installInfo, publishFailed);
await github.createOrUpdateComment(owner, repo, prNumber, comment, COMMENT_MARKER);
}
+1 -5
View File
@@ -22,11 +22,7 @@ interface BuildStep {
function getCommonSteps (): BuildStep[] {
return [
{
name: 'Install pnpm',
command: 'npm i -g pnpm',
errorMessage: 'Failed to install pnpm',
},
// pnpm 已通过 GitHub Action (pnpm/action-setup) 预安装并固定 v9, 此处无需再次安装
{
name: 'Install dependencies',
command: 'pnpm i',
+69
View File
@@ -0,0 +1,69 @@
/**
* PR Build - 触发 NapCat-Docker 仓库构建 PR 测试镜像
*
* 功能:
* 1. 在 PR 中创建 Docker 构建中评论
* 2. 触发 NapCat-Docker 仓库的 repository_dispatch 事件
*
* 环境变量:
* DISPATCH_PAT - 具备目标仓库 dispatch 权限的 PAT
* GITHUB_TOKEN - GitHub API Token (用于写 PR 评论)
* PR_NUMBER - PR 编号
* PR_SHA - PR HEAD 提交 SHA
* PR_HEAD_REPO - PR 源仓库 (owner/repo)
* SOURCE_REPO - 当前仓库 (默认 NapNeko/NapCatQQ)
* RELEASE_REPO - PR release 仓库 (默认 NapNeko/napcat-pr-release)
* TARGET_REPO - Docker 仓库 (默认 NapNeko/NapCat-Docker)
*/
import { GitHubAPI, getEnv } from './lib/github.ts';
import { generateDockerBuildingComment, DOCKER_COMMENT_MARKER } from './lib/comment.ts';
async function main (): Promise<void> {
console.log('🐳 Dispatching Docker build\n');
const token = getEnv('DISPATCH_PAT', true);
const githubToken = getEnv('GITHUB_TOKEN', true);
const prNumber = getEnv('PR_NUMBER', true);
const prSha = getEnv('PR_SHA', true);
const prHeadRepo = getEnv('PR_HEAD_REPO') || '';
const sourceRepo = getEnv('SOURCE_REPO') || 'NapNeko/NapCatQQ';
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
const targetRepo = getEnv('TARGET_REPO') || 'NapNeko/NapCat-Docker';
const [targetOwner, targetRepoName] = targetRepo.split('/');
const [sourceOwner, sourceRepoName] = sourceRepo.split('/');
const shortSha = prSha.substring(0, 7);
console.log(` PR: #${prNumber}`);
console.log(` SHA: ${shortSha}`);
console.log(` Target: ${targetRepo}`);
console.log(` Release: ${releaseRepo}\n`);
// 在 PR 中创建 Docker 构建中评论
console.log('💬 Creating Docker building comment...');
const prGithub = new GitHubAPI(githubToken);
const dockerComment = generateDockerBuildingComment(prNumber, prSha);
await prGithub.createOrUpdateComment(
sourceOwner, sourceRepoName, parseInt(prNumber, 10), dockerComment, DOCKER_COMMENT_MARKER
);
// 触发 Docker 仓库构建
const github = new GitHubAPI(token);
await github.repositoryDispatch(targetOwner, targetRepoName, 'napcatqq-pr-build', {
pr_number: prNumber,
pr_sha: prSha,
pr_short_sha: shortSha,
pr_head_repo: prHeadRepo,
source_repo: sourceRepo,
release_repo: releaseRepo,
});
console.log('✅ Dispatch succeeded');
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+173
View File
@@ -0,0 +1,173 @@
/**
* PR Build - 发布构建产物到 napcat-pr-release 仓库
*
* 功能:
* 1. 将 CI 构建产物(Framework / Shell)打包为 zip
* 2. 从 NapCat-Installer 仓库拉取 install.sh 并替换下载链接
* 3. 发布到 napcat-pr-release 仓库的 GitHub Release
*
* 环境变量:
* RELEASE_PAT - 具备目标仓库 release 写权限的 PAT
* PR_NUMBER - PR 编号
* PR_SHA - PR HEAD 提交 SHA
* NAPCAT_VERSION - 构建版本号
* ARTIFACTS_DIR - 构建产物目录 (默认 ./artifacts)
* RELEASE_REPO - 发布仓库 (默认 NapNeko/napcat-pr-release)
* INSTALLER_REPO - 安装脚本仓库 (默认 NapNeko/NapCat-Installer)
* INSTALLER_BRANCH - 安装脚本分支 (默认 main)
*/
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
import { toProxyUrl } from './lib/comment.ts';
interface AssetEntry {
name: string;
path: string;
contentType: string;
}
async function main (): Promise<void> {
console.log('📦 PR Release Publisher\n');
const token = getEnv('RELEASE_PAT', true);
const prNumber = getEnv('PR_NUMBER', true);
const prSha = getEnv('PR_SHA', true);
const version = getEnv('NAPCAT_VERSION') || 'unknown';
const artifactsDir = getEnv('ARTIFACTS_DIR') || './artifacts';
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
const installerRepo = getEnv('INSTALLER_REPO') || 'NapNeko/NapCat-Installer';
const installerBranch = getEnv('INSTALLER_BRANCH') || 'main';
const [releaseOwner, releaseRepoName] = releaseRepo.split('/');
const shortSha = prSha.substring(0, 7);
const tag = `pr-${prNumber}-${shortSha}`;
const releaseName = `PR #${prNumber} (${shortSha})`;
const downloadBase = `https://github.com/${releaseRepo}/releases/download/${tag}`;
console.log(` Tag: ${tag}`);
console.log(` Repo: ${releaseRepo}`);
console.log(` Version: ${version}`);
console.log(` SHA: ${shortSha}\n`);
const github = new GitHubAPI(token);
const releaseDir = resolve('./release-assets'); // 使用绝对路径,避免 zip cwd 切换后相对路径解析错误
mkdirSync(releaseDir, { recursive: true });
// ---- 打包构建产物 ----
const artifacts = ['NapCat.Framework', 'NapCat.Shell'];
for (const name of artifacts) {
const dir = join(artifactsDir, name);
if (existsSync(dir)) {
const zipPath = join(releaseDir, `${name}.zip`);
console.log(`📦 Packing ${name}...`);
execSync(`zip -qr "${zipPath}" .`, { cwd: dir, stdio: 'inherit' });
console.log(` ✓ ${name}.zip\n`);
} else {
console.log(` ⚠ ${name} 目录不存在,跳过\n`);
}
}
// ---- 拉取并修改安装脚本 ----
console.log('📜 Fetching install.sh...');
const scriptUrl = `https://raw.githubusercontent.com/${installerRepo}/${installerBranch}/script/install.sh`;
try {
const response = await fetch(scriptUrl);
if (response.ok) {
let script = await response.text();
// 替换下载链接(保留代理前缀 ${target_proxy:+${target_proxy}/})
const shellUrl = `${downloadBase}/NapCat.Shell.zip`;
const originalScript = script;
script = script.replace(
/napcat_download_url="\$\{target_proxy:\+\$\{target_proxy\}\/\}https:\/\/github\.com\/NapNeko\/NapCatQQ\/releases\/latest\/download\/NapCat\.Shell\.zip"/g,
`napcat_download_url="\${target_proxy:+\${target_proxy}/}${shellUrl}"`
);
if (script === originalScript) {
console.log(' ⚠ Warning: URL replacement did not match - install.sh format may have changed');
}
const scriptPath = join(releaseDir, 'install.sh');
writeFileSync(scriptPath, script, { mode: 0o755 });
console.log(` ✓ Patched download URL -> ${shellUrl}\n`);
} else {
console.log(` ⚠ Failed to fetch install.sh: ${response.status}\n`);
}
} catch (e) {
console.log(` ⚠ Failed to fetch install.sh: ${(e as Error).message}\n`);
}
// ---- 收集所有要上传的文件 ----
const assets: AssetEntry[] = [];
for (const file of readdirSync(releaseDir)) {
const ext = file.split('.').pop()?.toLowerCase();
const contentType = ext === 'zip' ? 'application/zip' : ext === 'sh' ? 'application/x-sh' : 'application/octet-stream';
assets.push({ name: file, path: join(releaseDir, file), contentType });
}
console.log(`📋 Assets to upload: ${assets.map(a => a.name).join(', ')}\n`);
// ---- 删除旧 release ----
console.log('🗑️ Checking for existing release...');
const existing = await github.getReleaseByTag(releaseOwner, releaseRepoName, tag);
if (existing) {
console.log(` Deleting existing release (id=${existing.id})...`);
await github.deleteRelease(releaseOwner, releaseRepoName, existing.id);
await github.deleteRef(releaseOwner, releaseRepoName, `tags/${tag}`);
console.log(' ✓ Deleted\n');
} else {
console.log(' No existing release\n');
}
// ---- 创建 Release ----
const directInstallUrl = `${downloadBase}/install.sh`;
const proxyInstallUrl = toProxyUrl(directInstallUrl);
const releaseBody = [
`## NapCat PR #${prNumber} 测试版本`,
'',
`- **版本**: \`${version}\``,
`- **提交**: \`${prSha}\``,
`- **来源**: [NapCatQQ PR #${prNumber}](https://github.com/NapNeko/NapCatQQ/pull/${prNumber})`,
'',
'### 快速安装 (Linux)',
'',
'**直连(需要能访问 GitHub)**',
'```bash',
`curl -sSL ${directInstallUrl} | bash`,
'```',
'',
'**加速(国内推荐,ghfast.top)**',
'```bash',
`curl -sSL ${proxyInstallUrl} | bash`,
'```',
'',
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。',
].join('\n');
console.log('🚀 Creating release...');
const release = await github.createRelease(
releaseOwner, releaseRepoName, tag, releaseName, releaseBody, true
);
console.log(` ✓ Release created: ${release.html_url}\n`);
// ---- 上传资产 ----
console.log('📤 Uploading assets...');
for (const asset of assets) {
const data = readFileSync(asset.path);
const uploaded = await github.uploadReleaseAsset(
release.upload_url, asset.name, data, asset.contentType
);
console.log(` ✓ ${asset.name} -> ${uploaded.browser_download_url}`);
}
console.log(`\n✅ Release published: ${release.html_url}`);
// 输出供后续 job 使用
setOutput('release_url', release.html_url);
setOutput('release_tag', tag);
setOutput('install_url', `${downloadBase}/install.sh`);
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+11 -4
View File
@@ -17,14 +17,17 @@ jobs:
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Install Dependencies
run: |
npm i -g pnpm
pnpm i
run: pnpm i
- name: Type Check
run: pnpm run typecheck
- name: Run Tests
@@ -50,6 +53,11 @@ jobs:
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
@@ -68,7 +76,6 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
+332 -212
View File
@@ -1,118 +1,106 @@
# =============================================================================
# PR 构建工作流
# =============================================================================
# 功能:
# 1. 在 PR 提交时自动构建 Framework 和 Shell 包
# 2. 支持通过 /build 命令手动触发构建(仅协作者/组织成员)
# 3. 在 PR 中发布构建状态评论,并持续更新(不会重复创建)
# 4. 支持 Fork PR 的构建(使用 pull_request_target 获取写权限)
#
# 安全说明:
# - 使用 pull_request_target 事件,在 base 分支上下文运行
# - 构建脚本始终从 base 分支 checkout,避免恶意 PR 篡改脚本
# - PR 代码单独 checkout 到 workspace 目录
# 安全模型:
# 1. pull_request_target / issue_comment 入口只读取元数据、检查权限、更新评论并触发构建。
# 2. 真正执行 PR 代码的构建流程只在 workflow_dispatch 中运行。
# 3. 构建流程不具备写仓库/写评论/读 secrets 权限,显式清空 GITHUB_TOKEN,不持久化 checkout 凭据。
# 4. 版本号在 Action 中提前生成,通过 NAPCAT_VERSION 传给 Vite 插件,插件无需 GitHub token。
# 5. 发布 Release、触发 Docker 等可信操作只消费构建 artifact,不执行 PR artifact 中的代码。
# =============================================================================
name: Build PR
# =============================================================================
# 触发条件
# =============================================================================
on:
# PR 事件:打开、同步(新推送)、重新打开时触发
# 注意:使用 pull_request_target 而非 pull_request,以便对 Fork PR 有写权限
pull_request_target:
types: [opened, synchronize, reopened]
# Issue 评论事件:用于响应 /build 命令
issue_comment:
types: [created]
# =============================================================================
# 权限配置
# =============================================================================
workflow_dispatch:
inputs:
pr_number:
description: PR 编号
required: true
type: string
pr_sha:
description: PR HEAD SHA
required: true
type: string
pr_head_repo:
description: PR 源仓库
required: true
type: string
pr_head_ref:
description: PR 源分支
required: false
type: string
permissions:
contents: read # 读取仓库内容
pull-requests: write # 写入 PR 评论
issues: write # 写入 Issue 评论(/build 命令响应)
actions: read # 读取 Actions 信息(获取构建日志链接)
contents: read
# =============================================================================
# 并发控制
# =============================================================================
# 同一 PR 的多次构建会取消之前未完成的构建,避免资源浪费
# 注意:只有在 should_build=true 时才会进入实际构建流程,
# issue_comment 事件如果不是 /build 命令,会在 check-build 阶段快速退出,
# 不会取消正在进行的构建(因为 cancel-in-progress 只影响同 group 的后续任务)
concurrency:
# 使用不同的 group 策略:
# - pull_request_target: 使用 PR 号
# - issue_comment: 只有确认是 /build 命令时才使用 PR 号,否则使用 run_id(不冲突)
group: pr-build-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
group: pr-build-${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
cancel-in-progress: true
# =============================================================================
# 任务定义
# =============================================================================
jobs:
# ---------------------------------------------------------------------------
# Job 1: 检查构建条件
# ---------------------------------------------------------------------------
# 判断是否应该触发构建:
# - pull_request_target 事件:总是触发
# - issue_comment 事件:检查是否为 /build 命令,且用户有权限
# 特权入口:只检查条件、写入“构建中”评论、触发无权限构建
# ---------------------------------------------------------------------------
check-build:
if: github.event_name != 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: write
outputs:
should_build: ${{ steps.check.outputs.should_build }} # 是否应该构建
pr_number: ${{ steps.check.outputs.pr_number }} # PR 编号
pr_sha: ${{ steps.check.outputs.pr_sha }} # PR 最新提交 SHA
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }} # PR 源仓库(用于 Fork)
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }} # PR 源分支
should_build: ${{ steps.check.outputs.should_build }}
pr_number: ${{ steps.check.outputs.pr_number }}
pr_sha: ${{ steps.check.outputs.pr_sha }}
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }}
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }}
steps:
# 仅 checkout 脚本目录,加快速度
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
# 使用 Node.js 24 以支持原生 TypeScript 执行
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 执行检查脚本,判断是否触发构建
- name: Check trigger condition
id: check
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
# ---------------------------------------------------------------------------
# Job 2: 更新评论为"构建中"状态
# ---------------------------------------------------------------------------
# 在 PR 中创建或更新评论,显示构建正在进行中
# ---------------------------------------------------------------------------
update-comment-building:
needs: check-build
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 更新 PR 评论,显示构建中状态
- name: Update building comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -120,185 +108,317 @@ jobs:
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
# ---------------------------------------------------------------------------
# Job 3: 构建 Framework 包
# ---------------------------------------------------------------------------
# 执行 napcat-framework 的构建流程
# ---------------------------------------------------------------------------
build-framework:
dispatch-build:
needs: [check-build, update-comment-building]
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
outputs:
status: ${{ steps.build.outcome }} # 构建结果:success/failure
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
version: ${{ steps.version.outputs.version }} # 构建版本号
steps:
# 【安全】先从 base 分支 checkout 构建脚本
# 这样即使 PR 中修改了脚本,也不会被执行
- name: Checkout scripts from base
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
# 将 PR 代码 checkout 到单独的 workspace 目录
- name: Checkout PR code
uses: actions/checkout@v5
with:
repository: ${{ needs.check-build.outputs.pr_head_repo }}
ref: ${{ needs.check-build.outputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 获取最新 release tag 并生成版本号
- name: Generate Version
id: version
working-directory: workspace
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
# 执行构建,使用 base 分支的脚本处理 workspace 中的代码
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
continue-on-error: true # 允许失败,后续更新评论时处理
# 构建成功时上传产物
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: NapCat.Framework
path: workspace/framework-dist
retention-days: 7 # 保留 7 天
# ---------------------------------------------------------------------------
# Job 4: 构建 Shell 包
# ---------------------------------------------------------------------------
# 执行 napcat-shell 的构建流程(与 Framework 并行执行)
# ---------------------------------------------------------------------------
build-shell:
needs: [check-build, update-comment-building]
if: needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
outputs:
status: ${{ steps.build.outcome }} # 构建结果:success/failure
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
version: ${{ steps.version.outputs.version }} # 构建版本号
steps:
# 【安全】先从 base 分支 checkout 构建脚本
- name: Checkout scripts from base
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
# 将 PR 代码 checkout 到单独的 workspace 目录
- name: Checkout PR code
uses: actions/checkout@v5
with:
repository: ${{ needs.check-build.outputs.pr_head_repo }}
ref: ${{ needs.check-build.outputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 获取最新 release tag 并生成版本号
- name: Generate Version
id: version
working-directory: workspace
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
# 执行构建
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
continue-on-error: true
# 构建成功时上传产物
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: NapCat.Shell
path: workspace/shell-dist
retention-days: 7 # 保留 7 天
# ---------------------------------------------------------------------------
# Job 5: 更新评论为构建结果
# ---------------------------------------------------------------------------
# 汇总所有构建结果,更新 PR 评论显示最终状态
# 使用 always() 确保即使构建失败/取消也会执行
# ---------------------------------------------------------------------------
update-comment-result:
needs: [check-build, update-comment-building, build-framework, build-shell]
if: always() && needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 更新评论,显示构建结果和下载链接
- name: Update result comment
- name: Dispatch untrusted build
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
PR_HEAD_REF: ${{ needs.check-build.outputs.pr_head_ref }}
WORKFLOW_FILE: build-pr.yml
DISPATCH_REF: ${{ github.event.repository.default_branch }}
run: node --experimental-strip-types .github/scripts/pr-build-dispatch.ts
# ---------------------------------------------------------------------------
# 无权限构建:只由 workflow_dispatch 执行 PR 代码
# ---------------------------------------------------------------------------
build-framework:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
status: ${{ steps.build.outcome }}
error: ${{ steps.build.outputs.error }}
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout scripts from base
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
persist-credentials: false
- name: Checkout PR code
uses: actions/checkout@v5
with:
repository: ${{ inputs.pr_head_repo }}
ref: ${{ inputs.pr_sha }}
path: workspace
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Generate Version
id: version
working-directory: workspace
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ inputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ''
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
continue-on-error: true
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: NapCat.Framework
path: workspace/framework-dist
retention-days: 5
build-shell:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
status: ${{ steps.build.outcome }}
error: ${{ steps.build.outputs.error }}
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout scripts from base
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
path: _scripts
persist-credentials: false
- name: Checkout PR code
uses: actions/checkout@v5
with:
repository: ${{ inputs.pr_head_repo }}
ref: ${{ inputs.pr_sha }}
path: workspace
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Generate Version
id: version
working-directory: workspace
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${{ inputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ''
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
continue-on-error: true
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: NapCat.Shell
path: workspace/shell-dist
retention-days: 5
# ---------------------------------------------------------------------------
# 可信后处理:只下载/打包/发布 artifact,不执行 artifact 中的代码
# ---------------------------------------------------------------------------
publish-pr-release:
needs: [build-framework, build-shell]
if: always() && github.event_name == 'workflow_dispatch' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
runs-on: ubuntu-latest
permissions:
contents: read
actions: read
outputs:
release_url: ${{ steps.publish.outputs.release_url }}
release_tag: ${{ steps.publish.outputs.release_tag }}
install_url: ${{ steps.publish.outputs.install_url }}
publish_status: ${{ steps.publish.outcome }}
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Download Framework artifact
if: needs.build-framework.outputs.status == 'success'
uses: actions/download-artifact@v6
with:
name: NapCat.Framework
path: ./artifacts/NapCat.Framework
- name: Download Shell artifact
if: needs.build-shell.outputs.status == 'success'
uses: actions/download-artifact@v6
with:
name: NapCat.Shell
path: ./artifacts/NapCat.Shell
- name: Publish release
id: publish
continue-on-error: true
env:
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
PR_NUMBER: ${{ inputs.pr_number }}
PR_SHA: ${{ inputs.pr_sha }}
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
ARTIFACTS_DIR: ./artifacts
run: |
if [ -z "${RELEASE_PAT}" ]; then
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 PR Release 发布"
exit 0
fi
node --experimental-strip-types .github/scripts/pr-publish-release.ts
- name: Upload install script as artifact
if: steps.publish.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: install-script
path: ./release-assets/install.sh
retention-days: 5
if-no-files-found: ignore
update-comment-result:
needs: [build-framework, build-shell, publish-pr-release]
if: always() && github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
actions: read
pull-requests: write
issues: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Update result comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ inputs.pr_number }}
PR_SHA: ${{ inputs.pr_sha }}
RUN_ID: ${{ github.run_id }}
# 构建版本号
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
# 获取构建状态,如果 job 被跳过则标记为 cancelled
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
trigger-docker:
needs: [build-shell, publish-pr-release]
if: github.event_name == 'workflow_dispatch' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Dispatch docker build
continue-on-error: true
env:
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ inputs.pr_number }}
PR_SHA: ${{ inputs.pr_sha }}
PR_HEAD_REPO: ${{ inputs.pr_head_repo }}
SOURCE_REPO: ${{ github.repository }}
RELEASE_REPO: NapNeko/napcat-pr-release
run: |
if [ -z "${DISPATCH_PAT}" ]; then
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 Docker 测试镜像构建"
exit 0
fi
node --experimental-strip-types .github/scripts/pr-docker-dispatch.ts
+2 -2
View File
@@ -9,8 +9,8 @@ on:
type: string
env:
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
QQ_URL_X86_64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_x86_64.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/fd40a3ec/linuxqq_3.2.30-50969_arm64.AppImage'
jobs:
get-version:
+14 -5
View File
@@ -12,7 +12,7 @@ permissions: write-all
env:
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -35,6 +35,11 @@ jobs:
uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
@@ -43,7 +48,6 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
@@ -90,7 +94,7 @@ jobs:
mkdir -p /tmp/napcat-downloads
cd /tmp/napcat-downloads
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
NT_URL="https://qqdl.gtimg.cn/qqfile/QQNT/9.9.32/beta/a33ab721/QQ9.9.32.50969_x64.exe"
echo "Downloading QQ installer..."
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
@@ -414,12 +418,17 @@ jobs:
NapCat.Shell.Windows.OneKey.zip
draft: false
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- name: Update apifox
env:
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm i --ignore-scripts
pnpm run build:openapi
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
+1
View File
@@ -21,3 +21,4 @@ tests/run/
guild1.db-wal
guild1.db-shm
packages/napcat-develop/config/.env
.claude
+3 -9
View File
@@ -11,15 +11,9 @@ _Modern protocol-side framework implemented based on NTQQ._
---
## New Feature
## New Framework ?
在 v4.8.115+ 版本开始
1. NapCatQQ 支持 [Stream Api](https://napneko.github.io/develop/file)
2. NapCatQQ 推荐 message_id/user_id/group_id 均使用字符串类型
- [1] 解决 Docker/跨设备/大文件 的多媒体上下传问题
- [2] 采用字符串可以解决扩展到int64的问题,同时也可以解决部分语言(如JavaScript)对大整数支持不佳的问题,增加极少成本。
可以试试更新更好用的 [SnowLuma](https://github.com/SnowLuma/SnowLuma) 作为NapCat Gui替代品。
## Welcome
@@ -64,7 +58,7 @@ _Modern protocol-side framework implemented based on NTQQ._
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
下面的QQ Group 无需密钥,随时清理不活跃人员和Bot,仅500人容量。
社区相关日后会进一步加强审核,并严格限制一定时间的入群人数,请具备一定编程基础和问题解决能力再申请入群。
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
+8 -3
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2021",
"module": "ESNext",
"moduleResolution": "Node",
"moduleResolution": "bundler",
"lib": [
"ES2021"
],
@@ -34,10 +34,15 @@
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"napcat-common/src/*": [
"../../packages/napcat-common/src/*"
],
"napcat-image-size/src/*": [
"../../packages/napcat-image-size/src/*"
],
"@/*": [
"../*"
"../../packages/*"
]
},
"skipLibCheck": true,
+85 -4
View File
@@ -12,11 +12,17 @@ import {
ShutUpGroupMember,
Peer,
ChatType,
GroupManagementSettings,
} from '@/napcat-core/index';
import { isNumeric, solveAsyncProblem } from 'napcat-common/src/helper';
import { LimitedHashTable } from 'napcat-common/src/message-unique';
import { CancelableTask, TaskExecutor } from 'napcat-common/src/cancel-task';
import { createGroupDetailInfoV2Param, createGroupExtFilter, createGroupExtInfo } from '../data';
import {
createGroupDetailInfoV2Param,
createGroupExtFilter,
createGroupExtInfo,
createGroupManagementRequests,
} from '../data';
import { NTEventWrapper } from '../helper/event';
export class NTQQGroupApi {
@@ -25,7 +31,7 @@ export class NTQQGroupApi {
groupMemberCache: Map<string, Map<string, GroupMember>> = new Map<string, Map<string, GroupMember>>();
essenceLRU = new LimitedHashTable<number, string>(1000);
// psKey 滑动缓存,TTL 60 秒,惰性删除(不主动清理,等下次访问检测到过期再刷新)
private _qunPskeyCache: { value: string; expireAt: number } | null = null;
private _qunPskeyCache: { value: string; expireAt: number; } | null = null;
constructor (context: InstanceContext, core: NapCatCore) {
this.context = context;
@@ -168,6 +174,54 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
}
async setGroupMemberInvitePolicy (
groupCode: string,
policy: NonNullable<GroupManagementSettings['memberInvite']>
) {
return this.modifyGroupManagementSettings(groupCode, { memberInvite: policy });
}
async setGroupMemberPermissions (
groupCode: string,
permissions: Pick<
GroupManagementSettings,
'allowMemberUploadAlbum' | 'allowMemberTemporarySession' | 'allowMemberCreateGroup'
>
) {
return this.modifyGroupManagementSettings(groupCode, permissions);
}
async setGroupNewMemberHistoryVisibility (groupCode: string, visible: boolean) {
return this.modifyGroupManagementSettings(groupCode, { newMembersSeeRecentHistory: visible });
}
private async modifyGroupManagementSettings (groupCode: string, settings: GroupManagementSettings) {
const results: Array<{ setting: string, result: GeneralCallResult; }> = [];
const changesKnownFlags = settings.memberInvite !== undefined ||
settings.allowMemberUploadAlbum !== undefined ||
settings.allowMemberTemporarySession !== undefined ||
settings.allowMemberCreateGroup !== undefined ||
settings.newMembersSeeRecentHistory !== undefined;
const currentDetail = changesKnownFlags ? await this.fetchGroupDetail(groupCode) : undefined;
for (const request of createGroupManagementRequests(
groupCode,
settings,
currentDetail?.privilegeFlag,
currentDetail?.groupFlagExt4
)) {
results.push({
setting: request.setting,
result: await this.context.session.getGroupService().modifyGroupDetailInfoV2(
request.param,
request.operationType
),
});
}
return results;
}
async setGroupSearch (groupCode: string, option: {
noCodeFingerOpenFlag?: number;
noFingerOpenFlag?: number;
@@ -297,6 +351,15 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().getGroupRecommendContactArkJson(groupCode);
}
async getJoinGroupLink (groupCode: string, needShortUrl = true, srcId = 73, additionalParam = '') {
return this.context.session.getGroupService().getJoinGroupLink({
groupCode,
srcId,
needShortUrl,
additionalParam,
});
}
async creatGroupFileFolder (groupCode: string, folderName: string) {
return this.context.session.getRichMediaService().createGroupFolder(groupCode, folderName);
}
@@ -430,6 +493,24 @@ export class NTQQGroupApi {
return this.context.session.getRichMediaService().batchGetGroupFileCount(groupCodes);
}
// getGroupFileList also carries the group's used/total space in its call
// result's `groupSpaceResult`; a single-item fetch is enough to read it.
async getGroupFileSpace (groupCode: string) {
const [result] = await this.core.eventWrapper.callNormalEventV2(
'NodeIKernelRichMediaService/getGroupFileList',
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
[
groupCode,
{ sortType: 1, fileCount: 1, startIndex: 0, sortOrder: 1, showOnlinedocFolder: 0 },
],
() => true,
() => true,
1,
5000
);
return result?.groupSpaceResult;
}
async getArkJsonGroupShare (groupCode: string) {
const ret = await this.core.eventWrapper.callNoListenerEvent(
'NodeIKernelGroupService/getGroupRecommendContactArkJson',
@@ -482,8 +563,8 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().modifyMemberRole(groupCode, memberUid, role);
}
async setGroupName (groupCode: string, groupName: string) {
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, false);
async setGroupName (groupCode: string, groupName: string, isNormalMember: boolean = false) {
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, isNormalMember);
}
async publishGroupBulletin (groupCode: string, content: string, picInfo: {
+12
View File
@@ -67,6 +67,18 @@ export class NTQQMsgApi {
return this.context.session.getMsgService().fetchFavEmojiList('', num, true, true);
}
async addFavEmoji (req: Parameters<NodeIKernelMsgService['addFavEmoji']>[0]) {
return this.context.session.getMsgService().addFavEmoji(req);
}
async deleteFavEmoji (ids: string[]) {
return this.context.session.getMsgService().deleteFavEmoji(ids);
}
async modifyFavEmojiDesc (items: Parameters<NodeIKernelMsgService['modifyFavEmojiDesc']>[0]) {
return this.context.session.getMsgService().modifyFavEmojiDesc(items);
}
async queryMsgsWithFilterExWithSeq (peer: Peer, msgSeq: string) {
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
chatInfo: peer,
+17 -2
View File
@@ -36,7 +36,7 @@ export class NTQQPacketApi {
})
.catch((err) => {
this.logger.logError(err);
this.errStack.push(err);
this.pushError(err);
return false;
})) && this.pkt?.available;
}
@@ -46,7 +46,15 @@ export class NTQQPacketApi {
}
get clientLogStack () {
return this.pkt?.clientLogStack + '\n' + this.errStack.join('\n');
return [this.pkt?.clientLogStack, ...this.errStack].filter(Boolean).join('\n');
}
private pushError (error: unknown) {
if (error instanceof Error) {
this.errStack.push(error.stack || error.message);
return;
}
this.errStack.push(String(error));
}
async InitSendPacket (qqVer: string) {
@@ -67,10 +75,17 @@ export class NTQQPacketApi {
}
this.pkt = new PacketClientSession(this.core);
await this.pkt.init(process.pid, table.recv, table.send);
if (!this.pkt.available) {
const err = '[Core] [Packet] NativePacketClient 初始化失败,PacketBackend 发包能力不可用!';
this.logger.logError(err);
this.errStack.push(err);
return false;
}
try {
await this.pkt.operation.FetchRkey(3000);
} catch (error) {
this.logger.logError('测试Packet状态异常', error);
this.pushError(error);
return false;
}
return true;
+143 -7
View File
@@ -13,6 +13,17 @@ import { createHash } from 'node:crypto';
import { basename } from 'node:path';
import { qunAlbumControl } from '../data/webapi';
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
buildQzoneUploadImageBody,
parseQzoneDeleteResponse,
parseQzonePublishResponse,
parseQzoneUploadImageResponseText,
toQzoneRichval,
QzoneDeleteResponse,
QzonePublishResponse,
} from '../data/qzone';
export interface SetNoticeRetSuccess {
ec: number;
em: string;
@@ -507,20 +518,145 @@ export class NTQQWebApi {
async doAlbumMediaLikeByNTQQ (
qunId: string,
albumId: string,
lloc: string,
id: string) {
batchId: string,
lloc: string | undefined,
isLike: boolean
) {
const random_seq = Math.floor(Math.random() * 9000) + 1000;
const uin = this.core.selfInfo.uin || '10001';
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${qunId}|${albumId}|${batchId}^||^421_1_0_${qunId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${qunId}|${albumId}|${batchId}`;
}
return await this.context.session.getAlbumService().doQunLike(
random_seq, {
random_seq,
{
map_info: [],
map_bytes_info: [],
map_user_account: [],
}, {
id,
status: 1,
},
createAlbumFeedPublish(qunId, uin, albumId, lloc)
type,
{
id,
status,
},
createAlbumFeedPublish(qunId, uin, albumId, batchId)
);
}
private async getQzoneAuth () {
const skey = await this.core.apis.UserApi.getSKey() || '';
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
const uin = this.core.selfInfo.uin || '10001';
const g_tk = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
return { skey, pskey, uin, g_tk, cookie };
}
/**
* 上传图片到 QQ 空间相册, 返回可用于发说说的 richval 字符串
* @param base64 图片Base64编码内容(不带data:前缀)
*/
async uploadImageToQzone (base64: string): Promise<string> {
const { skey, pskey, uin, g_tk, cookie } = await this.getQzoneAuth();
const body = buildQzoneUploadImageBody({ uin, skey, pskey, g_tk, base64 });
const api = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
const resultText = await RequestUtil.HttpGetText(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
});
const parsed = parseQzoneUploadImageResponseText(resultText);
if (parsed.code !== undefined && parsed.code !== 0) {
throw new Error(parsed.msg || `QQ空间图片上传失败, code=${parsed.code}`);
}
if (!parsed.data) {
throw new Error('QQ空间图片上传失败, 响应缺少data字段');
}
return toQzoneRichval(parsed.data);
}
/**
* 发表QQ空间说说
* @param content 说说正文
* @param richvals 每张图片对应的richval数组, 为空表示纯文字说说
* @param ugcRight 查看权限 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见
* @param targetUins 权限作用QQ号数组, ugcRight为16/128时使用
*/
async publishQzoneMsg (content: string, richvals: string[], ugcRight: number, targetUins?: number[]) {
const { uin, g_tk, cookie } = await this.getQzoneAuth();
const richval = richvals.length > 0 ? richvals.join('\t') : undefined;
const allowUins = targetUins && targetUins.length > 0 ? targetUins.join('|') : undefined;
const body = buildQzonePublishBody({
hostuin: uin,
content,
richval,
ugcRight,
allowUins,
});
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${g_tk}`;
const result = await RequestUtil.HttpGetJson<QzonePublishResponse>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
}, true, false);
return parseQzonePublishResponse(result);
}
/**
* 删除QQ空间说说
* @param tid 说说Tid, 来自 publishQzoneMsg 的返回值
*/
async deleteQzoneMsg (tid: string) {
const { uin, g_tk, cookie } = await this.getQzoneAuth();
const body = buildQzoneDeleteBody({ hostuin: uin, tid });
const api = `https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6?g_tk=${g_tk}`;
const result = await RequestUtil.HttpGetJson<QzoneDeleteResponse>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/x-www-form-urlencoded',
}, true, false);
return parseQzoneDeleteResponse(result);
}
async getDaySignedList (groupCode: string) {
const pSkey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const selfUin = this.core.selfInfo.uin;
const cookie = `p_uin=o${selfUin}; p_skey=${pSkey}; uin=o${selfUin}`;
const post = await RequestUtil.HttpGetJson<{
retCode: number,
costTime: number,
response: {
ret?: {
code: string,
msg: string,
},
page?: {
infos?: {
uid: string,
uidGroupNick: string,
signedTimeStamp: string,
signInRank: number,
}[],
offset: number,
total: number,
}[],
},
funcCode: number,
}>(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${this.getBknFromPSKey(pSkey)}`, 'POST', {
dayYmd: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
}, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
}
+8 -17
View File
@@ -163,14 +163,14 @@ export interface AlbumFeedLikePublish {
};
cell_media: {
album_id: string;
batch_id: number;
media_items: Array<{
batch_id: string | number;
media_items?: {
type: number;
image: {
lloc: string;
sloc: string;
};
}>;
}[];
};
cell_qun_info: {
qun_id: string;
@@ -182,21 +182,19 @@ export interface AlbumFeedLikePublish {
* @param qunId 群号
* @param uin 用户QQ号
* @param albumId 相册ID
* @param lloc 信息
* @param sloc 信息(可选,默认与lloc相同)
* @param batchId 批次ID
* @returns 动态发布请求参数对象
*/
export function createAlbumFeedPublish (
qunId: string,
uin: string,
albumId: string,
lloc: string,
sloc?: string
): AlbumFeedLikePublish {
batchId: string
) {
return {
cell_common: {
time: Date.now(),
feed_id: '',
feed_id: `422_0_${batchId}`, // 需要补全feed_id
},
cell_user_info: {
user: {
@@ -205,14 +203,7 @@ export function createAlbumFeedPublish (
},
cell_media: {
album_id: albumId,
batch_id: 0,
media_items: [{
type: 0,
image: {
lloc,
sloc: sloc || lloc,
},
}],
batch_id: batchId,
},
cell_qun_info: {
qun_id: qunId,
+139 -1
View File
@@ -1,4 +1,142 @@
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter } from '../types';
import { GroupDetailInfoV2Param, GroupExtInfo, GroupExtFilter, GroupManagementSettings } from '../types';
const MEMBER_INVITE_PRIVILEGE_MASK = 0x06100000;
const MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK = 0x1;
const MEMBER_CREATE_GROUP_FLAG = 0x8000;
const MEMBER_TEMPORARY_SESSION_FLAG = 0x10000;
const NEW_MEMBER_RECENT_HISTORY_FLAG = 0x4;
function mergeMaskedFlag (currentFlag: number, requestedFlag: number, maskValue: number): number {
const mask = BigInt(maskValue);
return Number((BigInt(currentFlag) & ~mask) | (BigInt(requestedFlag) & mask));
}
export function applyGroupManagementSettings (
param: GroupDetailInfoV2Param,
settings: GroupManagementSettings
): boolean {
let changed = false;
if (settings.memberInvite !== undefined) {
const privilegeByPolicy = {
disabled: 0x04000000,
require_approval: 0,
no_approval: 0x00100000,
no_approval_under_100: 0x02000000,
} satisfies Record<NonNullable<GroupManagementSettings['memberInvite']>, number>;
param.filter.allowMemberInvite = 1;
param.modifyInfo.allowMemberInvite = settings.memberInvite === 'disabled' ? 0 : 1;
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_INVITE_PRIVILEGE_MASK;
param.modifyInfo.appPrivilegeFlag |= privilegeByPolicy[settings.memberInvite];
changed = true;
}
if (settings.allowMemberUploadAlbum !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
if (!settings.allowMemberUploadAlbum) param.modifyInfo.appPrivilegeFlag |= MEMBER_UPLOAD_ALBUM_PRIVILEGE_MASK;
changed = true;
}
if (settings.allowMemberTemporarySession !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_TEMPORARY_SESSION_FLAG;
if (!settings.allowMemberTemporarySession) param.modifyInfo.appPrivilegeFlag |= MEMBER_TEMPORARY_SESSION_FLAG;
changed = true;
}
if (settings.allowMemberCreateGroup !== undefined) {
param.filter.appPrivilegeFlag = 1;
param.filter.appPrivilegeMask = 1;
param.modifyInfo.appPrivilegeMask |= MEMBER_CREATE_GROUP_FLAG;
if (!settings.allowMemberCreateGroup) param.modifyInfo.appPrivilegeFlag |= MEMBER_CREATE_GROUP_FLAG;
changed = true;
}
if (settings.newMembersSeeRecentHistory !== undefined) {
param.filter.groupFlagExt4 = 1;
param.filter.groupFlagExt4Mask = 1;
param.modifyInfo.groupFlagExt4Mask |= NEW_MEMBER_RECENT_HISTORY_FLAG;
if (settings.newMembersSeeRecentHistory) param.modifyInfo.groupFlagExt4 |= NEW_MEMBER_RECENT_HISTORY_FLAG;
changed = true;
}
return changed;
}
export function createGroupManagementRequests (
groupCode: string,
settings: GroupManagementSettings,
initialAppPrivilegeFlag = 0,
initialGroupFlagExt4 = 0
) {
const requests: Array<{ setting: string, param: GroupDetailInfoV2Param, operationType: number; }> = [];
const requestSettings: Array<{
setting: string,
value: GroupManagementSettings,
operationType: number;
}> = [
{ setting: 'member_invite', value: { memberInvite: settings.memberInvite }, operationType: 0 },
{
setting: 'new_members_see_recent_history',
value: { newMembersSeeRecentHistory: settings.newMembersSeeRecentHistory },
operationType: 0,
},
{
setting: 'allow_member_upload_album',
value: { allowMemberUploadAlbum: settings.allowMemberUploadAlbum },
operationType: 8,
},
{
setting: 'allow_member_temporary_session',
value: { allowMemberTemporarySession: settings.allowMemberTemporarySession },
operationType: 8,
},
{
setting: 'allow_member_create_group',
value: { allowMemberCreateGroup: settings.allowMemberCreateGroup },
operationType: 8,
},
];
let currentAppPrivilegeFlag = initialAppPrivilegeFlag;
let currentGroupFlagExt4 = initialGroupFlagExt4;
for (const requestSetting of requestSettings) {
const param = createGroupDetailInfoV2Param(groupCode);
if (applyGroupManagementSettings(param, requestSetting.value)) {
if (param.filter.appPrivilegeFlag) {
const nextAppPrivilegeFlag = mergeMaskedFlag(
currentAppPrivilegeFlag,
param.modifyInfo.appPrivilegeFlag,
param.modifyInfo.appPrivilegeMask
);
if (requestSetting.operationType === 8 && nextAppPrivilegeFlag === currentAppPrivilegeFlag) continue;
currentAppPrivilegeFlag = nextAppPrivilegeFlag;
// Linux NTQQ's wrapper builds this field from the current complete privilege value.
// Supplying only the targeted bit makes zero-valued clears get acknowledged but ignored.
param.modifyInfo.appPrivilegeFlag = currentAppPrivilegeFlag;
}
if (param.filter.groupFlagExt4) {
const nextGroupFlagExt4 = mergeMaskedFlag(
currentGroupFlagExt4,
param.modifyInfo.groupFlagExt4,
param.modifyInfo.groupFlagExt4Mask
);
if (nextGroupFlagExt4 === currentGroupFlagExt4) continue;
currentGroupFlagExt4 = nextGroupFlagExt4;
param.modifyInfo.groupFlagExt4 = currentGroupFlagExt4;
}
requests.push({ setting: requestSetting.setting, param, operationType: requestSetting.operationType });
}
}
return requests;
}
export function createGroupDetailInfoV2Param (group_code: string): GroupDetailInfoV2Param {
return {
+199
View File
@@ -0,0 +1,199 @@
/**
* QQ空间(Qzone)发说说/上传图片相关的纯数据构造与解析函数
* 不发起任何网络请求,方便单独测试
*/
export interface QzoneUploadImageParams {
uin: string;
skey: string;
pskey: string;
g_tk: string;
base64: string;
}
/**
* 构造上传图片到 QQ 空间的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image
*/
export function buildQzoneUploadImageBody (params: QzoneUploadImageParams): string {
const { uin, skey, pskey, g_tk, base64 } = params;
const backUrls = `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${g_tk}`;
const query = new URLSearchParams({
filename: 'filename',
uin,
skey,
zzpaneluin: uin,
p_uin: uin,
p_skey: pskey,
uploadtype: '1',
albumtype: '7',
exttype: '0',
refer: 'shuoshuo',
output_type: 'jsonhtml',
charset: 'utf-8',
output_charset: 'utf-8',
upload_hd: '1',
hd_width: '2048',
hd_height: '10000',
hd_quality: '96',
backUrls,
base64: '1',
jsonhtml_callback: 'callback',
picfile: base64,
qzreferrer: `https://user.qzone.qq.com/${uin}/main`,
});
return query.toString();
}
export interface QzoneUploadImageData {
albumid: string;
lloc: string;
type: string;
height: string;
width: string;
url?: string;
}
export interface QzoneUploadImageRawResponse {
code?: number;
msg?: string;
data?: QzoneUploadImageData;
}
/**
* 解析上传图片接口返回的 `frameElement.callback({...});</script>` 包裹响应
*/
export function parseQzoneUploadImageResponseText (raw: string): QzoneUploadImageRawResponse {
const startTag = 'frameElement.callback';
const endTag = '</script>';
const startIdx = raw.indexOf(startTag);
const endIdx = raw.indexOf(endTag);
if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
throw new Error('QQ空间图片上传响应格式异常');
}
const segment = raw.slice(startIdx + startTag.length, endIdx);
const jsonStart = segment.indexOf('(');
const jsonEnd = segment.lastIndexOf(')');
if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
throw new Error('QQ空间图片上传响应解析失败');
}
const jsonText = segment.slice(jsonStart + 1, jsonEnd);
try {
return JSON.parse(jsonText) as QzoneUploadImageRawResponse;
} catch {
throw new Error('QQ空间图片上传响应JSON解析失败');
}
}
/**
* 依据上传图片返回数据拼接 richval 字段
* 格式: ,albumid,lloc,sloc,type,height,width,,height,width (sloc 与 lloc 一致)
*/
export function toQzoneRichval (data: QzoneUploadImageData): string {
const { albumid, lloc, type, height, width } = data;
return `,${albumid},${lloc},${lloc},${type},${height},${width},,${height},${width}`;
}
export interface QzonePublishParams {
hostuin: string;
content: string;
/** 多张图片使用 \t 拼接后的 richval,无图时不传 */
richval?: string;
ugcRight: number;
/** ugc_right 为 16/128 时必填,多个QQ号使用 | 拼接 */
allowUins?: string;
}
/**
* 构造发表说说的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6
*/
export function buildQzonePublishBody (params: QzonePublishParams): string {
const { hostuin, content, richval, ugcRight, allowUins } = params;
const fields: Record<string, string> = {
syn_tweet_verson: '1',
paramstr: '1',
con: content,
feedversion: '1',
ver: '1',
ugc_right: String(ugcRight),
to_sign: '0',
hostuin,
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostuin}/main`,
};
if (richval) {
fields['richtype'] = '1';
fields['richval'] = richval;
}
if (allowUins) {
fields['allow_uins'] = allowUins;
fields['who'] = '1';
}
return new URLSearchParams(fields).toString();
}
export interface QzonePublishResponse {
subcode?: number;
code?: number;
tid?: string;
t1_tid?: string;
message?: string;
msg?: string;
}
/**
* 解析发表说说接口返回的 JSON, 提取 tid
*/
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; } {
const subcode = json.subcode ?? json.code;
if (subcode !== undefined && subcode !== 0) {
throw new Error(json.message || json.msg || `QQ空间发说说失败, subcode=${subcode}`);
}
const tid = json.t1_tid || json.tid;
if (!tid) {
throw new Error('QQ空间发说说失败, 未返回tid');
}
return { tid };
}
export interface QzoneDeleteParams {
hostuin: string;
tid: string;
}
/**
* 构造删除说说的表单请求体 (application/x-www-form-urlencoded)
* 对齐 https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6
*/
export function buildQzoneDeleteBody (params: QzoneDeleteParams): string {
const { hostuin, tid } = params;
const fields: Record<string, string> = {
hostuin,
tid,
t1_source: '1',
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostuin}`,
};
return new URLSearchParams(fields).toString();
}
export interface QzoneDeleteResponse {
subcode?: number;
code?: number;
message?: string;
msg?: string;
}
/**
* 解析删除说说接口返回的 JSON
*/
export function parseQzoneDeleteResponse (json: QzoneDeleteResponse): { success: true; } {
const subcode = json.subcode ?? json.code;
if (subcode !== undefined && subcode !== 0) {
throw new Error(json.message || json.msg || `QQ空间删说说失败, subcode=${subcode}`);
}
return { success: true };
}
+44
View File
@@ -566,5 +566,49 @@
"6.9.93-47354": {
"appid": 537346896,
"qua": "V1_MAC_NQ_6.9.93_47354_GW_B"
},
"9.9.30-48517": {
"appid": 537352474,
"qua": "V1_WIN_NQ_9.9.30_48517_GW_B"
},
"3.2.28-48517": {
"appid": 537352510,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"9.9.30-48762": {
"appid": 537352525,
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
},
"9.9.31-49599": {
"appid": 537355779,
"qua": "V1_WIN_NQ_9.9.31_49599_GW_B"
},
"9.9.31-49738": {
"appid": 537355830,
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
},
"3.2.29-49738": {
"appid": 537355867,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"9.9.32-50828": {
"appid": 537358739,
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
},
"3.2.30-50828": {
"appid": 537358775,
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
},
"9.9.32-50969": {
"appid": 537376308,
"qua": "V1_WIN_NQ_9.9.32_50969_GW_B"
},
"3.2.30-50969": {
"appid": 537376344,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"9.9.32-55230": {
"appid": 537379411,
"qua": "V1_WIN_NQ_9.9.32_55230_GW_B"
}
}
+165
View File
@@ -2593,6 +2593,171 @@
"AniStickerType": 1,
"AniStickerPackId": "1",
"AniStickerId": "59"
},
{
"QSid": "450",
"QDes": "/撇嘴",
"EMCode": "10450"
},
{
"QSid": "451",
"QDes": "/色",
"EMCode": "10451"
},
{
"QSid": "452",
"QDes": "/微笑",
"EMCode": "10452"
},
{
"QSid": "453",
"QDes": "/发呆",
"EMCode": "10453"
},
{
"QSid": "454",
"QDes": "/得意",
"EMCode": "10454"
},
{
"QSid": "455",
"QDes": "/害羞",
"EMCode": "10455"
},
{
"QSid": "456",
"QDes": "/闭嘴",
"EMCode": "10456"
},
{
"QSid": "457",
"QDes": "/睡",
"EMCode": "10457"
},
{
"QSid": "458",
"QDes": "/我吗",
"EMCode": "10458"
},
{
"QSid": "459",
"QDes": "/优雅",
"EMCode": "10459"
},
{
"QSid": "460",
"QDes": "/硬撑",
"EMCode": "10460"
},
{
"QSid": "461",
"QDes": "/宕机",
"EMCode": "10461"
},
{
"QSid": "462",
"QDes": "/无语",
"EMCode": "10462"
},
{
"QSid": "463",
"QDes": "/新年快乐",
"EMCode": "10463"
},
{
"QSid": "464",
"QDes": "/马上到",
"EMCode": "10464"
},
{
"QSid": "465",
"QDes": "/拆红包",
"EMCode": "10465"
},
{
"QSid": "466",
"QDes": "/羞羞哒",
"EMCode": "10466"
},
{
"QSid": "467",
"QDes": "/摇花手",
"EMCode": "10467"
},
{
"QSid": "468",
"QDes": "/失眠",
"EMCode": "10468"
},
{
"QSid": "469",
"QDes": "/坚毅",
"EMCode": "10469"
},
{
"QSid": "470",
"QDes": "/马到成功",
"EMCode": "10470"
},
{
"QSid": "472",
"QDes": "/心动",
"EMCode": "10472"
},
{
"QSid": "474",
"QDes": "/给你一拳",
"EMCode": "10474"
},
{
"QSid": "475",
"QDes": "/干饭",
"EMCode": "10475"
},
{
"QSid": "476",
"QDes": "/不是吧",
"EMCode": "10476"
},
{
"QSid": "477",
"QDes": "/你懂的",
"EMCode": "10477"
},
{
"QSid": "478",
"QDes": "/对的对的",
"EMCode": "10478"
},
{
"QSid": "479",
"QDes": "/不对不对",
"EMCode": "10479"
},
{
"QSid": "480",
"QDes": "/散味儿",
"EMCode": "10480"
},
{
"QSid": "481",
"QDes": "/学习",
"EMCode": "10481"
},
{
"QSid": "482",
"QDes": "/热化了",
"EMCode": "10482"
},
{
"QSid": "483",
"QDes": "/略",
"EMCode": "10483"
},
{
"QSid": "484",
"QDes": "/比爱心",
"EMCode": "10484"
}
],
"emoji": [
+60
View File
@@ -222,5 +222,65 @@
"6.9.93-47354-x64": {
"send": "28ADE46",
"recv": "0A8FD5A"
},
"9.9.30-48517-x64": {
"send": "0A9B1BC",
"recv": "1F0324D"
},
"3.2.28-48517-x64": {
"send": "5E41890",
"recv": "3216D10"
},
"3.2.28-48517-arm64": {
"send": "3F9C7E4",
"recv": "14E1AA8"
},
"9.9.30-48762-x64": {
"send": "0A9B1BC",
"recv": "1F0324D"
},
"9.9.31-49599-x64": {
"send": "0AF885C",
"recv": "20058E1"
},
"9.9.31-49738-x64": {
"send": "0AF9FCC",
"recv": "2007901"
},
"3.2.29-49738-x64": {
"send": "6234600",
"recv": "33D89D0"
},
"3.2.29-49738-arm64": {
"send": "426AA04",
"recv": "1596254"
},
"9.9.32-50828-x64": {
"send": "0B245CC",
"recv": "2073D65"
},
"3.2.30-50828-x64": {
"send": "6340530",
"recv": "346DA50"
},
"3.2.30-50828-arm64": {
"send": "4327764",
"recv": "15e3184"
},
"9.9.32-50969-x64": {
"send": "0B2E2AC",
"recv": "209C709"
},
"3.2.30-50969-x64": {
"send": "63F47B0",
"recv": "34B9E30"
},
"3.2.30-50969-arm64": {
"send": "43A4804",
"recv": "1608CC8"
},
"9.9.32-55230-x64": {
"send": "367FE18",
"recv": "36835CC"
}
}
+56
View File
@@ -730,5 +730,61 @@
"6.9.93-47354-x64": {
"send": "47CD940",
"recv": "47D04F0"
},
"3.2.28-48517-x64": {
"send": "AD7C280",
"recv": "AD7FD20"
},
"9.9.30-48517-x64": {
"send": "2F3B960",
"recv": "2F3EEE0"
},
"3.2.28-48517-arm64": {
"send": "6F48B70",
"recv": "6F4C520"
},
"9.9.30-48762-x64": {
"send": "2F3B960",
"recv": "2F3EEE0"
},
"9.9.31-49599-x64": {
"send": "3082C40",
"recv": "30861C8"
},
"9.9.31-49738-x64": {
"send": "3086C80",
"recv": "308A208"
},
"3.2.29-49738-x64": {
"send": "B3B20A0",
"recv": "B3B5B40"
},
"3.2.29-49738-arm64": {
"send": "7342800",
"recv": "73461B0"
},
"9.9.32-50828-x64": {
"send": "3155200",
"recv": "3158788"
},
"9.9.32-50828-arm64": {
"send": "4327764",
"recv": "15E3184"
},
"3.2.30-50828-x64": {
"send": "B5D0FC0",
"recv": "B5D4A60"
},
"9.9.32-50969-x64": {
"send": "31994E0",
"recv": "319CA68"
},
"3.2.30-50969-x64": {
"send": "B7394C0",
"recv": "B73CF60"
},
"3.2.30-50969-arm64": {
"send": "75BD1D0",
"recv": "75C0B80"
}
}
@@ -21,13 +21,13 @@ export interface VideoInfo {
/** Video duration in seconds */
duration: number;
/** Container format name (e.g., "mp4", "mkv", "avi") */
/** Generated thumbnail image format */
format: string;
/** Video codec name (e.g., "h264", "hevc", "vp9") */
videoCodec: string;
/** First frame thumbnail as BMP image buffer */
/** First frame thumbnail as JPEG image buffer */
image: Buffer;
}
@@ -138,14 +138,14 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
/**
* 获取时长
*/
async getDuration(filePath: string): Promise<number> {
async getDuration (filePath: string): Promise<number> {
const { stdout } = await execFileAsync(this.ffprobePath, [
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=noprint_wrappers=1:nokey=1',
filePath,
]);
@@ -6,6 +6,7 @@ import { platform } from 'node:os';
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegAdapterFactory } from './ffmpeg-adapter-factory';
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
if (process.platform === 'win32' && binaryPath) {
@@ -94,6 +95,15 @@ export class FFmpegService {
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 直接发送到 QQ kernel 的旧视频元素使用 PNG 缩略图。
* Packet/forward 路径继续使用当前适配器生成的 JPEG。
*/
public static async extractLegacyVideoThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 转换音频文件
*/
+3 -3
View File
@@ -187,14 +187,14 @@ export class LogWrapper implements ILogWrapper {
_log (level: LogLevel, ...args: any[]) {
if (this.consoleLogEnabled || this.fileLogEnabled) {
const message = this.formatMsg(args);
// eslint-disable-next-line no-control-regex
const message = this.formatMsg(args).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\x1B\[[0-?]*[ -/]*[@-~]|\x1B/g, '');
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
// eslint-disable-next-line no-control-regex
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
this.logger.log(level, message);
}
logSubscription.notify(JSON.stringify({ level, message }));
}
+11 -1
View File
@@ -107,10 +107,20 @@ export class RkeyManager {
for (const url of availableUrls) {
try {
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
if ('retcode' in temp) {
if (typeof temp === 'object' && temp !== null && 'retcode' in temp) {
// 支持Onebot Ret风格
temp = (temp as unknown as OneBotApiRet).data;
}
if (
typeof temp?.group_rkey !== 'string' ||
typeof temp?.private_rkey !== 'string' ||
typeof temp?.expired_time !== 'number' ||
temp.group_rkey.length <= 6 ||
temp.private_rkey.length <= 6 ||
temp.expired_time <= 0
) {
throw new Error('Rkey 服务返回格式无效:group_rkey/private_rkey/expired_time 缺失或不合法');
}
this.rkeyData = {
group_rkey: temp.group_rkey.slice(6),
private_rkey: temp.private_rkey.slice(6),
@@ -39,12 +39,17 @@ export class NativePacketClient {
async init (_pid: number, recv: string, send: string): Promise<void> {
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
if (isNewQQ) {
const success = this.napi2nativeLoader.initHook(send, recv);
if (success) {
this.available = true;
}
if (!isNewQQ) {
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
return;
}
const success = this.napi2nativeLoader.initHook(send, recv);
if (success) {
this.available = true;
this.logStack.pushLogInfo(`[PacketClient] NativePacketClient Hook 初始化成功 platform=${process.platform}.${process.arch}`);
return;
}
this.logStack.pushLogError(`[PacketClient] NativePacketClient Hook 初始化失败 platform=${process.platform}.${process.arch} send=${send} recv=${recv}`);
}
async sendPacket (
@@ -19,6 +19,7 @@ import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
import { gunzipSync } from 'zlib';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
export class PacketOperationContext {
private readonly context: PacketContext;
@@ -105,15 +106,7 @@ export class PacketOperationContext {
.filter(Boolean)
);
const res = await Promise.allSettled(reqList);
const failedCount = res.filter((r) => r.status === 'rejected').length;
if (failedCount > 0) {
this.context.logger.warn(`上传资源${res.length}个,失败${failedCount}个`);
res.forEach((result, index) => {
if (result.status === 'rejected') {
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
}
});
}
assertUploadResults(res, this.context.logger);
}
async UploadImage (img: PacketMsgPicElement) {
@@ -240,9 +233,10 @@ export class PacketOperationContext {
}
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
// await this.SendPreprocess(msg, groupUin);
// 遍历上传资源(跳过已有原始数据的项)
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
await Promise.all(msg.filter(item => item.actionMsg).map(async (item) => {
await this.SendPreprocess(item.actionMsg!, groupUin);
}));
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.UploadForwardMsg.parse(resp);
@@ -370,11 +364,39 @@ export class PacketOperationContext {
}
return element;
}
if (element.videoElement && rawElem?.commonElem?.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
const index = extra?.msgInfoBody[0]?.index;
if (!index) return element;
if (msg?.responseHead.grp !== undefined) {
element.videoElement = {
...element.videoElement,
filePath: await this.GetGroupVideoUrl(msg.responseHead.grp.groupUin ?? 0, index),
};
} else {
element.videoElement = {
...element.videoElement,
filePath: await this.GetVideoUrl(this.context.napcore.basicInfo.uid, index),
};
}
return element;
}
return element;
})
);
const isGroup = msg?.responseHead.grp !== undefined;
const peerUin = isGroup
? String(msg?.responseHead.grp?.groupUin ?? 0)
: String(msg?.responseHead.fromUin ?? 0);
const peerUid = isGroup
? String(msg?.responseHead.grp?.groupUin ?? 0)
: String(msg?.responseHead.fromUid ?? '');
const sendNickName = isGroup
? (msg?.responseHead.grp?.memberName ?? '')
: (msg?.responseHead.forward?.friendName ?? '');
return {
chatType: ChatType.KCHATTYPEGROUP,
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
elements,
guildId: '',
isOnlineMsg: false,
@@ -385,18 +407,18 @@ export class PacketOperationContext {
msgType: NTMsgType.KMSGTYPEMIX,
parentMsgIdList: [],
parentMsgPeer: {
chatType: ChatType.KCHATTYPEGROUP,
peerUid: String(msg?.responseHead.grp?.groupUin ?? 0),
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
peerUid,
},
peerName: '',
peerUid: '1094950020',
peerUin: '1094950020',
peerUid,
peerUin,
recallTime: '0',
records: [],
sendNickName: msg?.responseHead.grp?.memberName ?? '',
sendRemarkName: msg?.responseHead.grp?.memberName ?? '',
senderUid: '',
senderUin: '1094950020',
sendNickName,
sendRemarkName: sendNickName,
senderUid: msg?.responseHead.fromUid ?? '',
senderUin: String(msg?.responseHead.fromUin ?? 0),
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
subMsgType: 1,
};
@@ -0,0 +1,26 @@
export interface UploadResultLogger {
warn (message: string): unknown;
error (message: string): unknown;
}
export function assertUploadResults (
results: PromiseSettledResult<unknown>[],
logger: UploadResultLogger
): void {
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failures.length === 0) return;
logger.warn(`上传资源${results.length}个,失败${failures.length}个`);
results.forEach((result, index) => {
if (result.status === 'rejected') {
const reason = result.reason instanceof Error
? result.reason.stack ?? result.reason.message
: String(result.reason);
logger.error(`上传第${index + 1}个资源失败:${reason}`);
}
});
throw new AggregateError(
failures.map(result => result.reason),
`上传转发消息资源失败:${failures.length}/${results.length}`
);
}
@@ -21,8 +21,11 @@ import { PacketClientContext } from '@/napcat-core/packet/context/clientContext'
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
import { calculateFileMD5 } from 'napcat-common/src/file';
import { randomUUID } from 'node:crypto';
import { imageSizeFallBack } from 'napcat-image-size/src/index';
export const BlockSize = 1024 * 1024;
const VIDEO_THUMBNAIL_MAX_BYTES = 1024 * 1024;
interface HighwayServerAddr {
ip: string;
@@ -110,22 +113,37 @@ export class PacketHighwayContext {
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
}
// 如果缺少视频缩略图,自动生成一个
let tempThumbPath: string | null = null;
let thumbExists = false;
if (video.thumbPath) {
try {
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
thumbExists = true;
} catch {
thumbExists = false;
}
}
if (!video.thumbPath || !thumbExists) {
tempThumbPath = await this.ensureVideoThumb(video);
}
const cleanupThumbPaths: string[] = [];
try {
let thumbExists = false;
if (video.thumbPath) {
try {
await fs.promises.access(video.thumbPath, fs.constants.F_OK);
thumbExists = true;
} catch {
thumbExists = false;
}
}
let shouldGenerateThumb = !video.thumbPath || !thumbExists;
if (!shouldGenerateThumb) {
try {
await this.updateVideoThumbInfo(video);
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
this.logger.warn(`[Highway] Video thumbnail is too large: ${video.thumbSize} bytes, regenerating`);
shouldGenerateThumb = true;
}
} catch (e) {
this.logger.warn(`[Highway] Failed to inspect video thumbnail, regenerating. Reason: ${e instanceof Error ? e.message : e}`);
shouldGenerateThumb = true;
}
}
if (shouldGenerateThumb) {
cleanupThumbPaths.push(await this.ensureVideoThumb(video));
}
video.businessType = peer.chatType === ChatType.KCHATTYPEGROUP ? 21 : 11;
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupVideo(+peer.peerUid, video);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
@@ -134,23 +152,21 @@ export class PacketHighwayContext {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
} finally {
// 清理临时生成的缩略图文件
if (tempThumbPath) {
const thumbToClean = tempThumbPath;
fs.promises.unlink(thumbToClean)
.then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`))
.catch((e) => {
// 文件不存在时忽略错误
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
}
});
}
await Promise.allSettled(cleanupThumbPaths.map(async (thumbToClean) => {
try {
await fs.promises.unlink(thumbToClean);
this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
}
}
}));
}
}
/**
* 确保视频缩略图存在,如果不存在则自动生成
* 使用当前 FFmpeg 适配器生成符合 QQ 大小限制的视频缩略图
* @returns 生成的临时缩略图路径,用于后续清理
*/
private async ensureVideoThumb (video: PacketMsgVideoElement): Promise<string> {
@@ -161,9 +177,10 @@ export class PacketHighwayContext {
// 生成缩略图路径
const videoDir = path.dirname(video.filePath);
const videoBasename = path.basename(video.filePath, path.extname(video.filePath));
const thumbPath = path.join(videoDir, `${videoBasename}_thumb.png`);
const thumbPath = path.join(videoDir, `${videoBasename}_thumb_${randomUUID()}.jpg`);
this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
video.thumbPath = thumbPath;
try {
// 尝试使用 FFmpeg 提取视频缩略图
@@ -174,26 +191,36 @@ export class PacketHighwayContext {
} catch {
throw new Error('FFmpeg failed to generate thumbnail');
}
await this.updateVideoThumbInfo(video);
if ((video.thumbSize ?? 0) > VIDEO_THUMBNAIL_MAX_BYTES) {
throw new Error(`generated thumbnail is too large: ${video.thumbSize} bytes`);
}
} catch (e) {
// FFmpeg 失败时(包括未初始化的情况)使用默认缩略图
this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
await fs.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
await this.updateVideoThumbInfo(video);
}
// 更新视频元素的缩略图信息
video.thumbPath = thumbPath;
const thumbStat = await fs.promises.stat(thumbPath);
video.thumbSize = thumbStat.size;
video.thumbMd5 = await calculateFileMD5(thumbPath);
// 默认缩略图尺寸(与 defaultVideoThumbB64 匹配的尺寸)
if (!video.thumbWidth) video.thumbWidth = 240;
if (!video.thumbHeight) video.thumbHeight = 383;
this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
return thumbPath;
}
private async updateVideoThumbInfo (video: PacketMsgVideoElement): Promise<void> {
if (!video.thumbPath) {
throw new Error('video.thumbPath is empty, cannot inspect thumbnail');
}
const [thumbStat, thumbMd5, dimensions] = await Promise.all([
fs.promises.stat(video.thumbPath),
calculateFileMD5(video.thumbPath),
imageSizeFallBack(video.thumbPath),
]);
video.thumbSize = thumbStat.size;
video.thumbMd5 = thumbMd5;
video.thumbWidth = dimensions.width;
video.thumbHeight = dimensions.height;
this.logger.debug(`[Highway] Video thumbnail ready: ${dimensions.width}x${dimensions.height}, ${thumbStat.size} bytes`);
}
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
await this.checkAvailable();
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
@@ -296,13 +323,17 @@ export class PacketHighwayContext {
const req = trans.UploadGroupVideo.build(groupUin, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadGroupVideo.parse(resp);
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
if (!videoIndex || !thumbIndex) {
throw new Error('[Highway] uploadGroupVideo response is missing video or thumbnail MsgInfo');
}
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
fileUuid: videoIndex.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -324,16 +355,15 @@ export class PacketHighwayContext {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
if (subFile?.uKey && subFile.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -349,7 +379,7 @@ export class PacketHighwayContext {
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
@@ -361,13 +391,17 @@ export class PacketHighwayContext {
const req = trans.UploadPrivateVideo.build(peerUid, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivateVideo.parse(resp);
const videoIndex = preRespData.upload.msgInfo.msgInfoBody[0]?.index;
const thumbIndex = preRespData.upload.msgInfo.msgInfoBody[1]?.index;
if (!videoIndex || !thumbIndex) {
throw new Error('[Highway] uploadC2CVideo response is missing video or thumbnail MsgInfo');
}
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const md5 = Buffer.from(videoIndex.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
fileUuid: videoIndex.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
@@ -389,16 +423,15 @@ export class PacketHighwayContext {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
if (subFile?.uKey && subFile.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
const md5 = Buffer.from(thumbIndex.info.fileHash, 'hex');
const sha1 = Buffer.from(thumbIndex.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
fileUuid: thumbIndex.fileUuid,
uKey: subFile.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
@@ -414,7 +447,7 @@ export class PacketHighwayContext {
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile?.uKey ?? ''}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
@@ -4,6 +4,8 @@ import {
MessageElement,
Peer,
RawMessage,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -15,7 +17,7 @@ import {
SendReplyElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/index';
} from '@/napcat-core/types/element';
import {
IPacketMsgElement,
PacketMsgAtElement,
@@ -158,7 +160,8 @@ export class PacketMsgConverter {
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
const converters = [PacketMsgTextElement.parseElement,
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement,
PacketMsgVideoElement.parseElement, PacketMsgPicElement.parseElement];
return msg.map((element) => {
for (const converter of converters) {
const result = converter(element);
+56 -6
View File
@@ -20,7 +20,11 @@ import {
FaceType,
MessageElement,
NTMsgAtType,
NTVideoType,
PicType,
Peer,
} from '@/napcat-core/types/msg';
import {
SendArkElement,
SendFaceElement,
SendFileElement,
@@ -32,8 +36,7 @@ import {
SendMultiForwardMsgElement,
SendTextElement,
SendVideoElement,
Peer,
} from '@/napcat-core/index';
} from '@/napcat-core/types/element';
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
@@ -387,8 +390,10 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
if (elem?.commonElem?.serviceType === 48 &&
[10, 20].includes(elem.commonElem.businessType ?? 0) &&
elem.commonElem.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
const msgInfoBody = extra.msgInfoBody[0];
const index = msgInfoBody?.index;
return [{
@@ -406,7 +411,7 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
summary: '[图片]',
thumbPath: new Map(),
},
elementType: ElementType.UNKNOWN,
elementType: ElementType.PIC,
elementId: '',
}, elem];
}
@@ -446,8 +451,13 @@ export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
}
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
fileName: string;
fileSize?: string;
filePath?: string;
fileTime: number;
fileFormat: NTVideoType;
fileWidth?: number;
fileHeight?: number;
thumbSize?: number;
thumbPath?: string;
fileMd5?: string;
@@ -456,12 +466,18 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
thumbSha1?: string;
thumbWidth?: number;
thumbHeight?: number;
businessType: 11 | 21 = 21;
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
constructor (element: SendVideoElement) {
super(element);
this.fileName = element.videoElement.fileName;
this.fileSize = element.videoElement.fileSize;
this.filePath = element.videoElement.filePath;
this.fileTime = Math.max(0, Math.round(element.videoElement.fileTime ?? 0));
this.fileFormat = element.videoElement.fileFormat ?? NTVideoType.VIDEO_FORMAT_MP4;
this.fileWidth = element.videoElement.fileWidth;
this.fileHeight = element.videoElement.fileHeight;
this.thumbSize = element.videoElement.thumbSize;
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
this.fileMd5 = element.videoElement.videoMd5;
@@ -480,11 +496,45 @@ export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: 21,
businessType: this.businessType,
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType !== 48 ||
![11, 21].includes(elem.commonElem.businessType ?? 0) ||
!elem.commonElem.pbElem) {
return undefined;
}
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
const videoIndex = extra.msgInfoBody[0]?.index;
const thumbIndex = extra.msgInfoBody[1]?.index;
if (!videoIndex) return undefined;
return [{
videoElement: {
filePath: '',
fileName: videoIndex.info.fileName || videoIndex.info.fileHash,
videoMd5: videoIndex.info.fileHash,
thumbMd5: thumbIndex?.info.fileHash,
fileTime: videoIndex.info.time,
fileFormat: (videoIndex.info.type.videoFormat || NTVideoType.VIDEO_FORMAT_MP4) as NTVideoType,
fileSize: String(videoIndex.info.fileSize),
fileWidth: videoIndex.info.width,
fileHeight: videoIndex.info.height,
thumbWidth: thumbIndex?.info.width,
thumbHeight: thumbIndex?.info.height,
thumbSize: thumbIndex?.info.fileSize,
thumbPath: new Map(),
fileUuid: videoIndex.fileUuid,
busiType: 0,
subBusiType: 0,
},
elementType: ElementType.VIDEO,
elementId: '',
}, elem];
};
override toPreview (): string {
return '[视频]';
}
@@ -33,16 +33,16 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: 'nya.mp4',
fileName: video.fileName || 'video.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: 0,
videoFormat: video.fileFormat,
voiceFormat: 0,
},
height: 0,
width: 0,
time: 0,
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
original: 0,
},
subFileType: 0,
@@ -51,7 +51,7 @@ class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp>
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: 'nya.jpg',
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
type: {
type: 1,
picFormat: 0,
@@ -34,16 +34,16 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: 'nya.mp4',
fileName: video.fileName || 'video.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: 0,
videoFormat: video.fileFormat,
voiceFormat: 0,
},
height: 0,
width: 0,
time: 0,
height: video.fileHeight ?? 0,
width: video.fileWidth ?? 0,
time: video.fileTime,
original: 0,
},
subFileType: 0,
@@ -52,7 +52,7 @@ class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaRes
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: 'nya.jpg',
fileName: `${video.thumbMd5 || 'video-thumb'}.jpg`,
type: {
type: 1,
picFormat: 0,
@@ -88,6 +88,7 @@ export interface NodeIKernelAlbumService {
map_bytes_info: unknown[],
map_user_account: unknown[];
},
type: number, // type : number 1 取消 2 点赞
param: {
// {"id":"421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3e*KqaLVYdic!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560336594^||^1","status":1}
id: string,
@@ -341,7 +341,7 @@ export interface NodeIKernelMsgService {
getFileThumbSavePath (arg1: string, arg2: number, arg3: boolean): unknown;
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): unknown;
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): Promise<GeneralCallResult>;
setPttPlayedState (arg1: string, arg2: Peer, arg3: string): unknown;
@@ -369,7 +369,16 @@ export interface NodeIKernelMsgService {
}>;
}>;
addFavEmoji (arg: unknown): unknown;
addFavEmoji (arg: {
emojiId?: string,
packageId?: number,
emojiPath: string,
fileSize: string,
fileName: string,
md5: string,
isMarkFace?: boolean,
isOrigin?: boolean,
}): unknown;
fetchMarketEmoticonList (arg1: number, arg2: number): unknown;
@@ -397,9 +406,14 @@ export interface NodeIKernelMsgService {
downloadEmojiPic (arg1: number, arg2: Array<unknown>[], arg3: number, arg4: Map<unknown, unknown>): unknown;
deleteFavEmoji (arg: unknown): unknown;
deleteFavEmoji (arg: string[]): unknown;
modifyFavEmojiDesc (arg: unknown): unknown;
modifyFavEmojiDesc (arg: Array<{
emojiId: number,
resId: string,
md5: string,
desc: string,
}>): unknown;
queryFavEmojiByDesc (arg: unknown): unknown;
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
+2
View File
@@ -118,6 +118,8 @@ export interface VideoElement {
thumbSize?: number; // byte
fileFormat?: NTVideoType; // 2表示mp4 参考下面条目
fileSize?: string; // byte
fileWidth?: number;
fileHeight?: number;
thumbWidth?: number;
thumbHeight?: number;
busiType?: 0; //
+14
View File
@@ -74,6 +74,20 @@ export interface EXTInfo {
groupSquareSwitch: number;
}
export type GroupMemberInvitePolicy =
| 'disabled'
| 'require_approval'
| 'no_approval'
| 'no_approval_under_100';
export interface GroupManagementSettings {
memberInvite?: GroupMemberInvitePolicy;
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
allowMemberCreateGroup?: boolean;
newMembersSeeRecentHistory?: boolean;
}
export interface GroupGuildIDS {
guildIds: any[];
}
+58 -1
View File
@@ -105,6 +105,13 @@ export async function NCoreInitFramework (
loginContext.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
const oneBotContext = WebUiDataRuntime.getOneBotContext();
if (oneBotContext?.core?.selfInfo) {
oneBotContext.core.selfInfo.online = true;
WebUiDataRuntime.setQQLoginPhase('ready');
} else {
WebUiDataRuntime.setQQLoginPhase('initializing');
}
await new Promise<void>(resolve => {
registerInitCallback(() => resolve());
});
@@ -118,6 +125,8 @@ export async function NCoreInitFramework (
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
};
@@ -146,9 +155,14 @@ export async function NCoreInitFramework (
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
WebUiDataRuntime.setQQNewLoginList(list);
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
if (!loginContext.isLogined) {
const requested = loginService.getQRCodePicture();
logger.logWarn('[NapCat] [Framework] 登录服务连接完成,正在获取二维码', { requested, msfStatus: loginService.getMsfStatus() });
}
};
loginListener.onQRCodeSessionUserScaned = () => {
WebUiDataRuntime.setQQLoginPhase('qrcode_scanned');
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
};
@@ -194,7 +208,35 @@ export async function NCoreInitFramework (
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
let restartRequested = false;
loaderObject.core.event.on('KickedOffLine', (tips: string) => {
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
if (restartRequested) return;
restartRequested = true;
setTimeout(() => {
WebUiDataRuntime.requestRestartProcess().then((restartResult) => {
logger.logWarn('[NapCat] [Framework] 账号被踢下线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (!restartResult.result) {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
}
}).catch((error) => {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
});
}, 3_500);
});
}
function registerWebUiLoginCallbacks (
@@ -204,7 +246,22 @@ function registerWebUiLoginCallbacks (
) {
// 刷新二维码
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
loginService.getQRCodePicture();
loginContext.isLogined = false;
const msfStatus = loginService.getMsfStatus();
if (msfStatus === 2) {
WebUiDataRuntime.setQQLoginPhase('reconnecting');
const connected = loginService.connect();
logger.logWarn('[NapCat] [Framework] 登录服务离线,正在重连以获取二维码', { connected, msfStatus });
if (!connected) {
throw new Error('QQ 登录服务无法重新连接');
}
return;
}
const requested = loginService.getQRCodePicture();
logger.logWarn('[NapCat] [Framework] 请求刷新二维码', { requested, msfStatus });
if (!requested) {
throw new Error('QQ 未接受二维码刷新请求');
}
});
// 快速登录
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
@@ -42,4 +42,12 @@ export const ExtendsActionsExamples = {
payload: { group_id: '123456', user_id: '123456789', special_title: '头衔' },
response: null,
},
SendQzoneMsg: {
payload: { content: '今天天气不错', images: [], ugc_right: 1, target_uins: [] },
response: { tid: '1234567890abcdef1234567890' },
},
DeleteQzoneMsg: {
payload: { tid: '1234567890abcdef1234567890' },
response: null,
},
};
@@ -1,4 +1,21 @@
export const GroupActionsExamples = {
SetGroupMemberInvitePolicy: {
payload: { group_id: '123456', policy: 'require_approval' },
response: null,
},
SetGroupMemberPermissions: {
payload: {
group_id: '123456',
allow_member_upload_album: true,
allow_member_temporary_session: true,
allow_member_create_group: true,
},
response: null,
},
SetGroupNewMemberHistoryVisibility: {
payload: { group_id: '123456', visible: true },
response: null,
},
DelEssenceMsg: {
payload: { message_id: 123456 },
response: null,
@@ -0,0 +1,162 @@
import { createHash } from 'node:crypto';
import { stat, readFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { Type, Static } from '@sinclair/typebox';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
const FetchCustomFaceDetailPayloadSchema = Type.Object({
count: Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
});
type FetchCustomFaceDetailPayloadType = Static<typeof FetchCustomFaceDetailPayloadSchema>;
const FetchCustomFaceDetailReturnSchema = Type.Any({ description: '自定义表情详情列表' });
type FetchCustomFaceDetailReturnType = Static<typeof FetchCustomFaceDetailReturnSchema>;
export class FetchCustomFaceDetail extends OneBotAction<FetchCustomFaceDetailPayloadType, FetchCustomFaceDetailReturnType> {
override actionName = ActionName.FetchCustomFaceDetail;
override payloadSchema = FetchCustomFaceDetailPayloadSchema;
override returnSchema = FetchCustomFaceDetailReturnSchema;
override actionSummary = '获取自定义表情详情';
override actionTags = ['系统扩展'];
override payloadExample = {
count: 10,
};
override returnExample = null;
async _handle (payload: FetchCustomFaceDetailPayloadType) {
const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);
return ret.emojiInfoList;
}
}
const AddCustomFacePayloadSchema = Type.Object({
file: Type.String({ description: '本地表情文件路径' }),
emoji_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情ID,未提供时传空字符串' })),
package_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情包ID,未提供时传0' })),
file_name: Type.Optional(Type.String({ description: '文件名,未提供时从file路径取basename' })),
file_size: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '文件大小,未提供时读取本地文件' })),
md5: Type.Optional(Type.String({ description: '文件MD5,未提供时读取本地文件计算' })),
is_mark_face: Type.Optional(Type.Boolean({ description: '是否商城表情' })),
is_origin: Type.Optional(Type.Boolean({ description: '是否原图' })),
});
type AddCustomFacePayloadType = Static<typeof AddCustomFacePayloadSchema>;
const AddCustomFaceReturnSchema = Type.Any({ description: '添加结果' });
type AddCustomFaceReturnType = Static<typeof AddCustomFaceReturnSchema>;
export class AddCustomFace extends OneBotAction<AddCustomFacePayloadType, AddCustomFaceReturnType> {
override actionName = ActionName.AddCustomFace;
override payloadSchema = AddCustomFacePayloadSchema;
override returnSchema = AddCustomFaceReturnSchema;
override actionSummary = '添加自定义表情';
override actionTags = ['系统扩展'];
override payloadExample = {
file: 'C:\\Users\\Public\\face.png',
is_origin: true,
};
override returnExample = null;
async _handle (payload: AddCustomFacePayloadType) {
const fileStat = await stat(payload.file);
const md5 = payload.md5 ?? createHash('md5').update(await readFile(payload.file)).digest('hex');
return await this.core.apis.MsgApi.addFavEmoji({
emojiId: payload.emoji_id?.toString() ?? '',
packageId: payload.package_id === undefined ? 0 : Number(payload.package_id),
emojiPath: payload.file,
fileSize: payload.file_size?.toString() ?? fileStat.size.toString(),
fileName: payload.file_name ?? basename(payload.file),
md5,
isMarkFace: payload.is_mark_face ?? false,
isOrigin: payload.is_origin ?? true,
});
}
}
const DeleteCustomFacePayloadSchema = Type.Object({
res_id: Type.Optional(Type.Union([
Type.String({ description: 'fetch_custom_face_detail返回的resId' }),
Type.Array(Type.String({ description: 'fetch_custom_face_detail返回的resId' })),
])),
id: Type.Optional(Type.Union([
Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' }),
Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' })),
])),
ids: Type.Optional(Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID列表,通常为resId列表' }))),
md5: Type.Optional(Type.Union([
Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' }),
Type.Array(Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' })),
])),
});
type DeleteCustomFacePayloadType = Static<typeof DeleteCustomFacePayloadSchema>;
const DeleteCustomFaceReturnSchema = Type.Any({ description: '删除结果' });
type DeleteCustomFaceReturnType = Static<typeof DeleteCustomFaceReturnSchema>;
export class DeleteCustomFace extends OneBotAction<DeleteCustomFacePayloadType, DeleteCustomFaceReturnType> {
override actionName = ActionName.DeleteCustomFace;
override payloadSchema = DeleteCustomFacePayloadSchema;
override returnSchema = DeleteCustomFaceReturnSchema;
override actionSummary = '删除自定义表情';
override actionTags = ['系统扩展'];
override payloadExample = {
res_id: '2707600964_0_0_0_D8EAA70984B402EE10B0F33DB88F4173_0_0',
};
override returnExample = null;
async _handle (payload: DeleteCustomFacePayloadType) {
const ids = payload.ids ??
(Array.isArray(payload.res_id) ? payload.res_id : payload.res_id ? [payload.res_id] : undefined) ??
(Array.isArray(payload.id) ? payload.id : payload.id ? [payload.id] : undefined) ??
[];
if (ids.length === 0) throw new Error('res_id or ids is required');
return await this.core.apis.MsgApi.deleteFavEmoji(ids);
}
}
const SetCustomFaceDescPayloadSchema = Type.Object({
emoji_id: Type.Union([Type.Number(), Type.String()], { description: '表情ID' }),
res_id: Type.String({ description: '资源ID' }),
md5: Type.String({ description: '表情MD5' }),
desc: Type.String({ description: '新的表情描述' }),
});
type SetCustomFaceDescPayloadType = Static<typeof SetCustomFaceDescPayloadSchema>;
const SetCustomFaceDescReturnSchema = Type.Any({ description: '修改结果' });
type SetCustomFaceDescReturnType = Static<typeof SetCustomFaceDescReturnSchema>;
export class SetCustomFaceDesc extends OneBotAction<SetCustomFaceDescPayloadType, SetCustomFaceDescReturnType> {
override actionName = ActionName.SetCustomFaceDesc;
override payloadSchema = SetCustomFaceDescPayloadSchema;
override returnSchema = SetCustomFaceDescReturnSchema;
override actionSummary = '修改自定义表情描述';
override actionTags = ['系统扩展'];
override payloadExample = {
emoji_id: 1,
res_id: 'resource-id',
md5: 'd41d8cd98f00b204e9800998ecf8427e',
desc: '新的描述',
};
override returnExample = null;
async _handle (payload: SetCustomFaceDescPayloadType) {
return await this.core.apis.MsgApi.modifyFavEmojiDesc([{
emojiId: Number(payload.emoji_id),
resId: payload.res_id,
md5: payload.md5,
desc: payload.desc,
}]);
}
}
@@ -0,0 +1,26 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
tid: Type.String({ description: '说说 tid (来自 get_qzone_msg_list / send_qzone_msg)' }),
});
type PayloadType = Static<typeof PayloadSchema>;
export class DeleteQzoneMsg extends OneBotAction<PayloadType, void> {
override actionName = ActionName.DeleteQzoneMsg;
override actionSummary = '删除QQ空间说说';
override actionDescription = '删除QQ空间(Qzone)的一条说说, 按 tid 删除';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.DeleteQzoneMsg.payload;
override returnExample = ExtendsActionsExamples.DeleteQzoneMsg.response;
override payloadSchema = PayloadSchema;
override returnSchema = Type.Null();
async _handle (payload: PayloadType): Promise<void> {
await this.core.apis.WebApi.deleteQzoneMsg(payload.tid);
}
}
@@ -0,0 +1,51 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()], { description: '群号' }),
need_short_url: Type.Optional(Type.Union([Type.Boolean(), Type.String()], { default: true, description: '是否返回短链 (qm.qq.com/q/xxx),false 返回完整 universal-share 链接' })),
src_id: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 73, description: '分享来源 ID' })),
additional_param: Type.Optional(Type.String({ default: '', description: '附加参数' })),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
url: Type.String({ description: '群分享链接' }),
}, { description: '群分享链接' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupShareLink extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupShareLink;
override actionSummary = '获取群分享链接';
override actionDescription = '通过 NTQQ 原生 getJoinGroupLink 获取群的 H5 分享/加群链接 (qm.qq.com/q/xxx 或 qun.qq.com/universal-share/share?...)';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
need_short_url: true,
};
override returnExample = {
url: 'https://qm.qq.com/q/xxxxxxxxxx',
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const needShortUrl = payload.need_short_url === undefined ? true : payload.need_short_url.toString() === 'true';
const srcId = payload.src_id === undefined ? 73 : Number(payload.src_id);
const ret = await this.core.apis.GroupApi.getJoinGroupLink(
payload.group_id.toString(),
needShortUrl,
srcId,
payload.additional_param ?? ''
);
if (!ret?.url) {
throw new Error(`获取群分享链接失败: ${ret?.errMsg || JSON.stringify(ret)}`);
}
return { url: ret.url };
}
}
@@ -0,0 +1,48 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Array(
Type.Object({
user_id: Type.Number({ description: '打卡者QQ' }),
nick: Type.String({ description: '打卡者昵称' }),
time: Type.Number({ description: '打卡时间' }),
rank: Type.Number({ description: '打卡排名' }),
}),
{ description: '群组今日打卡列表' }
);
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupSignedList extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupSignedList;
override actionSummary = '获取群组今日打卡列表';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
};
override returnExample = {
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const data = await this.core.apis.WebApi.getDaySignedList(payload.group_id.toString());
if (!data.response.page) throw new Error('无法获取该群组打卡列表');
return data.response.page[0]?.infos?.map(info => ({
user_id: +info.uid,
nick: info.uidGroupNick,
time: +info.signedTimeStamp,
rank: (info.signInRank - 1) / 2 + 1,
})) ?? [];
}
}
@@ -0,0 +1,73 @@
import { uriToLocalFile } from 'napcat-common/src/file';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { existsSync, readFileSync } from 'node:fs';
import { unlink } from 'node:fs/promises';
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const ValidUgcRights = [1, 4, 16, 64, 128] as const;
const PayloadSchema = Type.Object({
content: Type.String({ description: '说说正文' }),
images: Type.Optional(Type.Array(Type.String(), { description: '图片数组, 支持 file:// http(s):// base64:// , 自动上传' })),
ugc_right: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '查看权限: 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见' })),
target_uins: Type.Optional(Type.Array(Type.Union([Type.Number(), Type.String()]), { description: 'ugc_right为16/128时, 权限作用的QQ号数组' })),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
tid: Type.String({ description: '说说Tid' }),
}, { description: '发说说结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SendQzoneMsg extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SendQzoneMsg;
override actionSummary = '发表QQ空间说说';
override actionDescription = '在QQ空间(Qzone)发表说说, 支持纯文字或带(多)图, 可设置查看权限';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.SendQzoneMsg.payload;
override returnExample = ExtendsActionsExamples.SendQzoneMsg.response;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<ReturnType> {
const ugcRight = payload.ugc_right !== undefined ? +payload.ugc_right : 1;
if (!ValidUgcRights.includes(ugcRight as typeof ValidUgcRights[number])) {
throw new Error(`ugc_right 参数不合法, 允许的值为: ${ValidUgcRights.join(', ')}`);
}
const targetUins = payload.target_uins?.map((uin) => +uin).filter((uin) => !Number.isNaN(uin));
if ((ugcRight === 16 || ugcRight === 128) && (!targetUins || targetUins.length === 0)) {
throw new Error('ugc_right 为 16 或 128 时, target_uins 不能为空');
}
const richvals: string[] = [];
const cleanupPaths: string[] = [];
try {
for (const image of payload.images ?? []) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, image);
if (!downloadResult.success) {
throw new Error(`图片${image}处理失败, ${downloadResult.errMsg}`);
}
if (!downloadResult.isLocal) {
cleanupPaths.push(downloadResult.path);
}
const base64 = readFileSync(downloadResult.path).toString('base64');
const richval = await this.core.apis.WebApi.uploadImageToQzone(base64);
richvals.push(richval);
}
const result = await this.core.apis.WebApi.publishQzoneMsg(payload.content, richvals, ugcRight, targetUins);
return result;
} finally {
for (const p of cleanupPaths) {
if (existsSync(p)) {
await unlink(p).catch(() => { });
}
}
}
}
}
@@ -5,9 +5,8 @@ import { Static, Type } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
lloc: Type.String({ description: '媒体ID (lloc)' }),
id: Type.String({ description: '点赞ID' }), // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
set: Type.Boolean({ default: true, description: '是否点赞' }), // true=点赞 false=取消点赞 未实现
batch_id: Type.String({ description: 'batch_id' }),
lloc: Type.Optional(Type.String({ description: 'lloc,若对整个上传操作则不填' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -22,9 +21,9 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
lloc: 'media_id_1',
id: '123456',
album_id: 'album_id_123',
batch_id: '112233',
lloc: 'aabbcc12213123',
};
override returnExample = {
@@ -38,8 +37,38 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
payload.group_id,
payload.album_id,
payload.batch_id,
payload.lloc,
payload.id
true // isLike = true
);
}
}
export class CancelGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.CancelGroupAlbumMediaLike; // 注意:需要在 router/index.ts 的 ActionName 枚举中补充该定义
override actionSummary = '取消点赞群相册媒体';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id',
batch_id: '112233',
lloc: 'aabbcc',
};
override returnExample = {
result: {},
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
payload.group_id,
payload.album_id,
payload.batch_id,
payload.lloc,
false
);
}
}
@@ -29,15 +29,22 @@ export class GetGroupFileSystemInfo extends OneBotAction<PayloadType, ReturnType
override returnExample = GoCQHTTPActionsExamples.GetGroupFileSystemInfo.response;
async _handle (payload: PayloadType) {
const groupFileCount = (await this.core.apis.GroupApi.getGroupFileCount([payload.group_id.toString()])).groupFileCounts[0];
if (!groupFileCount) {
const groupCode = payload.group_id.toString();
const [countResult, space] = await Promise.all([
this.core.apis.GroupApi.getGroupFileCount([groupCode]),
this.core.apis.GroupApi.getGroupFileSpace(groupCode),
]);
const groupFileCount = countResult.groupFileCounts[0];
if (groupFileCount === undefined) {
throw new Error('Group not found');
}
return {
file_count: groupFileCount,
limit_count: 10000,
used_space: 0,
total_space: 10 * 1024 * 1024 * 1024,
// Real values from the kernel's groupSpaceResult; fall back to the old
// placeholders if the field is unexpectedly absent.
used_space: space?.usedSpace ?? 0,
total_space: space?.totalSpace ?? 10 * 1024 * 1024 * 1024,
};
}
}
@@ -0,0 +1,13 @@
import type { GeneralCallResult } from 'napcat-core';
export function assertGroupManagementResults (
operation: string,
results: Array<{ setting: string, result: GeneralCallResult; }>
): void {
const failure = results.find(item => item.result.result !== 0);
if (!failure) return;
throw new Error(
`${operation}失败 Setting: ${failure.setting} ErrCode: ${failure.result.result} ` +
`ErrMsg: ${failure.result.errMsg || '未知错误'}`
);
}
@@ -1,6 +1,7 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { sleep } from '@/napcat-common/src/helper';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
@@ -27,8 +28,24 @@ export default class SetGroupCard extends OneBotAction<PayloadType, ReturnType>
override returnExample = GroupActionsExamples.SetGroupCard.response;
async _handle (payload: PayloadType): Promise<null> {
const member = await this.core.apis.GroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString());
if (member) await this.core.apis.GroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || '');
return null;
const groupId = payload.group_id.toString();
const userId = payload.user_id.toString();
const card = payload.card || '';
const member = await this.core.apis.GroupApi.getGroupMember(groupId, userId);
if (!member) {
throw new Error(`群(${groupId})成员${userId}不存在`);
}
await this.core.apis.GroupApi.setMemberCard(groupId, member.uid, card);
for (let i = 0; i < 3; i++) {
await sleep(1000);
const updatedMember = await this.core.apis.GroupApi.refreshGroupMemberCachePartial(groupId, member.uid);
if (updatedMember?.cardName === card) {
return null;
}
}
throw new Error('设置群名片未生效');
}
}
@@ -0,0 +1,41 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { assertGroupManagementResults } from './GroupOperationHelpers';
const MemberInvitePolicySchema = Type.Union([
Type.Literal('disabled'),
Type.Literal('require_approval'),
Type.Literal('no_approval'),
Type.Literal('no_approval_under_100'),
], {
description: '成员邀请策略:禁止、需要管理员审核、无需审核、群成员少于100人时无需审核',
});
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
policy: MemberInvitePolicySchema,
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupMemberInvitePolicy extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupMemberInvitePolicy;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置群成员邀请策略';
override actionDescription = '设置是否允许群成员邀请好友进群,以及邀请是否需要管理员审核';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupMemberInvitePolicy.payload;
override returnExample = GroupActionsExamples.SetGroupMemberInvitePolicy.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const results = await this.core.apis.GroupApi.setGroupMemberInvitePolicy(payload.group_id, payload.policy);
assertGroupManagementResults('设置群成员邀请策略', results);
return null;
}
}
@@ -0,0 +1,43 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { assertGroupManagementResults } from './GroupOperationHelpers';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
allow_member_upload_album: Type.Optional(Type.Boolean({ description: '允许成员上传群相册' })),
allow_member_temporary_session: Type.Optional(Type.Boolean({ description: '允许成员发起临时会话' })),
allow_member_create_group: Type.Optional(Type.Boolean({ description: '允许成员发起新的群聊' })),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupMemberPermissions extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupMemberPermissions;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置群成员功能权限';
override actionDescription = '设置群成员上传相册、发起临时会话和发起新群聊的权限;未传入的项目保持不变';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupMemberPermissions.payload;
override returnExample = GroupActionsExamples.SetGroupMemberPermissions.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const permissions = {
allowMemberUploadAlbum: payload.allow_member_upload_album,
allowMemberTemporarySession: payload.allow_member_temporary_session,
allowMemberCreateGroup: payload.allow_member_create_group,
};
if (Object.values(permissions).every(value => value === undefined)) {
throw new Error('至少需要提供一个群成员功能权限');
}
const results = await this.core.apis.GroupApi.setGroupMemberPermissions(payload.group_id, permissions);
assertGroupManagementResults('设置群成员功能权限', results);
return null;
}
}
@@ -26,7 +26,10 @@ export default class SetGroupName extends OneBotAction<PayloadType, ReturnType>
override returnExample = GroupActionsExamples.SetGroupName.response;
async _handle (payload: PayloadType): Promise<null> {
const ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
let ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
if (ret.result.toString() === '1287') {
ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name, true);
}
if (ret.result !== 0) {
throw new Error(`设置群名称失败 ErrCode: ${ret.result} ErrMsg: ${ret.errMsg}`);
}
@@ -0,0 +1,35 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
import { assertGroupManagementResults } from './GroupOperationHelpers';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
visible: Type.Boolean({ description: '新成员默认可见最近聊天记录' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupNewMemberHistoryVisibility extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupNewMemberHistoryVisibility;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置新成员历史消息可见性';
override actionDescription = '设置新入群成员默认是否可以查看最近聊天记录';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.payload;
override returnExample = GroupActionsExamples.SetGroupNewMemberHistoryVisibility.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const results = await this.core.apis.GroupApi.setGroupNewMemberHistoryVisibility(
payload.group_id,
payload.visible
);
assertGroupManagementResults('设置新成员历史消息可见性', results);
return null;
}
}
+23 -1
View File
@@ -63,6 +63,7 @@ import GetRecentContact from './user/GetRecentContact';
import { GetProfileLike } from './extends/GetProfileLike';
import SetGroupPortrait from './go-cqhttp/SetGroupPortrait';
import { FetchCustomFace } from './extends/FetchCustomFace';
import { AddCustomFace, DeleteCustomFace, FetchCustomFaceDetail, SetCustomFaceDesc } from './extends/CustomFace';
import GoCQHTTPUploadPrivateFile from './go-cqhttp/UploadPrivateFile';
import { FetchEmojiLike } from './extends/FetchEmojiLike';
import { GetEmojiLikes } from './extends/GetEmojiLikes';
@@ -74,6 +75,7 @@ import { SetInputStatus } from './extends/SetInputStatus';
import { GetCSRF } from './system/GetCSRF';
import { DelGroupNotice } from './group/DelGroupNotice';
import { GetGroupInfoEx } from './extends/GetGroupInfoEx';
import { GetGroupShareLink } from './extends/GetGroupShareLink';
import { DeleteGroupFile } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFile';
import { CreateGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/CreateGroupFileFolder';
import { DeleteGroupFileFolder } from '@/napcat-onebot/action/go-cqhttp/DeleteGroupFileFolder';
@@ -134,7 +136,7 @@ import { GetQunAlbumList } from './extends/GetQunAlbumList';
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
import { SetGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
import { SetGroupAlbumMediaLike, CancelGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
import { DelGroupAlbumMedia } from './extends/DelGroupAlbumMedia';
import { CleanStreamTempFile } from './stream/CleanStreamTempFile';
import { DownloadFileStream } from './stream/DownloadFileStream';
@@ -157,6 +159,13 @@ import { CancelOnlineFile } from './file/online/CancelOnlineFile';
import { ReceiveOnlineFile } from './file/online/ReceiveOnlineFile';
import { RefuseOnlineFile } from './file/online/RefuseOnlineFile';
import { GetFilesetId } from './file/flash/GetFilesetIdByCode';
import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText';
import { GetGroupSignedList } from './extends/GetGroupSignedList';
import { SendQzoneMsg } from './extends/SendQzoneMsg';
import { DeleteQzoneMsg } from './extends/DeleteQzoneMsg';
import SetGroupMemberInvitePolicy from './group/SetGroupMemberInvitePolicy';
import SetGroupMemberPermissions from './group/SetGroupMemberPermissions';
import SetGroupNewMemberHistoryVisibility from './group/SetGroupNewMemberHistoryVisibility';
export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
const actionHandlers = [
@@ -168,6 +177,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new UploadFileStream(obContext, core),
new DelGroupAlbumMedia(obContext, core),
new SetGroupAlbumMediaLike(obContext, core),
new CancelGroupAlbumMediaLike(obContext, core),
new DoGroupAlbumComment(obContext, core),
new GetGroupAlbumMediaList(obContext, core),
new GetQunAlbumList(obContext, core),
@@ -187,8 +197,10 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetRkeyServer(obContext, core),
new SetGroupRemark(obContext, core),
new GetGroupInfoEx(obContext, core),
new GetGroupShareLink(obContext, core),
new FetchEmojiLike(obContext, core),
new GetEmojiLikes(obContext, core),
new FetchPttText(obContext, core),
new GetFile(obContext, core),
new SetQQProfile(obContext, core),
new ShareGroupEx(obContext, core),
@@ -210,6 +222,12 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new MoveGroupFile(obContext, core),
new RenameGroupFile(obContext, core),
new TransGroupFile(obContext, core),
new GetGroupSignedList(obContext, core),
new SendQzoneMsg(obContext, core),
new DeleteQzoneMsg(obContext, core),
new SetGroupMemberInvitePolicy(obContext, core),
new SetGroupMemberPermissions(obContext, core),
new SetGroupNewMemberHistoryVisibility(obContext, core),
// onebot11
new SendLike(obContext, core),
new GetMsg(obContext, core),
@@ -274,6 +292,10 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetProfileLike(obContext, core),
new SetGroupPortrait(obContext, core),
new FetchCustomFace(obContext, core),
new FetchCustomFaceDetail(obContext, core),
new AddCustomFace(obContext, core),
new DeleteCustomFace(obContext, core),
new SetCustomFaceDesc(obContext, core),
new GoCQHTTPUploadPrivateFile(obContext, core),
new GetGuildProfile(obContext, core),
new GoCQHTTPGetModelShow(obContext, core),
@@ -0,0 +1,87 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { Static, Type } from '@sinclair/typebox';
import { PromiseTimer } from '@/napcat-common/src/helper';
import { ElementType } from '@/napcat-core';
import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples';
const PayloadSchema = Type.Object({
message_id: Type.Union([Type.Number(), Type.String()], { description: '消息ID' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({ text: Type.String({ description: '得到的文本' }) });
type ReturnType = Static<typeof ReturnSchema>;
export class FetchPttText extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.FetchPttText;
override actionSummary = '获取语音转文字结果';
override actionTags = ['消息扩展'];
override payloadExample = MsgActionsExamples.FetchPttText.payload;
override returnExample = MsgActionsExamples.FetchPttText.response;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
if (!payload.message_id) {
throw Error('参数message_id不能为空');
}
const MsgShortId = MessageUnique.getShortIdByMsgId(payload.message_id.toString());
const msgIdWithPeer = MessageUnique.getMsgIdAndPeerByShortId(MsgShortId ?? +payload.message_id);
if (!msgIdWithPeer) {
throw new Error('消息不存在');
}
const peer = { guildId: '', peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType };
const getMsgTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
const msgRes = await PromiseTimer(
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
getMsgTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
}
throw e;
});
const msg = msgRes.msgList[0];
if (!msg) throw Error('消息不存在或已被撤回');
const pttSegment = msg.elements.find((s) =>
s.elementType === ElementType.PTT
);
if (!pttSegment) {
throw Error('消息中不包含语音');
}
const getPttTextTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
await PromiseTimer(
this.core.context.session.getMsgService().translatePtt2Text(msgIdWithPeer.MsgId, msgIdWithPeer.Peer, pttSegment),
getPttTextTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`获取语音转文字结果失败: ${e.message || String(e)}`);
}
throw e;
});
const msgRes2 = await PromiseTimer(
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
getMsgTimeout
).catch((e: unknown) => {
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
}
throw e;
});
const msg2 = msgRes2.msgList[0];
if (!msg2) throw Error('消息不存在或已被撤回');
for (const s of msg2.elements) {
if (s.elementType === ElementType.PTT) {
if (s.pttElement?.text) {
return { text: s.pttElement?.text };
}
}
}
throw new Error('获取语音转文字结果失败');
}
}
+13 -8
View File
@@ -84,6 +84,13 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
}
const isBuddy = await core.apis.FriendApi.isBuddy(Uid);
if (!isBuddy) {
if (payload.group_id) {
return {
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
peerUid: Uid,
guildId: payload.group_id.toString(),
};
}
const ret = await core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, Uid);
if (ret.tmpChatInfo?.groupCode) {
return {
@@ -92,13 +99,6 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
guildId: '',
};
}
if (payload.group_id) {
return {
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
peerUid: Uid,
guildId: payload.group_id.toString(),
};
}
return {
chatType: ChatType.KCHATTYPEC2C,
peerUid: Uid,
@@ -245,7 +245,12 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
});
}
} else {
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(
OB11Data,
msgPeer,
[],
{ usePacketVideoMetadata: true }
);
sendElements = sendElementsCreateReturn.sendElements;
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
}
@@ -14,6 +14,12 @@ export const MsgActionsExamples = {
message: 'hello',
},
},
FetchPttText: {
payload: { message_id: 123456 },
response: {
text: 'hello',
},
},
MarkMsgAsRead: {
payload: { group_id: '123456' },
response: {},
@@ -16,7 +16,7 @@ export abstract class BaseGroupTodoAction extends GetPacketStatusDepends<GroupTo
override returnSchema = Type.Null();
override actionTags = ['核心接口'];
protected abstract handleGroupTodo(groupId: number, msgSeq: string): Promise<void>;
protected abstract handleGroupTodo (groupId: number, msgSeq: string): Promise<void>;
async _handle (payload: GroupTodoPayload) {
const groupId = +payload.group_id;
@@ -4,6 +4,8 @@ import { Type } from '@sinclair/typebox';
export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT> {
protected override async check (payload: PT): Promise<BaseCheckResult> {
const schemaResult = await super.check(payload);
if (!schemaResult.valid) return schemaResult;
if (!this.core.apis.PacketApi.packetStatus) {
return {
valid: false,
@@ -11,7 +13,22 @@ export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
};
}
return await super.check(payload);
return { valid: true };
}
}
export abstract class PacketSendAvailableDepends<PT, RT> extends OneBotAction<PT, RT> {
protected override async check (payload: PT): Promise<BaseCheckResult> {
const schemaResult = await super.check(payload);
if (!schemaResult.valid) return schemaResult;
if (!this.core.apis.PacketApi.available) {
return {
valid: false,
message: 'packetBackend发包能力不可用,请参照文档 https://napneko.github.io/config/advanced 和启动日志检查packetBackend状态或进行配置!' +
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
};
}
return { valid: true };
}
}
@@ -1,5 +1,5 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { PacketSendAvailableDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
import { PacketActionsExamples } from '../example/PacketActionsExamples';
@@ -11,7 +11,7 @@ export const SendPokePayloadSchema = Type.Object({
});
export type SendPokePayload = Static<typeof SendPokePayloadSchema>;
export class SendPokeBase extends GetPacketStatusDepends<SendPokePayload, void> {
export class SendPokeBase extends PacketSendAvailableDepends<SendPokePayload, void> {
override payloadSchema = SendPokePayloadSchema;
override returnSchema = Type.Null();
override actionSummary = '发送戳一戳';
+16
View File
@@ -24,6 +24,7 @@ export const ActionName = {
DelGroupAlbumMedia: 'del_group_album_media',
SetGroupAlbumMediaLike: 'set_group_album_media_like',
CancelGroupAlbumMediaLike: 'cancel_group_album_media_like',
DoGroupAlbumComment: 'do_group_album_comment',
GetGroupAlbumMediaList: 'get_group_album_media_list',
UploadImageToQunAlbum: 'upload_image_to_qun_album',
@@ -42,6 +43,9 @@ export const ActionName = {
GetRkeyEx: 'get_rkey',
GetRkeyServer: 'get_rkey_server',
SetGroupRemark: 'set_group_remark',
SetGroupMemberInvitePolicy: 'set_group_member_invite_policy',
SetGroupMemberPermissions: 'set_group_member_permissions',
SetGroupNewMemberHistoryVisibility: 'set_group_new_member_history_visibility',
NapCat_GetPrivateFileUrl: 'get_private_file_url',
ClickInlineKeyboardButton: 'click_inline_keyboard_button',
GetUnidirectionalFriendList: 'get_unidirectional_friend_list',
@@ -141,6 +145,7 @@ export const ActionName = {
ForwardFriendSingleMsg: 'forward_friend_single_msg',
ForwardGroupSingleMsg: 'forward_group_single_msg',
TranslateEnWordToZn: 'translate_en2zh',
FetchPttText: 'fetch_ptt_text',
SetMsgEmojiLike: 'set_msg_emoji_like',
GoCQHTTP_SendForwardMsg: 'send_forward_msg',
MarkPrivateMsgAsRead: 'mark_private_msg_as_read',
@@ -153,10 +158,15 @@ export const ActionName = {
_MarkAllMsgAsRead: '_mark_all_as_read',
GetProfileLike: 'get_profile_like',
FetchCustomFace: 'fetch_custom_face',
FetchCustomFaceDetail: 'fetch_custom_face_detail',
AddCustomFace: 'add_custom_face',
DeleteCustomFace: 'delete_custom_face',
SetCustomFaceDesc: 'set_custom_face_desc',
FetchEmojiLike: 'fetch_emoji_like',
GetEmojiLikes: 'get_emoji_likes',
SetInputStatus: 'set_input_status',
GetGroupInfoEx: 'get_group_info_ex',
GetGroupShareLink: 'get_group_share_link',
GetGroupDetailInfo: 'get_group_detail_info',
GetGroupIgnoreAddRequest: 'get_group_ignore_add_request',
DelGroupNotice: '_del_group_notice',
@@ -206,4 +216,10 @@ export const ActionName = {
ReceiveOnlineFile: 'receive_online_file',
RefuseOnlineFile: 'refuse_online_file',
CancelOnlineFile: 'cancel_online_file',
GetGroupSignedList: 'get_group_signed_list',
// QQ 空间扩展
SendQzoneMsg: 'send_qzone_msg',
DeleteQzoneMsg: 'delete_qzone_msg',
} as const;
+36 -5
View File
@@ -2,7 +2,7 @@ import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
import { encodeSilk } from '@/napcat-core/helper/audio';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { calculateFileMD5 } from 'napcat-common/src/file';
import { ElementType, NapCatCore, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
import { ElementType, NapCatCore, NTVideoType, PicElement, PicSubType, SendFileElement, SendPicElement, SendPttElement, SendVideoElement } from 'napcat-core';
import { getFileTypeForSendType } from 'napcat-core/helper/msg';
import { imageSizeFallBack } from 'napcat-image-size';
import { SendMessageContext } from './msg';
@@ -12,6 +12,21 @@ import fsPromises from 'fs/promises';
import fs from 'fs';
import { randomUUID } from 'crypto';
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
const videoFormatByExtension: Partial<Record<string, NTVideoType>> = {
afs: NTVideoType.VIDEO_FORMAT_AFS,
avi: NTVideoType.VIDEO_FORMAT_AVI,
mkv: NTVideoType.VIDEO_FORMAT_MKV,
mod: NTVideoType.VIDEO_FORMAT_MOD,
mov: NTVideoType.VIDEO_FORMAT_MOV,
mp4: NTVideoType.VIDEO_FORMAT_MP4,
mts: NTVideoType.VIDEO_FORMAT_MTS,
rm: NTVideoType.VIDEO_FORMAT_RM,
rmvb: NTVideoType.VIDEO_FORMAT_RMVB,
ts: NTVideoType.VIDEO_FORMAT_TS,
wmv: NTVideoType.VIDEO_FORMAT_WMV,
};
export class OneBotFileApi {
obContext: NapCatOneBot11Adapter;
core: NapCatCore;
@@ -114,9 +129,16 @@ export class OneBotFileApi {
}
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
const usePacketVideoMetadata = context.usePacketVideoMetadata === true;
const thumbExtension = usePacketVideoMetadata ? 'jpg' : 'png';
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.${thumbExtension}`);
try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (usePacketVideoMetadata) {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
} else {
videoInfo = await FFmpegService.getVideoInfo(filePath, '');
await FFmpegService.extractLegacyVideoThumbnail(filePath, thumbPath);
}
if (!fs.existsSync(thumbPath)) {
this.core.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
@@ -135,9 +157,18 @@ export class OneBotFileApi {
context.deleteAfterSentFiles.push(thumbPath);
const thumbSize = (await fsPromises.stat(thumbPath)).size;
const thumbMd5 = await calculateFileMD5(thumbPath);
context.deleteAfterSentFiles.push(thumbPath);
const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? (fileName || _fileName) : `${fileName || _fileName}.${fileExt}`;
const videoMetadata = usePacketVideoMetadata
? {
fileTime: Math.max(0, Math.round(videoInfo.time)),
fileFormat: videoFormatByExtension[fileExt.toLowerCase()] ?? NTVideoType.VIDEO_FORMAT_MP4,
fileWidth: videoInfo.width,
fileHeight: videoInfo.height,
}
: {
fileTime: videoInfo.time,
};
return {
elementType: ElementType.VIDEO,
elementId: '',
@@ -146,7 +177,7 @@ export class OneBotFileApi {
filePath: path,
videoMd5: md5,
thumbMd5,
fileTime: videoInfo.time,
...videoMetadata,
thumbPath: new Map([[0, thumbPath]]),
thumbSize,
thumbWidth: videoInfo.width,
+33 -14
View File
@@ -74,6 +74,7 @@ type Ob11ToRawConverters = {
export type SendMessageContext = {
deleteAfterSentFiles: string[],
peer: Peer;
usePacketVideoMetadata?: boolean;
};
export type RecvMessageContext = {
@@ -278,7 +279,7 @@ export class OneBotMsgApi {
};
},
replyElement: async (element, msg, _, quick_reply) => {
replyElement: async (element, msg, _, { quick_reply }) => {
const peer = {
chatType: msg.chatType,
peerUid: msg.peerUid,
@@ -310,9 +311,9 @@ export class OneBotMsgApi {
peer, msgSeq, msgTime, [senderUid]
)).msgList;
const replyMsg = msgRandom
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
const replyMsg = replyMsgList.find(msg =>
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
);
if (replyMsg) return replyMsg;
if (quick_reply) {
@@ -327,9 +328,9 @@ export class OneBotMsgApi {
peer, msgSeq, 1, true, true
)).msgList;
const replyMsg = msgRandom
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
const replyMsg = replyMsgList.find(msg =>
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
);
if (replyMsg) return replyMsg;
@@ -341,9 +342,9 @@ export class OneBotMsgApi {
peer, msgSeq, [senderUid]
)).msgList;
const replyMsg = msgRandom
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
const replyMsg = replyMsgList.find(msg =>
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
);
if (replyMsg) return replyMsg;
@@ -859,12 +860,23 @@ export class OneBotMsgApi {
// 获取签名服务地址
let signUrl = this.obContext.configLoader.configData.musicSignUrl;
if (!signUrl) {
signUrl = 'https://ss.xingzhige.com/music_card/card';// 感谢思思!已获思思许可 其余地方使用请自行询问
signUrl = 'http://106.55.0.102:10087/'; // 首选,yibai音卡签名,已更换稳定签名服务器
}
// 请求签名服务
try {
const musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
let musicJson: string;
try {
musicJson = await RequestUtil.HttpGetJson<string>(signUrl, 'POST', postData);
} catch {
// 首选失败,降级到备选
this.core.context.logger.logError('[音乐卡片签名] 首选地址失败,尝试备选地址...');
musicJson = await RequestUtil.HttpGetJson<string>(
'https://ss.xingzhige.com/music_card/card', // 思思的音卡签名
'POST',
postData
);
}
return this.ob11ToRawConverters.json({
data: { data: musicJson },
type: OB11MessageDataType.json,
@@ -1219,7 +1231,10 @@ export class OneBotMsgApi {
async createSendElements (
messageData: OB11MessageData[],
peer: Peer,
ignoreTypes: OB11MessageDataType[] = []
ignoreTypes: OB11MessageDataType[] = [],
options: {
usePacketVideoMetadata?: boolean;
} = {}
) {
const deleteAfterSentFiles: string[] = [];
const callResultList: Array<Promise<SendMessageElement | undefined>> = [];
@@ -1236,7 +1251,11 @@ export class OneBotMsgApi {
}
const callResult = converter(
sendMsg,
{ peer, deleteAfterSentFiles }
{
peer,
deleteAfterSentFiles,
usePacketVideoMetadata: options.usePacketVideoMetadata,
}
)?.catch(undefined);
callResultList.push(callResult);
}
+1
View File
@@ -59,6 +59,7 @@ const WebsocketClientConfigSchema = Type.Object({
token: Type.String({ default: '' }),
debug: Type.Boolean({ default: false }),
heartInterval: Type.Number({ default: 30000 }),
verifyCertificate: Type.Optional(Type.Boolean({ default: true })),
});
const PluginConfigSchema = Type.Object({
+6 -1
View File
@@ -73,7 +73,12 @@ export function encodeCQCode (data: OB11MessageData) {
continue;
}
try {
const text = value?.toString();
let text: string | undefined;
if (typeof value === 'object' && value?.toString === Object.prototype.toString) {
text = JSON.stringify(value);
} else {
text = value?.toString();
}
if (text) {
result += `,${name}=${CQCodeEscape(text)}`;
}
+107 -27
View File
@@ -65,6 +65,10 @@ interface ApiListType {
QuickActionApi: OneBotQuickActionApi;
FileApi: OneBotFileApi;
}
const RECALL_EVENT_DEDUP_MAX_SIZE = 1_000;
const RECALL_UPDATE_CLOCK_SKEW_SECONDS = 30;
// OneBot实现类
export class NapCatOneBot11Adapter {
readonly core: NapCatCore;
@@ -76,6 +80,8 @@ export class NapCatOneBot11Adapter {
actions: ActionMap;
private readonly bootTime = Date.now() / 1000;
recallEventCache = new Map<string, NodeJS.Timeout>();
private readonly reportedRecallEventCache = new Map<string, true>();
private readonly processingRecallEvents = new Map<string, Promise<void>>();
constructor (core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
this.core = core;
this.context = context;
@@ -157,10 +163,6 @@ export class NapCatOneBot11Adapter {
// 创建NetWork服务
// 注册Plugin 如果需要基于NapCat进行快速开发
// this.networkManager.registerAdapter(
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
// );
// 检查插件目录是否存在,不存在则不加载插件管理器
if (existsSync(this.context.pathWrapper.pluginPath)) {
this.context.logger.log('[Plugins] 插件目录存在,开始加载插件');
@@ -388,36 +390,34 @@ export class NapCatOneBot11Adapter {
this.context.logger.logError('处理发送消息失败', error);
}
};
msgListener.onMsgInfoListUpdate = async (msgList: RawMessage[]) => {
for (const msg of msgList) {
const element = this.getRecallElement(msg);
if (element && this.isCurrentRecallUpdate(msg)) {
// The gray-tip update is authoritative; the recall callback's sequence query can return a newer message.
await this.handleRecallMessage(msg, element);
}
}
};
msgListener.onMsgRecall = async (chatType: ChatType, uid: string, msgSeq: string) => {
const peer: Peer = {
chatType,
peerUid: uid,
guildId: '',
};
let msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find(e => e.msgType === NTMsgType.KMSGTYPEGRAYTIPS);
const element = msg?.elements.find(e => !!e.grayTipElement?.revokeElement);
if (msg && element?.grayTipElement?.revokeElement.isSelfOperate) {
const isSelfDevice = this.recallEventCache.has(msg.msgId);
if (isSelfDevice) {
await this.core.eventWrapper.registerListen('NodeIKernelMsgListener/onMsgRecall',
(chatType: ChatType, uid: string, msgSeq: string) => {
return chatType === msg?.chatType && uid === msg?.peerUid && msgSeq === msg?.msgSeq;
}
).catch(() => {
msg = undefined;
this.context.logger.logDebug('自操作消息撤回事件');
});
}
}
if (msg && element) {
const recallEvent = await this.emitRecallMsg(msg, element);
try {
if (recallEvent) {
await this.networkManager.emitEvent(recallEvent);
}
} catch (e) {
this.context.logger.logError('处理消息撤回失败', e);
try {
const msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList
.find(message => this.getRecallElement(message));
const element = msg && this.getRecallElement(msg);
if (msg && element) {
await this.handleRecallMessage(msg, element);
} else {
this.context.logger.logDebug(`撤回回调暂未查询到灰条消息,等待消息更新: ${chatType}/${uid}/${msgSeq}`);
}
} catch (e) {
this.context.logger.logError('查询撤回消息失败', e);
}
};
msgListener.onKickedOffLine = async (kick) => {
@@ -666,6 +666,86 @@ export class NapCatOneBot11Adapter {
}
}
private getRecallElement (message: RawMessage): MessageElement | undefined {
if (message.msgType !== NTMsgType.KMSGTYPEGRAYTIPS) {
return undefined;
}
return message.elements.find(element => !!element.grayTipElement?.revokeElement);
}
private isCurrentRecallUpdate (message: RawMessage): boolean {
const recallTime = Number(message.recallTime);
if (!Number.isFinite(recallTime) || recallTime <= 0) {
return false;
}
const recallTimeInSeconds = recallTime > 10_000_000_000 ? recallTime / 1000 : recallTime;
return recallTimeInSeconds >= this.bootTime - RECALL_UPDATE_CLOCK_SKEW_SECONDS;
}
private getRecallEventKey (message: RawMessage): string {
return `${message.chatType}/${message.peerUid}/${message.msgId}`;
}
private hasReportedRecallEvent (key: string): boolean {
return this.reportedRecallEventCache.has(key);
}
private markRecallEventReported (key: string): void {
this.reportedRecallEventCache.delete(key);
this.reportedRecallEventCache.set(key, true);
while (this.reportedRecallEventCache.size > RECALL_EVENT_DEDUP_MAX_SIZE) {
const oldestKey = this.reportedRecallEventCache.keys().next().value;
if (oldestKey === undefined) break;
this.reportedRecallEventCache.delete(oldestKey);
}
}
private async handleRecallMessage (message: RawMessage, element: MessageElement): Promise<void> {
const revokeElement = element.grayTipElement?.revokeElement;
if (!revokeElement) return;
if (revokeElement.isSelfOperate) {
const selfRecallTimeout = this.recallEventCache.get(message.msgId);
if (selfRecallTimeout) {
clearTimeout(selfRecallTimeout);
this.recallEventCache.delete(message.msgId);
this.context.logger.logDebug('自操作消息撤回事件');
}
}
const key = this.getRecallEventKey(message);
while (!this.hasReportedRecallEvent(key)) {
const processing = this.processingRecallEvents.get(key);
if (processing) {
// A duplicate callback becomes the retry path if the in-flight report fails.
await processing;
continue;
}
const task = (async () => {
try {
const recallEvent = await this.emitRecallMsg(message, element);
if (recallEvent) {
await this.networkManager.emitEvent(recallEvent);
this.markRecallEventReported(key);
}
} catch (e) {
this.context.logger.logError('处理消息撤回失败', e);
}
})();
this.processingRecallEvents.set(key, task);
try {
await task;
} finally {
if (this.processingRecallEvents.get(key) === task) {
this.processingRecallEvents.delete(key);
}
}
return;
}
}
private async emitRecallMsg (message: RawMessage, element: MessageElement) {
const peer: Peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: '' };
const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
@@ -250,7 +250,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
async httpApiRequest (req: Request, res: Response, request_sse: boolean = false) {
let payload = req.body;
if (req.method === 'get') {
if (req.method === 'GET') {
payload = req.query;
} else if (req.query) {
payload = { ...req.body, ...req.query };
@@ -307,6 +307,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
async reload (newConfig: HttpServerConfig) {
const wasEnabled = this.isEnable;
const oldPort = this.config.port;
const oldHost = this.config.host;
const oldEnableWebsocket = this.config.enableWebsocket;
this.config = newConfig;
@@ -318,7 +319,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
return OB11NetworkReloadType.NetWorkClose;
}
if (oldPort !== newConfig.port || oldEnableWebsocket !== newConfig.enableWebsocket) {
if (oldPort !== newConfig.port || oldHost !== newConfig.host || oldEnableWebsocket !== newConfig.enableWebsocket) {
this.close();
if (newConfig.enable) {
this.open();
@@ -1,378 +0,0 @@
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 { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
import fs from 'fs';
import path from 'path';
export interface PluginPackageJson {
name?: string;
plugin?: string;
version?: string;
main?: string;
}
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
plugin_init: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
plugin_onmessage?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: OB11Message, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
plugin_onevent?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: T, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
plugin_cleanup?: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
}
export interface LoadedPlugin {
name: string;
version?: string;
pluginPath: string;
entryPath: string;
packageJson?: PluginPackageJson;
module: PluginModule;
}
export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
private readonly pluginPath: 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
) {
const config = {
name,
messagePostFormat: 'array',
reportSelfMessage: true,
enable: true,
debug: true,
};
super(name, config, core, obContext, actions);
this.pluginPath = this.core.context.pathWrapper.pluginPath;
}
/**
* 扫描并加载插件
*/
private async loadPlugins (): Promise<void> {
try {
// 确保插件目录存在
if (!fs.existsSync(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 });
// 扫描文件和目录
for (const item of items) {
if (item.isFile()) {
// 处理单文件插件
await this.loadFilePlugin(item.name);
} else if (item.isDirectory()) {
// 处理目录插件
await this.loadDirectoryPlugin(item.name);
}
}
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> {
// 只处理支持的文件类型
if (!this.isSupportedFile(filename)) {
return;
}
const filePath = path.join(this.pluginPath, filename);
const pluginName = path.parse(filename).name;
try {
const module = await this.importModule(filePath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
return;
}
const plugin: LoadedPlugin = {
name: pluginName,
pluginPath: this.pluginPath,
entryPath: filePath,
module,
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
}
}
/**
* 加载目录插件
*/
private async loadDirectoryPlugin (dirname: string): Promise<void> {
const pluginDir = path.join(this.pluginPath, dirname);
try {
// 尝试读取 package.json
let packageJson: PluginPackageJson | undefined;
const packageJsonPath = path.join(pluginDir, 'package.json');
if (fs.existsSync(packageJsonPath)) {
try {
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
packageJson = JSON.parse(packageContent);
} catch (error) {
this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
}
}
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
if (!entryFile) {
this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
return;
}
const entryPath = path.join(pluginDir, entryFile);
const module = await this.importModule(entryPath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
return;
}
const plugin: LoadedPlugin = {
name: packageJson?.name || dirname,
version: packageJson?.version,
pluginPath: pluginDir,
entryPath,
packageJson,
module,
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
}
}
/**
* 查找插件目录的入口文件
*/
private findEntryFile (pluginDir: string, packageJson?: PluginPackageJson): string | null {
// 优先级:package.json main > 默认文件名
const possibleEntries = [
packageJson?.main,
'index.mjs',
'index.js',
'main.mjs',
'main.js',
].filter(Boolean) as string[];
for (const entry of possibleEntries) {
const entryPath = path.join(pluginDir, entry);
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
return entry;
}
}
return null;
}
/**
* 检查是否为支持的文件类型
*/
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);
}
/**
* 检查模块是否为有效的插件模块
*/
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...`);
return;
}
this.loadedPlugins.set(plugin.name, plugin);
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);
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
} catch (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) {
return;
}
// 调用插件清理方法
if (typeof plugin.module.plugin_cleanup === 'function') {
try {
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.loadedPlugins.delete(pluginName);
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
}
async onEvent<T extends OB11EmitEventContent> (event: T) {
if (!this.isEnable) {
return;
}
// 遍历所有已加载的插件,调用它们的事件处理方法
for (const [, plugin] of this.loadedPlugins) {
this.callPluginEventHandler(plugin, event);
}
}
/**
* 调用插件的事件处理方法
*/
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);
}
// 如果是消息事件并且插件有 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);
}
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
}
}
async open () {
if (this.isEnable) {
return;
}
this.logger.log('[Plugin Adapter] Opening plugin adapter...');
this.isEnable = true;
// 加载所有插件
await this.loadPlugins();
this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
}
async close () {
if (!this.isEnable) {
return;
}
this.logger.log('[Plugin Adapter] Closing plugin adapter...');
this.isEnable = false;
// 卸载所有插件
const pluginNames = Array.from(this.loadedPlugins.keys());
for (const pluginName of pluginNames) {
await this.unloadPlugin(pluginName);
}
this.logger.log('[Plugin Adapter] Plugin adapter closed');
}
async reload () {
this.logger.log('[Plugin Adapter] Reloading plugin adapter...');
// 先关闭然后重新打开
await this.close();
await this.open();
this.logger.log('[Plugin Adapter] Plugin adapter reloaded');
return OB11NetworkReloadType.Normal;
}
/**
* 获取已加载的插件列表
*/
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) {
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
return false;
}
try {
// 卸载插件
await this.unloadPlugin(pluginName);
// 重新加载插件
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
plugin.pluginPath !== this.pluginPath;
if (isDirectory) {
const dirname = path.basename(plugin.pluginPath);
await this.loadDirectoryPlugin(dirname);
} else {
const filename = path.basename(plugin.entryPath);
await this.loadFilePlugin(filename);
}
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
return true;
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
return false;
}
}
}
+109 -1
View File
@@ -10,6 +10,31 @@ import {
} from './types';
const require = createRequire(import.meta.url);
/** 允许加载的官方插件 ID 白名单。不在表内的插件一律拒绝加载。 */
const OFFICIAL_PLUGIN_IDS = new Set<string>([
'napcat-plugin-builtin',
'napcat-plugin-cleaner',
'napcat-plugin-ssqq',
'napcat-plugin-qce',
]);
/**
* 敏感词表:插件源码命中(黑灰产 / 支付发卡相关)即拒绝加载。
* 仅作启发式威慑,混淆/编码可绕过,并非唯一防线。
*/
const SENSITIVE_KEYWORDS: string[] = [
'发卡', '卡密', '卡网', '自动发卡', '寄售', '代刷', '刷单', '跑分',
'四件套', '洗钱', '黑产', '灰产', '博彩', '赌博', '菠菜', '涉黄',
'色情', '收款码', '代付', '担保交易', '第三方支付', 'USDT',
];
/** 纳入敏感词检测的源码扩展名 */
const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts']);
/** 跳过敏感词扫描的目录名 */
const SCAN_SKIP_DIRS = new Set(['data', 'node_modules', '.git']);
/** 单文件扫描大小上限,避免超大文件拖慢启动 */
const SCAN_MAX_FILE_BYTES = 5 * 1024 * 1024;
/**
* 插件加载器
* 负责扫描、加载和导入插件模块
@@ -121,6 +146,15 @@ export class PluginLoader {
// 获取插件 ID(包名或目录名)
const pluginId = packageJson?.name || dirname;
// 官方白名单 + 敏感词校验:被拒绝的插件视为不可见,
// 不入列表、不加载、更不会被动态导入执行。
// 该检查置于此处统一拦截 scanPlugins 与 rescanPlugin(安装/重载)两条路径。
const rejectReason = this.getRejectReason(pluginId, pluginDir);
if (rejectReason) {
this.logger.logWarn(`[PluginLoader] Rejected ${pluginId} (${dirname}): ${rejectReason}`);
return null;
}
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
const entryPath = entryFile ? path.join(pluginDir, entryFile) : undefined;
@@ -184,7 +218,12 @@ export class PluginLoader {
].filter(Boolean) as string[];
for (const entry of possibleEntries) {
const entryPath = path.join(pluginDir, entry);
const root = path.resolve(pluginDir);
const entryPath = path.resolve(pluginDir, entry);
// 拒绝 package.json main 指向插件目录之外(防路径穿越)
if (entryPath !== root && !entryPath.startsWith(root + path.sep)) {
continue;
}
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
return entry;
}
@@ -193,6 +232,75 @@ export class PluginLoader {
return null;
}
/** 是否为白名单内的官方插件 */
isOfficialPlugin (pluginId: string): boolean {
return OFFICIAL_PLUGIN_IDS.has(pluginId);
}
/**
* 判断插件是否应被拒绝(非官方 / 命中敏感词)。
* @returns 拒绝原因;通过校验返回 null
*/
private getRejectReason (pluginId: string, pluginDir: string): string | null {
const hit = this.scanSensitiveWords(pluginDir);
if (this.isOfficialPlugin(pluginId)) {
return null;
}
if (hit) {
return `sensitive keyword "${hit}"`;
}
return 'not in official plugin whitelist';
}
/**
* 递归扫描插件目录内源码是否命中敏感词(黑灰产 / 支付发卡)。
* @returns 命中的敏感词;未命中返回 null
*/
scanSensitiveWords (pluginDir: string): string | null {
const visit = (dir: string): string | null => {
let items: fs.Dirent[];
try {
items = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return null;
}
for (const item of items) {
if (item.isDirectory()) {
if (SCAN_SKIP_DIRS.has(item.name)) {
continue;
}
const hit = visit(path.join(dir, item.name));
if (hit) {
return hit;
}
continue;
}
if (!item.isFile()) {
continue;
}
if (!SCAN_EXTS.has(path.extname(item.name).toLowerCase())) {
continue;
}
const filePath = path.join(dir, item.name);
try {
if (fs.statSync(filePath).size > SCAN_MAX_FILE_BYTES) {
continue;
}
const content = fs.readFileSync(filePath, 'utf-8');
for (const word of SENSITIVE_KEYWORDS) {
if (content.includes(word)) {
return word;
}
}
} catch {
// 读取失败忽略该文件
}
}
return null;
};
return visit(pluginDir);
}
/**
* 动态导入模块
*/
@@ -1,529 +0,0 @@
import fs from 'fs';
import path from 'path';
import { ActionMap } from '@/napcat-onebot/action';
import { NapCatCore } from 'napcat-core';
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
import { OB11EmitEventContent, OB11NetworkReloadType } from '@/napcat-onebot/network/index';
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
import { PluginConfig } from '@/napcat-onebot/config/config';
import { NapCatConfig } from './config';
import { PluginLoader } from './loader';
import { PluginRouterRegistryImpl } from './router-registry';
import {
PluginEntry,
PluginLogger,
PluginStatusConfig,
NapCatPluginContext,
IPluginManager,
} from './types';
export class OB11PluginManager extends IOB11NetworkAdapter<PluginConfig> implements IPluginManager {
private readonly pluginPath: string;
private readonly configPath: string;
private readonly loader: PluginLoader;
/** 插件注册表: ID -> 插件条目 */
private plugins: Map<string, PluginEntry> = new Map();
/** 插件路由注册表: pluginId -> PluginRouterRegistry */
private pluginRouters: Map<string, PluginRouterRegistryImpl> = new Map();
declare config: PluginConfig;
public NapCatConfig = NapCatConfig;
override get isActive (): boolean {
return this.isEnable && this.getLoadedPlugins().length > 0;
}
constructor (
name: string,
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap
) {
const config = {
name,
messagePostFormat: 'array',
reportSelfMessage: true,
enable: true,
debug: true,
};
super(name, config, core, obContext, actions);
this.pluginPath = this.core.context.pathWrapper.pluginPath;
this.configPath = path.join(this.core.context.pathWrapper.configPath, 'plugins.json');
this.loader = new PluginLoader(this.pluginPath, this.configPath, this.logger);
}
// ==================== 插件状态配置 ====================
public getPluginConfig (): PluginStatusConfig {
return this.loader.loadPluginStatusConfig();
}
private savePluginConfig (config: PluginStatusConfig): void {
this.loader.savePluginStatusConfig(config);
}
// ==================== 插件扫描与加载 ====================
/**
* 扫描并加载所有插件
*/
private async scanAndLoadPlugins (): Promise<void> {
// 扫描所有插件目录
const entries = await this.loader.scanPlugins();
// 清空现有注册表
this.plugins.clear();
// 注册所有插件条目
for (const entry of entries) {
this.plugins.set(entry.id, entry);
}
this.logger.log(`[PluginManager] Scanned ${this.plugins.size} plugins`);
// 加载启用的插件
for (const entry of this.plugins.values()) {
if (entry.enable && entry.runtime.status !== 'error') {
await this.loadPlugin(entry);
}
}
const loadedCount = this.getLoadedPlugins().length;
this.logger.log(`[PluginManager] Loaded ${loadedCount} plugins`);
}
/**
* 加载单个插件
*/
private async loadPlugin (entry: PluginEntry): Promise<boolean> {
if (entry.loaded) {
return true;
}
if (entry.runtime.status === 'error') {
return false;
}
// 加载模块
const module = await this.loader.loadPluginModule(entry);
if (!module) {
return false;
}
// 创建上下文
const context = this.createPluginContext(entry);
// 初始化插件
try {
await module.plugin_init(context);
entry.loaded = true;
entry.runtime = {
status: 'loaded',
module,
context,
};
this.logger.log(`[PluginManager] Initialized plugin: ${entry.id}${entry.version ? ` v${entry.version}` : ''}`);
return true;
} catch (error: any) {
entry.loaded = false;
entry.runtime = {
status: 'error',
error: error.message || 'Initialization failed',
};
this.logger.logError(`[PluginManager] Error initializing plugin ${entry.id}:`, error);
return false;
}
}
/**
* 卸载单个插件
*/
private async unloadPlugin (entry: PluginEntry): Promise<void> {
if (!entry.loaded || entry.runtime.status !== 'loaded') {
return;
}
const { module, context } = entry.runtime;
// 调用清理方法
if (module && context && typeof module.plugin_cleanup === 'function') {
try {
await module.plugin_cleanup(context);
this.logger.log(`[PluginManager] Cleaned up plugin: ${entry.id}`);
} catch (error) {
this.logger.logError(`[PluginManager] Error cleaning up plugin ${entry.id}:`, error);
}
}
// 重置状态
entry.loaded = false;
entry.runtime = {
status: 'unloaded',
};
this.logger.log(`[PluginManager] Unloaded plugin: ${entry.id}`);
}
/**
* 创建插件上下文
*/
private createPluginContext (entry: PluginEntry): NapCatPluginContext {
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', entry.id);
const configPath = path.join(dataPath, 'config.json');
// 确保插件配置目录存在
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(dataPath, { recursive: true });
}
// 创建插件专用日志器
const pluginPrefix = `[Plugin: ${entry.id}]`;
const coreLogger = this.logger;
const pluginLogger: PluginLogger = {
log: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
debug: (...args: any[]) => coreLogger.logDebug(pluginPrefix, ...args),
info: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
warn: (...args: any[]) => coreLogger.logWarn(pluginPrefix, ...args),
error: (...args: any[]) => coreLogger.logError(pluginPrefix, ...args),
};
// 创建或获取插件路由注册器
let router = this.pluginRouters.get(entry.id);
if (!router) {
router = new PluginRouterRegistryImpl(entry.id, entry.pluginPath);
this.pluginRouters.set(entry.id, router);
}
// 创建获取其他插件导出的方法
const getPluginExports = <T = any> (pluginId: string): T | undefined => {
const targetEntry = this.plugins.get(pluginId);
if (!targetEntry || !targetEntry.loaded || targetEntry.runtime.status !== 'loaded') {
return undefined;
}
return targetEntry.runtime.module as T;
};
return {
core: this.core,
oneBot: this.obContext,
actions: this.actions,
pluginName: entry.id,
pluginPath: entry.pluginPath,
dataPath,
configPath,
NapCatConfig,
adapterName: this.name,
pluginManager: this,
logger: pluginLogger,
router,
getPluginExports,
};
}
// ==================== 公共 API ====================
/**
* 获取插件目录路径
*/
public getPluginPath (): string {
return this.pluginPath;
}
/**
* 获取所有插件条目
*/
public getAllPlugins (): PluginEntry[] {
return Array.from(this.plugins.values());
}
/**
* 获取已加载的插件列表
*/
public getLoadedPlugins (): PluginEntry[] {
return Array.from(this.plugins.values()).filter(p => p.loaded);
}
/**
* 通过 ID 获取插件信息
*/
public getPluginInfo (pluginId: string): PluginEntry | undefined {
return this.plugins.get(pluginId);
}
/**
* 设置插件状态(启用/禁用)
*/
public async setPluginStatus (pluginId: string, enable: boolean): Promise<void> {
const config = this.getPluginConfig();
config[pluginId] = enable;
this.savePluginConfig(config);
const entry = this.plugins.get(pluginId);
if (entry) {
entry.enable = enable;
if (enable && !entry.loaded) {
// 启用插件
await this.loadPlugin(entry);
} else if (!enable && entry.loaded) {
// 禁用插件
await this.unloadPlugin(entry);
}
}
}
/**
* 通过 ID 加载插件
*/
public async loadPluginById (pluginId: string): Promise<boolean> {
let entry = this.plugins.get(pluginId);
if (!entry) {
// 尝试查找并扫描
const dirname = this.loader.findPluginDirById(pluginId);
if (!dirname) {
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found in filesystem`);
return false;
}
const newEntry = this.loader.rescanPlugin(dirname);
if (!newEntry) {
return false;
}
this.plugins.set(newEntry.id, newEntry);
entry = newEntry;
}
if (!entry.enable) {
this.logger.log(`[PluginManager] Skipping loading disabled plugin: ${pluginId}`);
return false;
}
return await this.loadPlugin(entry);
}
/**
* 卸载插件(仅从内存卸载)
*/
public async unregisterPlugin (pluginId: string): Promise<void> {
const entry = this.plugins.get(pluginId);
if (entry) {
await this.unloadPlugin(entry);
}
}
/**
* 卸载并删除插件
*/
public async uninstallPlugin (pluginId: string, cleanData: boolean = false): Promise<void> {
const entry = this.plugins.get(pluginId);
if (!entry) {
throw new Error(`Plugin ${pluginId} not found`);
}
const pluginPath = entry.pluginPath;
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
// 先卸载插件
await this.unloadPlugin(entry);
// 从注册表移除
this.plugins.delete(pluginId);
// 删除插件目录
if (fs.existsSync(pluginPath)) {
fs.rmSync(pluginPath, { recursive: true, force: true });
}
// 清理插件配置数据
if (cleanData && fs.existsSync(dataPath)) {
fs.rmSync(dataPath, { recursive: true, force: true });
}
}
/**
* 重载指定插件
*/
public async reloadPlugin (pluginId: string): Promise<boolean> {
const entry = this.plugins.get(pluginId);
if (!entry) {
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found`);
return false;
}
try {
// 卸载插件
await this.unloadPlugin(entry);
// 重新扫描
const newEntry = this.loader.rescanPlugin(entry.fileId);
if (!newEntry) {
return false;
}
// 更新注册表
this.plugins.set(newEntry.id, newEntry);
// 重新加载
if (newEntry.enable) {
await this.loadPlugin(newEntry);
}
this.logger.log(`[PluginManager] Plugin ${pluginId} reloaded successfully`);
return true;
} catch (error) {
this.logger.logError(`[PluginManager] Error reloading plugin ${pluginId}:`, error);
return false;
}
}
/**
* 加载目录插件(用于新安装的插件)
*/
public async loadDirectoryPlugin (dirname: string): Promise<void> {
const entry = this.loader.rescanPlugin(dirname);
if (!entry) {
return;
}
// 检查是否已存在
if (this.plugins.has(entry.id)) {
this.logger.logWarn(`[PluginManager] Plugin ${entry.id} already exists`);
return;
}
this.plugins.set(entry.id, entry);
if (entry.enable && entry.runtime.status !== 'error') {
await this.loadPlugin(entry);
}
}
/**
* 获取插件数据目录路径
*/
public getPluginDataPath (pluginId: string): string {
return path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
}
/**
* 获取插件配置文件路径
*/
public getPluginConfigPath (pluginId: string): string {
return path.join(this.getPluginDataPath(pluginId), 'config.json');
}
/**
* 获取插件路由注册器
*/
public getPluginRouter (pluginId: string): PluginRouterRegistryImpl | undefined {
return this.pluginRouters.get(pluginId);
}
/**
* 获取所有插件路由注册器
*/
public getAllPluginRouters (): Map<string, PluginRouterRegistryImpl> {
return this.pluginRouters;
}
// ==================== 事件处理 ====================
async onEvent<T extends OB11EmitEventContent> (event: T): Promise<void> {
if (!this.isEnable) {
return;
}
try {
await Promise.allSettled(
this.getLoadedPlugins().map((entry) =>
this.callPluginEventHandler(entry, event)
)
);
} catch (error) {
this.logger.logError('[PluginManager] Error handling event:', error);
}
}
/**
* 调用插件的事件处理方法
*/
private async callPluginEventHandler (
entry: PluginEntry,
event: OB11EmitEventContent
): Promise<void> {
if (entry.runtime.status !== 'loaded' || !entry.runtime.module || !entry.runtime.context) {
return;
}
const { module, context } = entry.runtime;
try {
// 优先使用 plugin_onevent 方法
if (typeof module.plugin_onevent === 'function') {
await module.plugin_onevent(context, event);
}
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
if (
(event as any).message_type &&
typeof module.plugin_onmessage === 'function'
) {
await module.plugin_onmessage(context, event as OB11Message);
}
} catch (error) {
this.logger.logError(`[PluginManager] Error calling plugin ${entry.id} event handler:`, error);
}
}
// ==================== 生命周期 ====================
async open (): Promise<void> {
if (this.isEnable) {
return;
}
this.logger.log('[PluginManager] Opening plugin manager...');
this.isEnable = true;
// 扫描并加载所有插件
await this.scanAndLoadPlugins();
this.logger.log(`[PluginManager] Plugin manager opened with ${this.getLoadedPlugins().length} plugins loaded`);
}
async close (): Promise<void> {
if (!this.isEnable) {
return;
}
this.logger.log('[PluginManager] Closing plugin manager...');
this.isEnable = false;
// 卸载所有已加载的插件
for (const entry of this.plugins.values()) {
if (entry.loaded) {
await this.unloadPlugin(entry);
}
}
this.logger.log('[PluginManager] Plugin manager closed');
}
async reload (): Promise<OB11NetworkReloadType> {
this.logger.log('[PluginManager] Reloading plugin manager...');
// 先关闭然后重新打开
await this.close();
await this.open();
this.logger.log('[PluginManager] Plugin manager reloaded');
return OB11NetworkReloadType.Normal;
}
}
@@ -73,7 +73,7 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
if (!this.connection && this.isEnable) {
let isClosedByError = false;
this.connection = new WebSocket(this.config.url, {
const wsOptions: WebSocket.ClientOptions = {
maxPayload: 50 * 1024 * 1024, // 50 MB
handshakeTimeout: 2000,
perMessageDeflate: false,
@@ -83,8 +83,14 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
'x-client-role': 'Universal', // 为koishi adpter适配
'User-Agent': 'OneBot/11',
},
};
});
// 如果配置了 verifyCertificate,设置 rejectUnauthorized
if (this.config.verifyCertificate !== undefined) {
wsOptions.rejectUnauthorized = this.config.verifyCertificate;
}
this.connection = new WebSocket(this.config.url, wsOptions);
this.connection.on('pong', () => {
// this.logger.logDebug('[OneBot] [WebSocket Client] 收到pong');
});
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "../../packages"
},
"include": [
"*.ts",
"**/*.ts"
+1 -75
View File
@@ -2,84 +2,10 @@ 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();
// 依赖排除
const external = [];
// 构建后拷贝插件
function copyToShellPlugin () {
return {
name: 'copy-to-shell',
writeBundle () {
try {
const sourceDir = resolve(__dirname, 'dist');
const targetDir = resolve(__dirname, '../napcat-shell/dist/plugins/napcat-plugin-builtin');
const packageJsonSource = resolve(__dirname, 'package.json');
const webuiSourceDir = resolve(__dirname, 'webui');
const webuiTargetDir = resolve(targetDir, 'webui');
// 确保目标目录存在
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++;
}
// 拷贝 webui 目录
if (fs.existsSync(webuiSourceDir)) {
copyDirRecursive(webuiSourceDir, webuiTargetDir);
console.log(`[copy-to-shell] Copied webui directory to ${webuiTargetDir}`);
}
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;
}
},
};
}
// 递归复制目录
function copyDirRecursive (src: string, dest: string) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest, { recursive: true });
}
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = resolve(src, entry.name);
const destPath = resolve(dest, entry.name);
if (entry.isDirectory()) {
copyDirRecursive(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
export default defineConfig({
resolve: {
@@ -102,5 +28,5 @@ export default defineConfig({
external: [...nodeModules, ...external],
},
},
plugins: [nodeResolve(), copyToShellPlugin()],
plugins: [nodeResolve()],
});
+1 -1
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Node",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
+1 -2
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2021",
"module": "ESNext",
"moduleResolution": "Node",
"moduleResolution": "bundler",
"lib": [
"ES2021"
],
@@ -34,7 +34,6 @@
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"baseUrl": ".",
"skipLibCheck": true,
"skipDefaultLibCheck": true
},
+1 -2
View File
@@ -4,10 +4,9 @@
"outDir": "./dist",
"rootDir": "./src",
"noEmit": true,
"baseUrl": ".",
"paths": {
"@/*": [
"../*/"
"../../packages/*"
]
}
},
+97 -11
View File
@@ -126,7 +126,7 @@ async function handleLogin (
quickLoginUin: string | undefined,
historyLoginList: LoginListItem[]
): Promise<SelfInfo> {
const context = { isLogined: false };
const context = { isLogined: false, loginFlowInitialized: false };
let inner_resolve: (value: SelfInfo) => void;
const selfInfo: Promise<SelfInfo> = new Promise((resolve) => {
inner_resolve = resolve;
@@ -142,6 +142,14 @@ async function handleLogin (
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
context.isLogined = true;
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
const oneBotContext = WebUiDataRuntime.getOneBotContext();
if (oneBotContext?.core?.selfInfo) {
oneBotContext.core.selfInfo.online = true;
WebUiDataRuntime.setQQLoginPhase('ready');
} else {
WebUiDataRuntime.setQQLoginPhase('initializing');
}
inner_resolve({
uid: loginResult.uid,
uin: loginResult.uin,
@@ -149,14 +157,35 @@ async function handleLogin (
online: true,
});
};
loginListener.onLoginDisConnected = () => {
context.isLogined = false;
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginPhase('offline');
logger.logWarn('[Core] [Login] 登录服务已断开,将允许重新获取二维码');
};
loginListener.onLogoutSucceed = () => {
context.isLogined = false;
WebUiDataRuntime.setQQLoginStatus(false);
WebUiDataRuntime.setQQLoginPhase('offline');
};
loginListener.onLoginConnected = () => {
waitForNetworkConnection(loginService, logger).then(() => {
handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList).then().catch(e => logger.logError(e));
loginListener.onLoginConnected = () => { };
});
waitForNetworkConnection(loginService, logger).then(async () => {
if (!context.loginFlowInitialized) {
context.loginFlowInitialized = true;
await handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList);
return;
}
if (!context.isLogined) {
WebUiDataRuntime.setQQLoginPhase('generating_qrcode');
const requested = loginService.getQRCodePicture();
logger.logWarn('[Core] [Login] 登录服务重连完成,正在获取二维码', { requested, msfStatus: loginService.getMsfStatus() });
}
}).catch(e => logger.logError(e));
};
loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('waiting_qrcode');
const realBase64 = pngBase64QrcodeData.replace(/^data:image\/\w+;base64,/, '');
const buffer = Buffer.from(realBase64, 'base64');
@@ -175,14 +204,20 @@ async function handleLogin (
});
};
loginListener.onQRCodeSessionUserScaned = () => {
WebUiDataRuntime.setQQLoginPhase('qrcode_scanned');
logger.log('[Core] [Login] 二维码已被扫描,等待确认...');
};
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
if (!context.isLogined) {
logger.logError('[Core] [Login] Login Error,ErrType: ', errType, ' ErrCode:', errCode);
if (errType === 1 && errCode === 3) {
// 二维码过期刷新
// 仅二维码过期时自动请求下一张二维码。账号被踢下线等其他错误
// 需要由用户触发刷新,避免每两秒重复创建原生登录会话。
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
loginService.getQRCodePicture();
}
loginService.getQRCodePicture();
}
};
@@ -196,7 +231,7 @@ async function handleLogin (
loginService.connect();
return await selfInfo;
}
async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
async function handleLoginInner (context: { isLogined: boolean; loginFlowInitialized: boolean; }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
const resolveQuickPasswordMd5 = (): string | undefined => {
const quickPasswordMd5 = process.env['NAPCAT_QUICK_PASSWORD_MD5']?.trim();
if (quickPasswordMd5) {
@@ -217,7 +252,19 @@ async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWr
// 注册刷新二维码回调
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
loginService.getQRCodePicture();
context.isLogined = false;
const msfStatus = loginService.getMsfStatus();
if (msfStatus === 2) {
// KickedOffLine 会在后台负责重启 Worker。这里不能重启:该回调由
// RefreshQRcode HTTP 请求触发,重启会中断正在等待响应的请求。
WebUiDataRuntime.setQQLoginPhase('reconnecting');
throw new Error('QQ_LOGIN_SERVICE_RESTARTING');
}
const requested = loginService.getQRCodePicture();
logger.logWarn('[Core] [Login] 请求刷新二维码', { requested, msfStatus });
if (!requested) {
throw new Error('QQ 未接受二维码刷新请求');
}
});
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
@@ -483,17 +530,27 @@ async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWr
} else {
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
if (historyLoginList.length > 0) {
logger.log(`可用于快速登录的 QQ:\n${historyLoginList
logger.log(`可用于快速登录 of QQ:\n${historyLoginList
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
.join('\n')
}`);
}
loginService.getQRCodePicture();
let hasAttemptedFallback = false;
try {
// 检查是否配置了自动登录账号,并尝试 WebUi 快速/密码回退登录。
// 这可以避免在已经有自动登录配置的情况下过早输出二维码。
const quickLoginList = WebUiDataRuntime.getQQQuickLoginList() || [];
const hasAutoLogin = process.env['NAPCAT_QUICK_ACCOUNT'] || (quickLoginList.length > 0); // 假如有历史登录列表
if (hasAutoLogin || process.env['NAPCAT_QUICK_PASSWORD'] || process.env['NAPCAT_QUICK_PASSWORD_MD5']) {
hasAttemptedFallback = true;
}
await WebUiDataRuntime.runWebUiConfigQuickFunction();
} catch (error) {
logger.logError('WebUi 快速登录失败 执行失败', error);
}
if (!hasAttemptedFallback && !context.isLogined) {
loginService.getQRCodePicture();
}
}
loginService.getLoginList().then((res) => {
@@ -783,8 +840,34 @@ export class NapCatShell {
// }
// 监听下线通知并同步到 WebUI
let restartRequested = false;
this.core.event.on('KickedOffLine', (tips: string) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 被踢后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
if (restartRequested) return;
restartRequested = true;
// 不从 RefreshQRcode 请求中重启 Worker;否则请求会在返回前被中断,
// 浏览器只能得到 ERR_EMPTY_RESPONSE。KickedOffLine 是独立事件,
// 在此异步调度可让前端先观察到“二维码已清空、正在恢复”的状态。
setTimeout(() => {
WebUiDataRuntime.requestRestartProcess().then((restartResult) => {
this.context.logger.logWarn('[Core] [Login] 账号被踢下线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (!restartResult.result) {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
}
}).catch((error) => {
restartRequested = false;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
});
// 常规状态轮询为 3 秒;留出一个轮询周期,确保浏览器先清除旧二维码。
}, 3_500);
});
// 使用 NapCatAdapterManager 统一管理协议适配器
const adapterManager = new NapCatAdapterManager(this.core, this.context, this.context.pathWrapper);
@@ -794,6 +877,9 @@ export class NapCatShell {
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
}
}
+8
View File
@@ -247,6 +247,14 @@ async function startWorker (passQuickLogin: boolean = true, secretKey?: string,
...(preferredPort ? { NAPCAT_WEBUI_PREFERRED_PORT: String(preferredPort) } : {}),
},
stdio: isElectron ? 'pipe' : ['inherit', 'pipe', 'pipe', 'ipc'],
// --no-sandbox 是 Chromium 开关,仅当子进程完整引导 Electron(未设 ELECTRON_RUN_AS_NODE)时
// 才会被解析;纯 Node / Electron node 模式子进程会因 bad option 以退出码 9 拒绝启动
// (ELECTRON_RUN_AS_NODE 变量存在即触发 node 模式,与取值无关)
...(!isElectron &&
process.versions['electron'] &&
process.env['ELECTRON_RUN_AS_NODE'] === undefined
? { execArgv: ['--no-sandbox'] }
: {}),
});
currentWorker = child;
+2 -1
View File
@@ -34,6 +34,7 @@ export interface IWorkerProcess {
export interface ProcessOptions {
env: NodeJS.ProcessEnv;
stdio: 'pipe' | 'ignore' | 'inherit' | Array<'pipe' | 'ignore' | 'inherit' | 'ipc'>;
execArgv?: string[];
}
/**
@@ -168,7 +169,7 @@ export async function createProcessManager (): Promise<{
manager: IProcessManager;
isElectron: boolean;
}> {
const isElectron = typeof process.versions['electron'] !== 'undefined';
const isElectron = process.env['NAPCAT_FORCE_NODE_PROCESS'] !== '1' && typeof process.versions['electron'] !== 'undefined';
if (isElectron) {
// @ts-ignore - electron 运行时存在但类型声明可能缺失
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
+1 -1
View File
@@ -54,7 +54,7 @@ const ShellBaseConfig = (source_map: boolean = false) =>
build: {
sourcemap: source_map,
target: 'esnext',
minify: false,
minify: source_map ? false : 'esbuild',
lib: {
entry: {
napcat: path.resolve(__dirname, 'napcat.ts'),
@@ -0,0 +1,124 @@
import { describe, expect, test } from 'vitest';
import {
applyGroupManagementSettings,
createGroupDetailInfoV2Param,
createGroupManagementRequests,
} from '../napcat-core/data/group';
import { assertGroupManagementResults } from '../napcat-onebot/action/group/GroupOperationHelpers';
describe('NTQQ group operations', () => {
test('reports the exact native setting that failed', () => {
expect(() => assertGroupManagementResults('设置群成员功能权限', [{
setting: 'allow_member_create_group',
result: { result: 1006, errMsg: '未知错误' },
}])).toThrow(/allow_member_create_group.*1006.*未知错误/);
expect(() => assertGroupManagementResults('设置群成员功能权限', []))
.not.toThrow();
});
test('builds the NTQQ permission masks without changing unrelated flags', async () => {
const request = createGroupDetailInfoV2Param('123456');
expect(applyGroupManagementSettings(request, {
memberInvite: 'no_approval',
allowMemberUploadAlbum: false,
allowMemberTemporarySession: true,
allowMemberCreateGroup: false,
newMembersSeeRecentHistory: true,
})).toBe(true);
expect(request.groupCode).toBe('123456');
expect(request.filter).toMatchObject({
allowMemberInvite: 1,
appPrivilegeFlag: 1,
appPrivilegeMask: 1,
groupFlagExt4: 1,
groupFlagExt4Mask: 1,
});
expect(request.modifyInfo).toMatchObject({
allowMemberInvite: 1,
appPrivilegeFlag: 0x00108001,
appPrivilegeMask: 0x06118001,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
groupFlagExt4: 0x4,
groupFlagExt4Mask: 0x4,
});
});
test('maps every member invite policy to the native app privilege value', async () => {
const expected = {
disabled: 0x04000000,
require_approval: 0,
no_approval: 0x00100000,
no_approval_under_100: 0x02000000,
} as const;
for (const [memberInvite, privilegeFlag] of Object.entries(expected)) {
const request = createGroupDetailInfoV2Param('123456');
applyGroupManagementSettings(request, { memberInvite: memberInvite as keyof typeof expected });
expect(request.modifyInfo.allowMemberInvite).toBe(memberInvite === 'disabled' ? 0 : 1);
expect(request.modifyInfo.appPrivilegeFlag).toBe(privilegeFlag);
expect(request.modifyInfo.appPrivilegeMask).toBe(0x06100000);
}
});
test('uses NTQQ privilege operation type 8 for album, temporary-session, and create-group flags', () => {
const requests = createGroupManagementRequests('123456', {
memberInvite: 'require_approval',
allowMemberUploadAlbum: true,
allowMemberTemporarySession: true,
allowMemberCreateGroup: true,
}, 0x18001);
expect(requests.map(request => request.operationType)).toEqual([0, 8, 8, 8]);
expect(requests.map(request => request.setting)).toEqual([
'member_invite',
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
]);
expect(requests.slice(1).map(request => request.param.modifyInfo.appPrivilegeMask))
.toEqual([0x1, 0x10000, 0x8000]);
expect(requests[1]?.param.modifyInfo).toMatchObject({
appPrivilegeFlag: 0x18000,
appPrivilegeMask: 0x1,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
});
expect(requests[2]?.param.modifyInfo).toMatchObject({
appPrivilegeFlag: 0x8000,
appPrivilegeMask: 0x10000,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
});
expect(requests[3]?.param.modifyInfo).toMatchObject({
appPrivilegeFlag: 0,
appPrivilegeMask: 0x8000,
groupFlagExt3: 0,
groupFlagExt3Mask: 0,
});
});
test('preserves the complete privilege value when clearing Linux NTQQ permission bits', () => {
const requests = createGroupManagementRequests('123456', {
allowMemberUploadAlbum: false,
allowMemberTemporarySession: false,
allowMemberCreateGroup: false,
}, 0);
expect(requests.map(request => request.param.modifyInfo.appPrivilegeFlag))
.toEqual([0x1, 0x10001, 0x18001]);
expect(requests.map(request => request.param.modifyInfo.appPrivilegeMask))
.toEqual([0x1, 0x10000, 0x8000]);
});
test('skips privilege requests whose effective value is already current', () => {
const requests = createGroupManagementRequests('123456', {
allowMemberUploadAlbum: true,
allowMemberTemporarySession: true,
allowMemberCreateGroup: true,
newMembersSeeRecentHistory: true,
}, 0x00100000, 0x4);
expect(requests).toEqual([]);
});
});
@@ -2,6 +2,9 @@ import { describe, expect, test, vi } from 'vitest';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbSvcTrpcTcpBase } from '@/napcat-core/packet/transformer/proto/oidb/OidbBase';
import { OidbSvcTrpcTcp0XF90 } from '@/napcat-core/packet/transformer/proto/oidb/Oidb.0xf90';
import SetGroupTodo from '@/napcat-core/packet/transformer/action/SetGroupTodo';
import CompleteGroupTodo from '@/napcat-core/packet/transformer/action/CompleteGroupTodo';
import CancelGroupTodo from '@/napcat-core/packet/transformer/action/CancelGroupTodo';
vi.mock('@/napcat-core/packet/transformer/base', () => ({
PacketTransformer: class PacketTransformer {
@@ -14,10 +17,6 @@ vi.mock('@/napcat-core/packet/transformer/base', () => ({
PacketBufBuilder: (str: Uint8Array) => Buffer.from(str),
}));
import SetGroupTodo from '@/napcat-core/packet/transformer/action/SetGroupTodo';
import CompleteGroupTodo from '@/napcat-core/packet/transformer/action/CompleteGroupTodo';
import CancelGroupTodo from '@/napcat-core/packet/transformer/action/CancelGroupTodo';
const decodePacket = (data: Buffer) => {
const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(data);
const body = new NapProtoMsg(OidbSvcTrpcTcp0XF90).decode(base.body);
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, test } from 'vitest';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
buildQzoneUploadImageBody,
parseQzoneDeleteResponse,
parseQzonePublishResponse,
parseQzoneUploadImageResponseText,
toQzoneRichval,
} from '@/napcat-core/data/qzone';
describe('Qzone data helpers', () => {
test('buildQzoneUploadImageBody encodes required fields', () => {
const body = buildQzoneUploadImageBody({
uin: '123456',
skey: 'sk',
pskey: 'pk',
g_tk: '999',
base64: 'AAAA',
});
const params = new URLSearchParams(body);
expect(params.get('uin')).toBe('123456');
expect(params.get('skey')).toBe('sk');
expect(params.get('p_skey')).toBe('pk');
expect(params.get('picfile')).toBe('AAAA');
expect(params.get('uploadtype')).toBe('1');
expect(params.get('albumtype')).toBe('7');
expect(params.get('base64')).toBe('1');
expect(params.get('qzreferrer')).toContain('123456');
});
test('parseQzoneUploadImageResponseText parses valid callback wrapper', () => {
const raw = 'frameElement.callback({"code":0,"data":{"albumid":"a1","lloc":"l1","type":"22","height":"100","width":"200"}});</script>';
const parsed = parseQzoneUploadImageResponseText(raw);
expect(parsed.code).toBe(0);
expect(parsed.data?.albumid).toBe('a1');
expect(parsed.data?.lloc).toBe('l1');
});
test('parseQzoneUploadImageResponseText throws on malformed response', () => {
expect(() => parseQzoneUploadImageResponseText('not a valid response')).toThrow();
});
test('toQzoneRichval builds expected format', () => {
const richval = toQzoneRichval({ albumid: 'a1', lloc: 'l1', type: '22', height: '100', width: '200' });
expect(richval).toBe(',a1,l1,l1,22,100,200,,100,200');
});
test('buildQzonePublishBody without images omits richval/richtype', () => {
const body = buildQzonePublishBody({
hostuin: '123456',
content: 'hello world',
ugcRight: 1,
});
const params = new URLSearchParams(body);
expect(params.get('con')).toBe('hello world');
expect(params.get('ugc_right')).toBe('1');
expect(params.has('richval')).toBe(false);
expect(params.has('richtype')).toBe(false);
expect(params.has('allow_uins')).toBe(false);
});
test('buildQzonePublishBody with images and allow_uins sets richtype and who', () => {
const body = buildQzonePublishBody({
hostuin: '123456',
content: 'with pic',
richval: ',a1,l1,l1,22,100,200,,100,200\t,a2,l2,l2,22,100,200,,100,200',
ugcRight: 16,
allowUins: '10001|10002',
});
const params = new URLSearchParams(body);
expect(params.get('richtype')).toBe('1');
expect(params.get('richval')).toContain('\t');
expect(params.get('ugc_right')).toBe('16');
expect(params.get('allow_uins')).toBe('10001|10002');
expect(params.get('who')).toBe('1');
});
test('parseQzonePublishResponse extracts tid on success', () => {
const result = parseQzonePublishResponse({ subcode: 0, tid: 'tid123' });
expect(result.tid).toBe('tid123');
});
test('parseQzonePublishResponse prefers t1_tid over tid', () => {
const result = parseQzonePublishResponse({ subcode: 0, tid: 'tid123', t1_tid: 't1tid456' });
expect(result.tid).toBe('t1tid456');
});
test('parseQzonePublishResponse throws when subcode indicates failure', () => {
expect(() => parseQzonePublishResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
});
test('parseQzonePublishResponse throws when tid missing', () => {
expect(() => parseQzonePublishResponse({ subcode: 0 })).toThrow();
});
test('buildQzoneDeleteBody encodes required fields', () => {
const body = buildQzoneDeleteBody({ hostuin: '123456', tid: 'tid123' });
const params = new URLSearchParams(body);
expect(params.get('hostuin')).toBe('123456');
expect(params.get('tid')).toBe('tid123');
expect(params.get('t1_source')).toBe('1');
expect(params.get('code_version')).toBe('1');
expect(params.get('format')).toBe('json');
expect(params.get('qzreferrer')).toContain('123456');
});
test('parseQzoneDeleteResponse succeeds when subcode is 0', () => {
const result = parseQzoneDeleteResponse({ subcode: 0 });
expect(result.success).toBe(true);
});
test('parseQzoneDeleteResponse throws when subcode indicates failure', () => {
expect(() => parseQzoneDeleteResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
});
test('parseQzoneDeleteResponse throws with default message when subcode indicates failure without message', () => {
expect(() => parseQzoneDeleteResponse({ subcode: -200 })).toThrow('subcode=-200');
});
});
+309
View File
@@ -0,0 +1,309 @@
import { describe, expect, test, vi } from 'vitest';
import { ChatType, NTMsgType, type RawMessage } from 'napcat-core';
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
vi.mock('../napcat-webui-backend/index', () => ({
pendingTokenToSend: undefined,
}));
vi.mock('../napcat-webui-backend/src/helper/Data', () => ({
WebUiDataRuntime: {},
}));
vi.mock('@/napcat-onebot/config', () => ({
OB11ConfigLoader: class {},
}));
vi.mock('@/napcat-onebot/network', () => ({
OB11HttpClientAdapter: class {},
OB11WebSocketClientAdapter: class {},
OB11NetworkManager: class {},
OB11NetworkReloadType: {},
OB11HttpServerAdapter: class {},
OB11WebSocketServerAdapter: class {},
}));
vi.mock('@/napcat-onebot/api', () => ({
OneBotFriendApi: class {},
OneBotGroupApi: class {},
OneBotMsgApi: class {},
OneBotQuickActionApi: class {},
OneBotUserApi: class {},
}));
vi.mock('@/napcat-onebot/action', () => ({
createActionMap: vi.fn(),
}));
vi.mock('@/napcat-onebot/network/adapter', () => ({
IOB11NetworkAdapter: class {},
}));
vi.mock('@/napcat-onebot/network/http-server-sse', () => ({
OB11HttpSSEServerAdapter: class {},
}));
vi.mock('@/napcat-onebot/network/plugin-manger', () => ({
OB11PluginMangerAdapter: class {},
}));
vi.mock('@/napcat-onebot/api/file', () => ({
OneBotFileApi: class {},
}));
interface TestMsgListener {
onMsgRecall (chatType: ChatType, uid: string, msgSeq: string): Promise<void> | void;
onMsgInfoListUpdate (messages: RawMessage[]): Promise<void> | void;
}
const friendUid = 'u_friend';
const friendUin = '123456';
const recalledMsgId = 'recalled-message-id';
const recalledMsgSeq = '100';
const botUin = '999999';
function createMessage (overrides: Partial<RawMessage>): RawMessage {
return {
msgId: 'message-id',
msgRandom: '1',
msgSeq: '101',
cntSeq: '101',
chatType: ChatType.KCHATTYPEC2C,
msgType: NTMsgType.KMSGTYPEUNKNOWN,
subMsgType: 0,
sendStatus: 2,
senderUid: friendUid,
senderUin: friendUin,
peerUid: friendUid,
peerUin: friendUin,
peerName: 'friend',
sendNickName: 'friend',
sendRemarkName: 'friend',
msgTime: '1',
recallTime: '0',
elements: [],
records: [],
sourceType: 0,
isOnlineMsg: true,
...overrides,
} as RawMessage;
}
function createRecallGrayTip (): RawMessage {
return createMessage({
msgId: recalledMsgId,
msgSeq: recalledMsgSeq,
msgType: NTMsgType.KMSGTYPEGRAYTIPS,
recallTime: Math.floor(Date.now() / 1000).toString(),
elements: [{
elementType: 8,
elementId: 'recall-element',
grayTipElement: {
revokeElement: {
operatorRole: '0',
operatorUid: friendUid,
operatorNick: 'friend',
operatorRemark: '',
isSelfOperate: false,
wording: '',
},
},
} as unknown as RawMessage['elements'][number]],
});
}
function createHarness (queryResult: RawMessage[], operatorUin = '654321') {
let listener: TestMsgListener | undefined;
const emitEvent = vi.fn(async (_event: unknown): Promise<void> => undefined);
const queryMsgsWithFilterExWithSeq = vi.fn(async () => ({ msgList: queryResult }));
const registerListen = vi.fn();
const logger = {
logDebug: vi.fn(),
logError: vi.fn(),
logMessage: vi.fn(),
};
const context = {
logger,
session: {
getMsgService: () => ({
addKernelMsgListener: (registeredListener: TestMsgListener) => {
listener = registeredListener;
},
}),
},
};
const core = {
selfInfo: { uin: botUin },
apis: {
MsgApi: { queryMsgsWithFilterExWithSeq },
UserApi: { getUinByUidV2: vi.fn(async () => operatorUin) },
},
eventWrapper: { registerListen },
};
const adapter = Object.create(NapCatOneBot11Adapter.prototype) as NapCatOneBot11Adapter;
Object.assign(adapter, {
core,
context,
networkManager: { emitEvent },
bootTime: Date.now() / 1000,
recallEventCache: new Map(),
reportedRecallEventCache: new Map(),
processingRecallEvents: new Map(),
});
(adapter as unknown as { initMsgListener (): void }).initMsgListener();
if (!listener) {
throw new Error('message listener was not registered');
}
return { adapter, listener, emitEvent, logger, queryMsgsWithFilterExWithSeq, registerListen };
}
describe('friend recall reporting', () => {
test('reports a recalled non-latest private message from its gray-tip update', async () => {
const botReply = createMessage({
msgId: 'bot-reply-id',
msgSeq: '101',
senderUid: 'u_bot',
senderUin: botUin,
});
const grayTip = createRecallGrayTip();
const { listener, emitEvent } = createHarness([botReply]);
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
await listener.onMsgInfoListUpdate([grayTip]);
expect(emitEvent).toHaveBeenCalledTimes(1);
expect(emitEvent).toHaveBeenCalledWith(expect.objectContaining({
notice_type: 'friend_recall',
user_id: Number(friendUin),
}));
});
test('deduplicates the same recall from the gray-tip update and recall callback', async () => {
const grayTip = createRecallGrayTip();
const { listener, emitEvent } = createHarness([grayTip]);
await listener.onMsgInfoListUpdate([grayTip]);
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
await listener.onMsgInfoListUpdate([grayTip]);
expect(emitEvent).toHaveBeenCalledTimes(1);
});
test('deduplicates concurrent update and callback processing', async () => {
const grayTip = createRecallGrayTip();
const { listener, emitEvent } = createHarness([grayTip]);
let finishEmit: (() => void) | undefined;
emitEvent.mockImplementationOnce(() => new Promise<void>((resolve) => {
finishEmit = resolve;
}));
const updateTask = listener.onMsgInfoListUpdate([grayTip]);
await vi.waitFor(() => expect(emitEvent).toHaveBeenCalledTimes(1));
const callbackTask = listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
finishEmit?.();
await Promise.all([updateTask, callbackTask]);
expect(emitEvent).toHaveBeenCalledTimes(1);
});
test('uses a concurrent duplicate callback to retry a failed report', async () => {
const grayTip = createRecallGrayTip();
const { listener, emitEvent, logger } = createHarness([grayTip]);
let failFirstEmit: (() => void) | undefined;
emitEvent
.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
failFirstEmit = () => reject(new Error('network unavailable'));
}))
.mockResolvedValueOnce(undefined);
const updateTask = listener.onMsgInfoListUpdate([grayTip]);
await vi.waitFor(() => expect(emitEvent).toHaveBeenCalledTimes(1));
const callbackTask = listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
failFirstEmit?.();
await Promise.all([updateTask, callbackTask]);
expect(emitEvent).toHaveBeenCalledTimes(2);
expect(logger.logError).toHaveBeenCalledWith('处理消息撤回失败', expect.any(Error));
});
test('reports one self recall without waiting for a duplicate callback', async () => {
const grayTip = createRecallGrayTip();
const revokeElement = grayTip.elements[0]?.grayTipElement?.revokeElement;
if (!revokeElement) throw new Error('missing revoke element');
revokeElement.isSelfOperate = true;
const { adapter, listener, emitEvent, registerListen } = createHarness([grayTip]);
const originTimeout = setTimeout(() => undefined, 60_000);
adapter.recallEventCache.set(recalledMsgId, originTimeout);
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
expect(emitEvent).toHaveBeenCalledTimes(1);
expect(adapter.recallEventCache.has(recalledMsgId)).toBe(false);
expect(registerListen).not.toHaveBeenCalled();
});
test('retries reporting when the first network emission fails', async () => {
const grayTip = createRecallGrayTip();
const { listener, emitEvent, logger } = createHarness([grayTip]);
emitEvent
.mockRejectedValueOnce(new Error('network unavailable'))
.mockResolvedValueOnce(undefined);
await listener.onMsgInfoListUpdate([grayTip]);
await listener.onMsgInfoListUpdate([grayTip]);
expect(emitEvent).toHaveBeenCalledTimes(2);
expect(logger.logError).toHaveBeenCalledWith('处理消息撤回失败', expect.any(Error));
});
test('ignores historical recall rows replayed during startup sync', async () => {
const grayTip = createRecallGrayTip();
grayTip.recallTime = Math.floor(Date.now() / 1000 - 120).toString();
const { listener, emitEvent } = createHarness([]);
await listener.onMsgInfoListUpdate([grayTip]);
expect(emitEvent).not.toHaveBeenCalled();
});
test('ignores ordinary message updates', async () => {
const ordinaryMessage = createMessage({ recallTime: Math.floor(Date.now() / 1000).toString() });
const { listener, emitEvent } = createHarness([]);
await listener.onMsgInfoListUpdate([ordinaryMessage]);
expect(emitEvent).not.toHaveBeenCalled();
});
});
describe('group recall reporting', () => {
test('preserves group, sender and operator fields', async () => {
const grayTip = createRecallGrayTip();
const groupUin = '112233';
const senderUin = '223344';
grayTip.chatType = ChatType.KCHATTYPEGROUP;
grayTip.peerUid = groupUin;
grayTip.peerUin = groupUin;
grayTip.senderUin = senderUin;
const { listener, emitEvent } = createHarness([], '334455');
await listener.onMsgInfoListUpdate([grayTip]);
expect(emitEvent).toHaveBeenCalledTimes(1);
expect(emitEvent).toHaveBeenCalledWith(expect.objectContaining({
notice_type: 'group_recall',
group_id: Number(groupUin),
user_id: Number(senderUin),
operator_id: 334455,
}));
});
});
+51
View File
@@ -97,6 +97,57 @@ describe('NapCat Configuration Loaders', () => {
expect(loaded.musicSignUrl).toBe('');
});
test('OneBotConfig websocketClients should apply verifyCertificate default', () => {
const partialConfig: Partial<OneBotConfig> = {
network: {
httpServers: [],
httpSseServers: [],
httpClients: [],
websocketServers: [],
websocketClients: [{
name: 'test-ws-client',
enable: true,
url: 'wss://example.com',
messagePostFormat: 'array',
reportSelfMessage: false,
reconnectInterval: 5000,
token: '',
debug: false,
heartInterval: 30000,
}],
plugins: [],
},
};
const loaded = loadOneBotConfig(partialConfig);
expect(loaded.network.websocketClients[0]?.verifyCertificate).toBe(true);
});
test('OneBotConfig websocketClients should preserve explicit verifyCertificate false', () => {
const partialConfig: Partial<OneBotConfig> = {
network: {
httpServers: [],
httpSseServers: [],
httpClients: [],
websocketServers: [],
websocketClients: [{
name: 'test-ws-client',
enable: true,
url: 'wss://example.com',
messagePostFormat: 'array',
reportSelfMessage: false,
reconnectInterval: 5000,
token: '',
debug: false,
heartInterval: 30000,
verifyCertificate: false,
}],
plugins: [],
},
};
const loaded = loadOneBotConfig(partialConfig);
expect(loaded.network.websocketClients[0]?.verifyCertificate).toBe(false);
});
test('NapcatConfig should compile and apply defaults', () => {
let compiled: ReturnType<typeof TypeCompiler.Compile> | undefined;
expect(() => {
+170
View File
@@ -0,0 +1,170 @@
import { describe, expect, it, vi } from 'vitest';
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
import { ElementType, NTVideoType } from '@/napcat-core/types/msg';
import { SendVideoElement } from '@/napcat-core/types/element';
import {
PacketMsgPicElement,
PacketMsgVideoElement,
} from '@/napcat-core/packet/message/element';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
import { assertUploadResults } from '@/napcat-core/packet/context/uploadResult';
import { Elem, MsgInfo } from '@/napcat-core/packet/transformer/proto';
import { NTV2RichMediaReq } from '@/napcat-core/packet/transformer/proto/oidb/common/Ntv2.RichMediaReq';
import UploadGroupVideo from '@/napcat-core/packet/transformer/highway/UploadGroupVideo';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
function createVideoMsgInfo (): NapProtoEncodeStructType<typeof MsgInfo> {
return {
msgInfoBody: [
{
index: {
info: {
fileSize: 1024,
fileHash: '00112233445566778899aabbccddeeff',
fileSha1: '00112233445566778899aabbccddeeff00112233',
fileName: 'clip.mp4',
type: {
type: 2,
videoFormat: NTVideoType.VIDEO_FORMAT_MP4,
},
width: 1920,
height: 1080,
time: 12,
},
fileUuid: 'video-uuid',
},
},
{
index: {
info: {
fileSize: 2048,
fileHash: 'ffeeddccbbaa99887766554433221100',
fileSha1: 'ffeeddccbbaa99887766554433221100ffeeddcc',
fileName: 'thumb.jpg',
type: {
type: 1,
picFormat: 0,
},
width: 640,
height: 360,
},
fileUuid: 'thumb-uuid',
},
},
],
};
}
function createSendVideoElement (): SendVideoElement {
return {
elementType: ElementType.VIDEO,
elementId: '',
videoElement: {
filePath: 'clip.mp4',
fileName: 'clip.mp4',
videoMd5: '00112233445566778899aabbccddeeff',
thumbMd5: 'ffeeddccbbaa99887766554433221100',
fileTime: 12,
fileFormat: NTVideoType.VIDEO_FORMAT_MP4,
fileSize: '1024',
fileWidth: 1920,
fileHeight: 1080,
thumbWidth: 640,
thumbHeight: 360,
thumbSize: 2048,
thumbPath: new Map([[0, 'thumb.jpg']]),
},
};
}
function decodeElem (
elem: NapProtoEncodeStructType<typeof Elem>
): NapProtoDecodeStructType<typeof Elem> {
const codec = new NapProtoMsg(Elem);
return codec.decode(codec.encode(elem));
}
function createCommonVideoElem (businessType: 11 | 21): NapProtoDecodeStructType<typeof Elem> {
return decodeElem({
commonElem: {
serviceType: 48,
businessType,
pbElem: new NapProtoMsg(MsgInfo).encode(createVideoMsgInfo()),
},
});
}
describe('packet video forwarding', () => {
it('emits only the common rich-media element so mobile rendering is not blocked', () => {
const video = new PacketMsgVideoElement(createSendVideoElement());
video.msgInfo = createVideoMsgInfo();
video.businessType = 11;
const elems = video.buildElement();
expect(elems).toHaveLength(1);
expect(elems[0]?.videoFile).toBeUndefined();
expect(elems[0]?.commonElem?.serviceType).toBe(48);
expect(elems[0]?.commonElem?.businessType).toBe(11);
expect(video.valid).toBe(true);
});
it('parses common business type 11/21 as video instead of image', () => {
for (const businessType of [11, 21] as const) {
const commonElem = createCommonVideoElem(businessType);
expect(PacketMsgPicElement.parseElement(commonElem)).toBeUndefined();
const parsed = new PacketMsgConverter().packetMsgToRaw([commonElem]);
expect(parsed).toHaveLength(1);
expect(parsed[0]?.[0].elementType).toBe(ElementType.VIDEO);
expect(parsed[0]?.[0].picElement).toBeUndefined();
expect(parsed[0]?.[0].videoElement).toMatchObject({
fileName: 'clip.mp4',
fileTime: 12,
fileWidth: 1920,
fileHeight: 1080,
thumbWidth: 640,
thumbHeight: 360,
fileUuid: 'video-uuid',
});
}
});
it('preserves video metadata in the rich-media upload request', () => {
const video = new PacketMsgVideoElement(createSendVideoElement());
video.fileSha1 = '00112233445566778899aabbccddeeff00112233';
video.thumbSha1 = 'ffeeddccbbaa99887766554433221100ffeeddcc';
const packet = UploadGroupVideo.build(123456, video);
const envelope = OidbBase.parse(packet.data);
const request = new NapProtoMsg(NTV2RichMediaReq).decode(envelope.body);
const videoInfo = request.upload?.uploadInfo[0]?.fileInfo;
const thumbInfo = request.upload?.uploadInfo[1]?.fileInfo;
expect(videoInfo).toMatchObject({
fileName: 'clip.mp4',
fileSize: 1024,
width: 1920,
height: 1080,
time: 12,
});
expect(videoInfo?.type.videoFormat).toBe(NTVideoType.VIDEO_FORMAT_MP4);
expect(thumbInfo?.fileName).toBe('ffeeddccbbaa99887766554433221100.jpg');
});
it('propagates resource upload failures instead of silently continuing', () => {
const uploadError = new Error('thumb upload failed');
const logger = {
warn: vi.fn(),
error: vi.fn(),
};
expect(() => assertUploadResults([
{ status: 'fulfilled', value: undefined },
{ status: 'rejected', reason: uploadError },
], logger)).toThrow('上传转发消息资源失败');
expect(logger.warn).toHaveBeenCalledWith('上传资源2个,失败1个');
expect(logger.error).toHaveBeenCalledOnce();
});
});
+131
View File
@@ -0,0 +1,131 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { OneBotFileApi } from '@/napcat-onebot/api/file';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { NTVideoType } from '@/napcat-core/types/msg';
const MP4_HEADER = Buffer.from([
0x00, 0x00, 0x00, 0x18,
0x66, 0x74, 0x79, 0x70,
0x69, 0x73, 0x6f, 0x6d,
0x00, 0x00, 0x00, 0x00,
0x69, 0x73, 0x6f, 0x6d,
]);
const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const JPEG_HEADER = Buffer.from([0xff, 0xd8, 0xff, 0xe0]);
describe('OneBot video send modes', () => {
let tempDir: string;
let sourceVideoPath: string;
let uploadedVideoPath: string;
let fileApi: OneBotFileApi;
beforeEach(async () => {
tempDir = await mkdtemp(path.join(tmpdir(), 'napcat-video-send-mode-'));
sourceVideoPath = path.join(tempDir, 'clip.mp4');
uploadedVideoPath = path.join(tempDir, 'cache', 'Ori', 'clip.mp4');
await mkdir(path.dirname(uploadedVideoPath), { recursive: true });
await Promise.all([
writeFile(sourceVideoPath, MP4_HEADER),
writeFile(uploadedVideoPath, MP4_HEADER),
]);
const core = {
NapCatTempPath: tempDir,
context: {
logger: {
logError: vi.fn(),
},
},
apis: {
FileApi: {
uploadFile: vi.fn().mockResolvedValue({
fileName: 'clip.mp4',
path: uploadedVideoPath,
fileSize: MP4_HEADER.length,
md5: '00112233445566778899aabbccddeeff',
}),
copyFile: vi.fn(),
},
},
} as unknown as ConstructorParameters<typeof OneBotFileApi>[1];
fileApi = new OneBotFileApi(
{} as ConstructorParameters<typeof OneBotFileApi>[0],
core
);
});
afterEach(async () => {
vi.restoreAllMocks();
await rm(tempDir, { recursive: true, force: true });
});
it('uses a PNG thumbnail and legacy minimal metadata for direct kernel sends', async () => {
const getVideoInfo = vi.spyOn(FFmpegService, 'getVideoInfo').mockResolvedValue({
width: 480,
height: 852,
time: 3.6,
format: 'jpg',
size: MP4_HEADER.length,
filePath: sourceVideoPath,
});
const extractLegacyThumbnail = vi
.spyOn(FFmpegService, 'extractLegacyVideoThumbnail')
.mockImplementation(async (_videoPath, thumbnailPath) => {
await writeFile(thumbnailPath, PNG_HEADER);
});
const context = {
deleteAfterSentFiles: [],
peer: {},
} as unknown as Parameters<OneBotFileApi['createValidSendVideoElement']>[0];
const element = await fileApi.createValidSendVideoElement(context, sourceVideoPath);
const thumbnailPath = element.videoElement.thumbPath?.get(0) as string;
expect(getVideoInfo).toHaveBeenCalledWith(sourceVideoPath, '');
expect(extractLegacyThumbnail).toHaveBeenCalledWith(sourceVideoPath, thumbnailPath);
expect(path.extname(thumbnailPath)).toBe('.png');
expect((await readFile(thumbnailPath)).subarray(0, PNG_HEADER.length)).toEqual(PNG_HEADER);
expect(element.videoElement.fileTime).toBe(3.6);
expect('fileFormat' in element.videoElement).toBe(false);
expect('fileWidth' in element.videoElement).toBe(false);
expect('fileHeight' in element.videoElement).toBe(false);
});
it('keeps JPEG thumbnails and complete metadata for packet forward uploads', async () => {
const getVideoInfo = vi
.spyOn(FFmpegService, 'getVideoInfo')
.mockImplementation(async (videoPath, thumbnailPath) => {
await writeFile(thumbnailPath, JPEG_HEADER);
return {
width: 480,
height: 852,
time: 3.6,
format: 'jpg',
size: MP4_HEADER.length,
filePath: videoPath,
};
});
const extractLegacyThumbnail = vi.spyOn(FFmpegService, 'extractLegacyVideoThumbnail');
const context = {
deleteAfterSentFiles: [],
peer: {},
usePacketVideoMetadata: true,
} as unknown as Parameters<OneBotFileApi['createValidSendVideoElement']>[0];
const element = await fileApi.createValidSendVideoElement(context, sourceVideoPath);
const thumbnailPath = element.videoElement.thumbPath?.get(0) as string;
expect(getVideoInfo).toHaveBeenCalledWith(sourceVideoPath, thumbnailPath);
expect(extractLegacyThumbnail).not.toHaveBeenCalled();
expect(path.extname(thumbnailPath)).toBe('.jpg');
expect((await readFile(thumbnailPath)).subarray(0, JPEG_HEADER.length)).toEqual(JPEG_HEADER);
expect(element.videoElement.fileTime).toBe(4);
expect(element.videoElement.fileFormat).toBe(NTVideoType.VIDEO_FORMAT_MP4);
expect(element.videoElement.fileWidth).toBe(480);
expect(element.videoElement.fileHeight).toBe(852);
});
});
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more