Compare commits

...
91 Commits
Author SHA1 Message Date
手瓜一十雪 ff9a829e29 fix(shell): preserve Windows launcher paths and elevation arguments
macOS QQ runtime / runtime (arm64, macos-15) (push) Canceled after 0s
macOS QQ runtime / runtime (x64, macos-15-intel) (push) Canceled after 0s
Windows launcher / launchers (push) Canceled after 0s
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
macOS native compatibility / native (arm64, macos-15) (push) Canceled after 0s
macOS native compatibility / native (x64, macos-15-intel) (push) Canceled after 0s
2026-10-10 11:17:31 +08:00
手瓜一十雪 f8786c65de test(macos): read XML entitlements and cache verified QQ image 2026-10-10 10:41:55 +08:00
手瓜一十雪 038dd558da test(macos): exercise signed QQ with native modules without login 2026-10-10 10:29:52 +08:00
手瓜一十雪 abda6a96de fix(native): complete cross-platform media and packet integration
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
macOS native compatibility / native (arm64, macos-15) (push) Canceled after 0s
macOS native compatibility / native (x64, macos-15-intel) (push) Canceled after 0s
2026-10-10 09:53:28 +08:00
H3CoF6 4e2c48624a fix(onebot): 修复 create_flash_task 触发的 QQ 内核崩溃,并新增时效字段 (#2098) 2026-10-10 05:37:09 +08:00
手瓜一十雪 1c0f7cce4f fix(macos): support verified QQ builds on arm64 and x64 2026-10-10 01:05:09 +08:00
手瓜一十雪 b31e1c0f0c fix(packet): extend QQ build coverage from 40768 to 53644
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-09 22:15:24 +08:00
手瓜一十雪 83c1d1d596 fix(packet): support QQ 53644 and missing recent builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-09 20:19:36 +08:00
Shxiao 05feca9a2c fix(onebot): get_group_files_by_folder 不再丢弃子文件夹 (#2095)
该接口的 returnSchema 声明了 folders(文件夹列表),actionDescription
也写着「获取指定群文件夹下的文件及子文件夹列表」,但 _handle 把 folders
硬编码成空数组。

它调用的 MsgApi.getGroupFileList 与 get_group_root_files 相同,返回项
既可能带 fileInfo 也可能带 folderInfo;兄弟实现 GetGroupRootFiles 把
两类都映射了出来。后果是进入某个子目录后无法继续往下遍历,调用方永远
只能拿到空的 folders。

改为按兄弟接口的方式映射 folderInfo。
2026-10-07 22:05:51 +08:00
Shxiao f750d95545 fix(onebot): 恢复 set_group_leave 的 is_dismiss 解散群聊支持 (#2094)
payloadSchema 声明了 is_dismiss(是否解散),该字段也会出现在 build:openapi
生成的接口文档中,但 _handle 始终只调用 quitGroup:群主传 is_dismiss=true
期望解散群聊时,实际只把账号退出群聊——群没解散,账号却已经不在群里。

同一问题曾在 #1694(deae7fd4)修复过。该 PR 随后被 #1701(e6f646837,
2026-03-13)整包回滚,54 个文件全部撤销;触发原因记录在 #1700(v4.17.48
无法正常发送 JSON 卡片消息),回滚后 v4.17.49 确认修复。回滚一并删掉了
destroyGroup 与 is_dismiss 分支,本次只恢复这一条分支。

本补丁不触碰任何 schema、描述与示例字段。
2026-10-07 22:05:16 +08:00
手瓜一十雪 ec6aadaeea fix(shell): support QQ 9.9.36 Windows file query aliases
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-07 00:07:42 +08:00
手瓜一十雪 463d3ea5b1 fix(test): use typed spawn options for Windows batch regression
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-06 18:08:08 +08:00
手瓜一十雪 0d6ce7f509 fix(ci): sync typescript dependency in workspace lockfile 2026-10-06 18:07:06 +08:00
手瓜一十雪 4f1401da78 fix(types): preserve complete nested types during post-processing
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Use the TypeScript parser instead of a regex that truncates nested generics and function types. Validate generated syntax and add a regression test. Include workspace aliases and PTY ambient declarations. The full type package build still reports six errors in third-party node-pty source; this commit does not claim to resolve that remaining issue.
2026-10-06 17:51:21 +08:00
手瓜一十雪 9109b8cfe2 fix: repair Windows release dependencies and loader paths
Bundle required crypto and SSL DLLs and gate releases on a Windows native-load smoke test. Resolve loader paths independently of the working directory and encode file URLs correctly. Include the quick-login launcher built from Windows-Boot 0ff70ce10e34ac26411f9e6bcedaedfacc1e74f0. Validated builds, five path regressions, and live Shell and Windows Node startup to QR login.
2026-10-06 17:51:21 +08:00
手瓜一十雪 297133a1b1 fix(shell): update Windows hook for native file information queries
Include the x64 Release hook built from NapCat-Windows-Boot commit 789e6cce00be40d02659e1aca992f8cd928b790a. SHA256: 7C48E7D10D77E2C3936E5D190AEB0DDEE353D55FD06DE81C714F2740112B94B1.

Related to #2091. The replacement passes 10 independent Win32 checks; the reported QQ crash remains to be verified in the reporter's environment.
2026-10-06 16:54:12 +08:00
sj817 454cc0eda2 ci(release): 下游 AppImage 用的 QQ 换成 3.2.32-52194
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
原来的 3.2.30-50969 链接已经 404,v4.18.29 发版时 AppImage、NodeLoader 的构建都因此失败。
2026-10-05 13:50:01 +08:00
sj817 435cb7cf52 fix(core): Windows Server 缺少媒体基础组件时给出明确提示
QQNT.dll 静态依赖 mf.dll / mfplat.dll / mfreadwrite.dll,Windows Server 默认不安装
「媒体基础」,加载 wrapper.node 时系统只报 The specified module could not be found(#2069)。
现在 Windows 下加载失败且找不到 mfplat.dll 时,直接提示安装媒体基础的方法。
2026-10-05 13:37:07 +08:00
sj817 8005afebd2 fix: 静默离线等 60 秒再重启 Worker,被踢下线不受影响
静默离线(#2080)原来和被踢下线一样 3.5 秒后就重启 Worker。网络短暂断开时 QQ
也可能报离线,这样一次网络抖动就会把整个 Worker 重启掉。现在静默离线先等 60 秒,
期间恢复在线就不重启;等待期间收到被踢通知则不再等,按原来的 3.5 秒重启。

Shell 和 Framework 里重复的下线处理抽成 createOfflineRecovery,并补上测试。
2026-10-05 13:23:32 +08:00
xboHodx a8f6a57311 feat: 群相册支持多图同批次上传与视频上传,分片上传改为并发 (#2081)
- 新增 upload_images_to_qun_album:多张图片共用一个批次,相册里显示为同一条
- 新增 upload_video_to_qun_album:上传视频并自动抽取首帧作为封面
- 分片大小改用服务端返回的 slice_size,分片并发上传,最后一片等其它分片传完再发
- 摘要改为流式计算,分片按需读取,不再把整个文件读进内存
- 批次号同一秒内递增,避免两次上传被并成一条
2026-10-05 13:21:38 +08:00
sj817 c0fd089539 chore(release): 发布说明换成仍可下载的 QQ 官方 CDN 链接
原来的 9.9.26-44343 / 3.2.23-44343 / Mac 40990 链接已经全部 404。
换成 Windows 9.9.33-52230 和 Linux 3.2.32-52194 的官方 CDN 链接并标注,
附上 GitHub 镜像作为备用,MacOS 写明暂不支持。
2026-10-05 12:45:34 +08:00
sj817 88643854a0 fix(core): 新入群拉不到成员列表时群消息不再整条丢失
- getGroupMember 在群成员缓存刷新失败时 members 为 undefined,
  直接 members!.values() 抛 TypeError,整条群消息上报失败;
  现在返回 undefined,拉取失败的结果也不再写进缓存
- 未缓存的群刚刷新过就不再重复强制拉取,群消息处理里也去掉重复查询
- 临时会话按来源群号查成员,之前误把对方 QQ 号当群号去拉成员列表
- uin 转 uid 在 NT 接口都查不到时,先从已缓存的群成员里找

Refs #2070
2026-10-05 12:39:05 +08:00
Shxiao 9a06abbbbd fix: 静默离线(无 KickedOffLine 通知)后自动恢复登录 (#2080)
服务端静默断开会话时不会下发 KickedOffLine,onSelfStatusChanged 仅把
selfInfo.online 置为 false 并打一行日志,没有任何消费者:进程与 WS 连接
继续存活,下游 OneBot 客户端长时间收不到任何事件。

- core 在 在线 -> 离线 的跳变上广播新的 SelfOffline 事件(重复的 status=20
  不重复触发,未登录时不触发)
- framework/shell 复用 #2030 已建立的下线恢复链路:同步 WebUI -> 重启 Worker
  -> 快速登录
- 静默离线可能是临时状态,重启前重新确认仍未恢复,避免误重启 Worker

Closes #2071
2026-10-05 12:06:22 +08:00
sj817 8371359677 fix(webui): Firefox 下关闭卡片倾斜效果,修复登录页内容不显示
Firefox 里 backdrop-filter 和 3D transform 作用在同一个元素上时,卡片里
带层叠上下文的元素(标题、输入框、按钮)不会被绘制,登录页只剩一行提示文字。
报告者在 macOS 的 Firefox 157 上确认:去掉 transform 或 backdrop-filter
任意一个都能恢复,只去掉 transform 时鼠标移上去重新倾斜又会消失。

倾斜只是装饰,保留毛玻璃效果,Firefox 下不再设置 transform 和 will-change,
鼠标光晕照常显示。其他浏览器行为不变。

Closes #2083
2026-10-05 11:46:26 +08:00
sj817 651c15aa61 fix(native): 更新 MoeHoo,修复收到空包时 QQ 进程段错误
QQ 在网络未就绪、连接异常等情况下会以空包调用收发函数,MoeHoo 的
recv_hook/send_hook 不判空直接解引用,导致 QQ 进程 SIGSEGV(#2060、#1668,
崩溃点为 recv_hook+34)。Docker 部署启动后几秒内崩溃就是这个原因。

MoeHoo-NapCat new-test@ff1e937:空包直接交给原函数,不再解引用。
二进制来自该提交的 CI(run 37260275360),更新 linux.x64、linux.arm64、win32.x64。
darwin.arm64 现有二进制与 CI 产物不是同一套实现(54 KB / 1.1 MB),且无法在 Mac 上验证,
本次不更新。

验证:用伪造的 wrapper.node 在 Linux x64 上让 MoeHoo 挂钩同签名函数,
旧二进制在空包、空 src、空指针参数、发送空包时都会段错误,新二进制都正常返回,
正常包的回调内容(uin、cmd、seq、数据)与旧版一致。
2026-10-05 11:44:48 +08:00
sj817 00729e4807 feat(onebot): 群文件夹返回最后修改时间与修改者
get_group_root_files 返回的文件夹新增 modify_time、modifier、modifier_name,
取自 NT 原始数据 folderInfo 的 modifyTime / modifyUin / modifyName,
命名与群文件已有的 modify_time 保持一致。

Closes #1964
2026-10-05 11:07:59 +08:00
sj817 5ef4f6cb7c fix(webui): Passkey 检查不再阻塞 Token 登录
在电脑端注册 Passkey 后用手机打开 WebUI,本机没有对应 Passkey 时
navigator.credentials.get 可能一直不返回,而检查期间 Token 输入框和回车登录
都被禁用,页面就卡在「正在检查Passkey」。

- 检查 Passkey 期间不再禁用 Token 输入框和回车登录
- credentials.get 加 30 秒超时和 AbortController
- 提交 Token 或离开页面时取消仍在等待的 Passkey 验证

Closes #2076
2026-10-05 11:07:59 +08:00
sj817 13a8a2b8dd fix(onebot): get_group_notice 返回「发给新成员」公告
get_t_list 会把「发给新成员」类公告单独放在 inst 数组里,之前只遍历 feeds,
这类公告(群规通常发在这里)完全拿不到。现在把 inst 条目追加在 feeds 之后返回,
已有条目的顺序不变,并按 fid 去重。

新增字段:
- send_to_new_member:是否为「发给新成员」公告
- pinned:由 inst 条目的 settings.inst_no_pinned 映射(0 = 置顶),
  feeds 条目读不到置顶状态,不带该字段

Closes #2082
2026-10-05 11:07:42 +08:00
手瓜一十雪 8d69a8e086 feat
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-04 20:24:08 +08:00
Shxiao 26d7533e0f fix: get_friend_msg_history 未透传 quick_reply 参数 (#2073)
payload schema 声明了 quick_reply,但 _handle 调用 parseMessage 时
没有传入,字段被静默忽略;与 get_group_msg_history 行为不一致。
将 payload.quick_reply 作为第 5 个参数透传,并补充回归测试。
2026-09-29 15:18:10 +08:00
风澪 870a6060b8 fix(onebot): 私聊引用丢失 reply 段——按 clientSeq 反查被引用消息 (#2016)
私聊被引用时,引用元素里的 replayMsgSeq 常为 0(客户端未填序号),
replyElement 的三条 seq 查询与协议兜底都会落空,最终返回 null;null 段
被 parseMessageSegments 过滤掉,于是事件里没有 reply 段、也没有报错(#1508)。

同一元素携带的 replyMsgClientSeq / replyMsgTime 在这种场景下依然准确,而
NapCat 已有按 (peer, clientSeq, time) 查询的 getMsgByClientSeqAndTime
(此前无调用点)。这里在 seq 查询链失败之后用它反查被引用消息,命中即用
真实的 msgId 构造 reply 段。

新路径仅在 seq 链失败后追加,群聊与带真实序号的私聊行为不变。

实测(NapCat 4.18.28 / OneBot 私聊):
- 日志复现「方法1/2/3 查询失败,序号: 0」→「所有查找方法均失败」
- 修复后 reply 段的 id 等于被引用消息自身事件里的 message_id,
  get_msg 可反查,带 reply 段回发引用正常

注:本 PR 先前版本改为直用 records.msgId,实测证伪——那是每次事件一份的
快照 id,get_msg 查不到、回发引用会被静默丢弃,已放弃该方案。
2026-09-29 15:18:04 +08:00
Shxiao 0b4cfe65ed fix: set_qq_profile 无法将性别设置为 0(未知) (#2065) 2026-09-23 16:52:24 +08:00
Shxiao 46e505f4ba fix: 移出精华消息时 msg_random 与 msg_seq 参数顺序错误 (#2064) 2026-09-23 10:08:42 +08:00
手瓜一十雪 2049e64260 Add newer QQ appids and arch-aware lookup
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Updated the external QQ appid, native, and packet tables for newer Linux and Windows builds, including architecture-specific Linux AppID entries. QQBasicInfoWrapper now prefers the matching x64/arm64 AppID before falling back to version-only lookups, and regression tests cover Linux/Windows version resolution and fallback behavior.
2026-09-14 12:36:00 +08:00
手瓜一十雪 7a35ef035a Pin Windows QQ package for release build
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
The Windows release workflow now uses a fixed QQ installer URL and SHA256 hash, verifies the downloaded installer before packaging, and makes the download cache key sensitive to the selected QQ URL, hash, and Node version. The workflow also switches QQ downloads to curl with retries for transient HTTP errors and centralizes the Node version variable to keep the build config consistent.
2026-09-14 12:01:24 +08:00
五加一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
194 changed files with 9200 additions and 2211 deletions

No files matched your search

+8 -6
View File
@@ -5,12 +5,14 @@
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
+10 -8
View File
@@ -24,7 +24,7 @@
- **控制数量**:最终保持 5-15 条更新要点
- **保留 commit hash**:每条末尾附上短 hash,格式 `(a1b2c3d)`
## 输出模板 - 必须严格遵守以下格式
## 输出模板 - 必须严格遵守以下格式,不要使用代码区域包裹
```
# {VERSION}
@@ -44,12 +44,14 @@ NapCat.Shell.Windows.OneKey.zip (无头)
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
**[9.9.26-44343 X64 Win](https://dldir1.qq.com/qqfile/qq/QQNT/40d6045a/QQ9.9.26.44343_x64.exe)**
[LinuxX64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_amd64.deb)
[LinuxX64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.rpm)
[LinuxArm64 DEB 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.deb)
[LinuxArm64 RPM 44343 ](https://dldir1.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_aarch64.rpm)
[MAC DMG 40990 ](https://dldir1v6.qq.com/qqfile/qq/QQNT/c6cb0f5d/QQ_v6.9.82.40990.dmg)
以下均为腾讯官方 CDN 链接,腾讯会不定期下架旧版本,链接失效时可以在 [Rodert/qq-versions](https://github.com/Rodert/qq-versions/releases) 找同版本的镜像
**[9.9.33-52230 X64 Win(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/497e2f1f/QQ_9.9.33_260813_x64_01.exe)**
[LinuxX64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_amd64_01.deb)
[LinuxX64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_x86_64_01.rpm)
[LinuxArm64 DEB 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_arm64_01.deb)
[LinuxArm64 RPM 52194(官方 CDN)](https://qqdl.gtimg.cn/qqfile/QQNT/9.9.33/release/3f89efc5/QQ_3.2.32_260812_aarch64_01.rpm)
**MacOS 暂不支持**
## 如果WinX64缺少运行库或者xxx.dll?
[安装运行库](https://aka.ms/vs/17/release/vc_redist.x64.exe)
@@ -76,7 +78,7 @@ NapCat.Shell.Windows.OneKey.zip (无头)
- "Windows 一键包"部分的文本必须完全一致,不要修改任何措辞
- "警告"部分必须包含所有 QQ 版本下载链接,保持原有格式
- "如果WinX64缺少运行库或者xxx.dll?"这一行必须保持原样
- QQ 版本号和下载链接保持不变(40990 版本)
- QQ 版本号、下载链接、"官方 CDN"标注和"MacOS 暂不支持"保持不变
- 只有"## 更新"部分下面的内容需要根据实际 commit 生成
## 重要约束
+23 -1
View File
@@ -254,6 +254,28 @@ export class GitHubAPI {
}
}
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[]> {
@@ -293,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);
});
+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',
+1 -1
View File
@@ -19,7 +19,7 @@
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, basename, resolve } from 'node:path';
import { join, resolve } from 'node:path';
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
import { toProxyUrl } from './lib/comment.ts';
+93
View File
@@ -0,0 +1,93 @@
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const { join } = require('node:path');
const { test } = require('node:test');
const nativePath = join(__dirname, '../../../packages/napcat-native');
const napiPath = join(nativePath, 'napi2native', 'napi2native.darwin.' + process.arch + '.node');
const packetPath = join(nativePath, 'packet', 'MoeHoo.darwin.' + process.arch + '.node');
async function probe (mode) {
if (mode === 'missing-wrapper') {
const napi = require(napiPath);
assert.throws(() => napi.initHook('1', '2'), /Failed to initialize send hook/);
const packet = require(packetPath);
assert.equal(packet.initHook('2', '4', () => {}, false), 'error search');
return;
}
const wrapper = require('./wrapper.node');
const addresses = wrapper.addresses();
const napi = require(napiPath);
assert.equal(napi.initHook(addresses.coerce, addresses.resolver), true);
const lengths = [0, 1, 21, 22, 23, 24, 255, 4096];
for (const length of lengths) {
const payload = Buffer.from(Array.from({ length }, (_, index) => index % 256));
assert.deepEqual(wrapper.convert(payload), payload, 'convert length ' + length);
const error = Buffer.from('e'.repeat(length));
const result = await wrapper.resolve(-17, error, payload);
assert.equal(result.result, -17);
assert.equal(result.errMsg, error.toString());
assert.equal(result.rsp, payload.toString());
assert.deepEqual(result.rspbuffer, payload, 'resolve length ' + length);
}
for (const value of ['', '文🙂'.repeat(20), 12345, null, true]) {
assert.deepEqual(wrapper.convert(value), Buffer.from(String(value)));
}
const responses = await Promise.all(Array.from({ length: 64 }, (_, index) => {
const payload = Buffer.from([0, index, 255, 128]);
return wrapper.resolve(index, Buffer.alloc(0), payload).then(result => {
assert.equal(result.result, index);
assert.deepEqual(result.rspbuffer, payload);
});
}));
assert.equal(responses.length, 64);
const packet = require(packetPath);
const received = [];
assert.equal(packet.initHook(addresses.send, addresses.recv, (...args) => received.push(args), false), 'success');
assert.equal(wrapper.emptyPackets(), 7);
const expected = [];
for (const length of lengths) {
const uin = Buffer.from('1'.repeat(length));
const command = Buffer.from('C'.repeat(length));
const payload = Buffer.from(Array.from({ length }, (_, index) => index % 256));
for (const direction of [0, 1]) {
const sequence = length + 3000;
const result = wrapper.packet(direction, uin, command, sequence, payload);
assert.equal(result.returned, direction === 0 ? 102 : 209);
assert.deepEqual(result.command, command);
expected.push([direction, direction === 0 ? '0' : uin.toString(), command.toString(), sequence, payload.toString('hex').toUpperCase()]);
}
}
const embeddedNull = Buffer.from('A\0B');
wrapper.packet(1, embeddedNull, embeddedNull, 99, Buffer.from([255, 0, 128]));
expected.push([1, 'A\0B', 'A\0B', 99, 'FF0080']);
packet.setO3Setting(true);
const replaced = wrapper.packet(0, Buffer.from('1'), Buffer.from('trpc.o3.report.Report.SsoReport'), 0, Buffer.alloc(0));
assert.equal(replaced.command.toString(), 'fuck.trpc.o3');
packet.setO3Setting(false);
for (let attempt = 0; received.length < expected.length && attempt < 100; attempt++) {
await new Promise(resolve => setTimeout(resolve, 10));
}
assert.deepEqual(received, expected);
}
if (process.argv[2] === '--probe') {
probe(process.argv[3]).catch(error => {
console.error(error);
process.exitCode = 1;
});
} else {
for (const mode of ['missing-wrapper', 'hooks']) {
test('macOS ' + process.arch + ' native ' + mode, () => {
const result = spawnSync(process.execPath, [__filename, '--probe', mode], {
encoding: 'utf8',
timeout: 20000,
});
assert.ifError(result.error);
assert.equal(result.signal, null, result.stderr);
assert.equal(result.status, 0, result.stderr + result.stdout);
});
}
}
+317
View File
@@ -0,0 +1,317 @@
#include <node_api.h>
#include <array>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <sstream>
#include <string>
#include <vector>
struct alignas(8) QQString
{
std::array<uint8_t, 24> bytes{};
};
#if defined(__aarch64__)
constexpr size_t flagOffset = 23;
constexpr size_t dataOffset = 0;
constexpr uint8_t heapMask = 0x80;
#else
constexpr size_t flagOffset = 0;
constexpr size_t dataOffset = 16;
constexpr uint8_t heapMask = 1;
#endif
static uint64_t ReadWord(const QQString &value, size_t offset)
{
uint64_t word;
std::memcpy(&word, value.bytes.data() + offset, sizeof(word));
return word;
}
static void WriteWord(QQString &value, size_t offset, uint64_t word)
{
std::memcpy(value.bytes.data() + offset, &word, sizeof(word));
}
static QQString MakeString(const void *data, size_t length)
{
QQString value;
if (length <= 22)
{
#if defined(__aarch64__)
std::memcpy(value.bytes.data(), data, length);
value.bytes[23] = length;
#else
std::memcpy(value.bytes.data() + 1, data, length);
value.bytes[0] = length * 2;
#endif
}
else
{
size_t capacity = (length | 15) + 1;
auto buffer = static_cast<uint8_t *>(std::calloc(capacity, 1));
std::memcpy(buffer, data, length);
WriteWord(value, dataOffset, reinterpret_cast<uintptr_t>(buffer));
WriteWord(value, 8, length);
#if defined(__aarch64__)
WriteWord(value, 16, capacity | (uint64_t{1} << 63));
#else
WriteWord(value, 0, capacity | 1);
#endif
}
return value;
}
static std::string ReadString(const QQString &value)
{
if ((value.bytes[flagOffset] & heapMask) != 0)
return {reinterpret_cast<const char *>(ReadWord(value, dataOffset)), ReadWord(value, 8)};
#if defined(__aarch64__)
return {reinterpret_cast<const char *>(value.bytes.data()), value.bytes[23]};
#else
return {reinterpret_cast<const char *>(value.bytes.data() + 1), static_cast<size_t>(value.bytes[0] / 2)};
#endif
}
static void FreeString(const QQString &value)
{
if ((value.bytes[flagOffset] & heapMask) != 0)
std::free(reinterpret_cast<void *>(ReadWord(value, dataOffset)));
}
static QQString FromBuffer(napi_env env, napi_value input)
{
void *data;
size_t length;
napi_get_buffer_info(env, input, &data, &length);
return MakeString(data, length);
}
extern "C" __attribute__((noinline)) QQString MockCoerce(napi_env env, napi_value input)
{
napi_value text;
napi_coerce_to_string(env, input, &text);
size_t length;
napi_get_value_string_utf8(env, text, nullptr, 0, &length);
std::vector<char> bytes(length + 1);
napi_get_value_string_utf8(env, text, bytes.data(), bytes.size(), &length);
return MakeString(bytes.data(), length);
}
struct Context
{
uint8_t padding[24]{};
napi_env env;
napi_deferred deferred;
};
struct AsyncResult
{
uint8_t padding[16]{};
Context *context;
int32_t result;
int32_t alignment{};
QQString error;
QQString response;
};
extern "C" __attribute__((noinline)) void MockResolver(AsyncResult *result)
{
napi_throw_error(result->context->env, nullptr, "Resolver was not intercepted");
}
static volatile int64_t sendCalls = 0;
static volatile int64_t recvCalls = 0;
extern "C" __attribute__((noinline)) int64_t MockSend(void *self, void **packet)
{
sendCalls += 1;
return 101 + (self != nullptr) + (packet != nullptr);
}
extern "C" __attribute__((noinline)) int64_t MockRecv(void *self, void **packet, uint32_t marker)
{
recvCalls += 1;
return 201 + marker + (self != nullptr) + (packet != nullptr);
}
static napi_value Convert(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value input;
napi_get_cb_info(env, info, &argc, &input, nullptr, nullptr);
auto output = MockCoerce(env, input);
auto bytes = ReadString(output);
napi_value result;
napi_create_buffer_copy(env, bytes.size(), bytes.data(), nullptr, &result);
FreeString(output);
return result;
}
static napi_value Resolve(napi_env env, napi_callback_info info)
{
size_t argc = 3;
napi_value args[3];
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
Context context{};
context.env = env;
napi_value promise;
napi_create_promise(env, &context.deferred, &promise);
AsyncResult result{};
result.context = &context;
napi_get_value_int32(env, args[0], &result.result);
result.error = FromBuffer(env, args[1]);
result.response = FromBuffer(env, args[2]);
MockResolver(&result);
FreeString(result.error);
FreeString(result.response);
return promise;
}
struct ByteVector
{
uint8_t *begin;
uint8_t *end;
};
struct SendInner
{
QQString command;
uint64_t padding{};
ByteVector *payload;
};
struct SendPacket
{
SendInner *inner;
uint8_t padding[48]{};
QQString uin;
uint64_t alignment{};
int64_t sequence;
uint8_t tail[16]{};
};
struct RecvPacket
{
QQString uin;
int64_t sequence;
QQString command;
ByteVector *payload;
};
static_assert(offsetof(AsyncResult, error) == 32);
static_assert(offsetof(AsyncResult, response) == 56);
static_assert(offsetof(SendPacket, uin) == 56);
static_assert(offsetof(SendPacket, sequence) == 88);
static_assert(offsetof(RecvPacket, payload) == 56);
static napi_value Packet(napi_env env, napi_callback_info info)
{
size_t argc = 5;
napi_value args[5];
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
int32_t direction;
int64_t sequence;
napi_get_value_int32(env, args[0], &direction);
napi_get_value_int64(env, args[3], &sequence);
auto uin = FromBuffer(env, args[1]);
auto command = FromBuffer(env, args[2]);
void *payloadData;
size_t payloadLength;
napi_get_buffer_info(env, args[4], &payloadData, &payloadLength);
uint8_t emptyPayload = 0;
auto bytes = payloadLength ? static_cast<uint8_t *>(payloadData) : &emptyPayload;
ByteVector payload{bytes, bytes + payloadLength};
int64_t returnValue;
if (direction == 0)
{
SendInner inner{command, 0, &payload};
SendPacket packet{};
packet.inner = &inner;
packet.uin = uin;
packet.sequence = sequence;
void *pointer = &packet;
returnValue = MockSend(nullptr, &pointer);
command = inner.command;
}
else
{
RecvPacket packet{uin, sequence, command, &payload};
void *pointer = &packet;
returnValue = MockRecv(nullptr, &pointer, 7);
}
napi_value result;
napi_create_object(env, &result);
napi_value returned;
napi_create_int64(env, returnValue, &returned);
napi_set_named_property(env, result, "returned", returned);
auto commandBytes = ReadString(command);
napi_value outputCommand;
napi_create_buffer_copy(env, commandBytes.size(), commandBytes.data(), nullptr, &outputCommand);
napi_set_named_property(env, result, "command", outputCommand);
FreeString(uin);
FreeString(command);
return result;
}
static napi_value EmptyPackets(napi_env env, napi_callback_info info)
{
void *missing = nullptr;
MockSend(nullptr, nullptr);
MockSend(nullptr, &missing);
SendPacket send{};
void *sendPointer = &send;
MockSend(nullptr, &sendPointer);
SendInner inner{};
send.inner = &inner;
MockSend(nullptr, &sendPointer);
MockRecv(nullptr, nullptr, 0);
MockRecv(nullptr, &missing, 0);
RecvPacket recv{};
void *recvPointer = &recv;
MockRecv(nullptr, &recvPointer, 0);
napi_value result;
napi_create_int64(env, sendCalls + recvCalls, &result);
return result;
}
static napi_value Addresses(napi_env env, napi_callback_info info)
{
Dl_info image{};
dladdr(reinterpret_cast<void *>(MockCoerce), &image);
uintptr_t base = reinterpret_cast<uintptr_t>(image.dli_fbase);
napi_value result;
napi_create_object(env, &result);
const std::pair<const char *, uintptr_t> functions[] = {
{"coerce", reinterpret_cast<uintptr_t>(MockCoerce) - base},
{"resolver", reinterpret_cast<uintptr_t>(MockResolver) - base},
{"send", (reinterpret_cast<uintptr_t>(MockSend) - base) * 2},
{"recv", (reinterpret_cast<uintptr_t>(MockRecv) - base) * 2},
};
for (const auto &entry : functions)
{
std::ostringstream hex;
hex << std::hex << entry.second;
napi_value value;
napi_create_string_utf8(env, hex.str().c_str(), NAPI_AUTO_LENGTH, &value);
napi_set_named_property(env, result, entry.first, value);
}
return result;
}
static napi_value Init(napi_env env, napi_value exports)
{
const napi_property_descriptor properties[] = {
{"addresses", nullptr, Addresses, nullptr, nullptr, nullptr, napi_default, nullptr},
{"convert", nullptr, Convert, nullptr, nullptr, nullptr, napi_default, nullptr},
{"resolve", nullptr, Resolve, nullptr, nullptr, nullptr, napi_default, nullptr},
{"packet", nullptr, Packet, nullptr, nullptr, nullptr, napi_default, nullptr},
{"emptyPackets", nullptr, EmptyPackets, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
return exports;
}
NAPI_MODULE(wrapper, Init)
+75
View File
@@ -0,0 +1,75 @@
import json
import os
from pathlib import Path
import plistlib
import re
import shutil
import signal
import subprocess
import sys
import time
application = Path(sys.argv[1]).resolve()
distribution = Path(sys.argv[2]).resolve()
evidence = Path('qq-runtime-evidence')
evidence.mkdir(exist_ok=True)
signature = subprocess.run(['/usr/bin/codesign', '-d', '--entitlements', ':-', str(application)],
capture_output=True, check=True, timeout=20)
(evidence / 'entitlements.plist').write_bytes(signature.stdout)
(evidence / 'signature.txt').write_bytes(signature.stderr)
entitlements = plistlib.loads(signature.stdout)
print(json.dumps({'entitlements': entitlements}, ensure_ascii=False), flush=True)
documents = Path.home() / 'Library/Containers/com.tencent.qq/Data/Documents'
runtime = documents / 'napcat-runtime-audit'
runtime.mkdir(parents=True, exist_ok=True)
shutil.copytree(distribution, runtime / 'napcat', dirs_exist_ok=True)
bootstrap = runtime / 'loader.cjs'
bootstrap.write_text('''const path = require('node:path');
const { pathToFileURL } = require('node:url');
const addon = { exports: {} };
process.dlopen(addon, path.join(__dirname, 'napcat/native/ffmpeg', `ffmpegAddon.darwin.${process.arch}.node`));
console.log('QQ_NATIVE_ADDON_PROBE', Object.keys(addon.exports));
import(pathToFileURL(path.join(__dirname, 'napcat/napcat.mjs')).href);
''')
package_path = application / 'Contents/Resources/app/package.json'
package = json.loads(package_path.read_text())
assert package['version'] == '7.0.2-53644', package
package['main'] = os.path.relpath(bootstrap, package_path.parent)
package_path.write_text(json.dumps(package))
executable = application / 'Contents/MacOS/QQ'
raw_log = evidence / 'runtime.log'
started = time.monotonic()
with raw_log.open('w') as output:
process = subprocess.Popen([str(executable), '--no-sandbox'], cwd=runtime, start_new_session=True,
stdout=output, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 35
while process.poll() is None and time.monotonic() < deadline:
time.sleep(0.5)
premature_exit = process.poll()
finally:
if process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=5)
log = raw_log.read_text(errors='replace')
log = re.sub(r'(?i)(token[=:]\s*)[^\s]+', r'\1[redacted]', log)
raw_log.write_text(log)
checks = {
'remains_running': premature_exit is None,
'external_native_module': 'QQ_NATIVE_ADDON_PROBE' in log,
'napcat_started': 'NapCat.Core Version:' in log,
'packet_hook_initialized': '[PacketHandler] 初始化成功' in log,
'napi_module_loaded': '[Napi2NativeLoader] 加载成功' in log,
'ffmpeg_native_available': '使用 Native Addon 适配器' in log,
}
result = {'exit_code': premature_exit, 'seconds': time.monotonic() - started, 'checks': checks}
(evidence / 'result.json').write_text(json.dumps(result, indent=2))
print(log[-16000:], flush=True)
print(json.dumps(result, ensure_ascii=False), flush=True)
assert all(checks.values()), result
@@ -0,0 +1,96 @@
$ErrorActionPreference = 'Stop'
$auditRoot = Join-Path ([IO.Path]::GetTempPath()) 'napcat-windows-launcher-tests'
$sourceRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../../packages/napcat-shell-loader'))
New-Item -ItemType Directory -Path $auditRoot -Force | Out-Null
$compiledStub = Join-Path $auditRoot ('stub-' + [guid]::NewGuid().ToString('N') + '.exe')
& (Join-Path $env:WINDIR 'Microsoft.NET/Framework64/v4.0.30319/csc.exe') /nologo ("/out:" + $compiledStub) (Join-Path $PSScriptRoot 'windows-launcher-stub.cs')
if ($LASTEXITCODE -ne 0) { throw 'Failed to compile launcher fixture' }
$stubDirectory = Join-Path $auditRoot 'tools'
New-Item -ItemType Directory -Path $stubDirectory -Force | Out-Null
foreach ($stubName in @('reg.exe', 'net.exe', 'powershell.exe')) {
Copy-Item -LiteralPath $compiledStub -Destination (Join-Path $stubDirectory $stubName) -Force
}
$results = [Collections.Generic.List[object]]::new()
foreach ($launcher in @('launcher.bat', 'launcher-win10.bat', 'launcher-user.bat', 'launcher-win10-user.bat')) {
foreach ($pathKind in @('plain', 'space', 'special', 'unquoted', 'missing-registry', 'boot-error', 'elevation')) {
if ($pathKind -eq 'elevation' -and $launcher -like '*-user.bat') { continue }
$directoryName = switch ($pathKind) {
plain { 'plain' }
space { 'space path' }
special { "路径 & () ! # ' test" }
default { "路径 & () ! # ' $pathKind" }
}
$fixture = Join-Path $auditRoot ($launcher.Replace('.bat', '') + '\' + $directoryName)
New-Item -ItemType Directory -Path $fixture -Force | Out-Null
Copy-Item -LiteralPath (Join-Path $sourceRoot $launcher) -Destination $fixture -Force
Copy-Item -LiteralPath $compiledStub -Destination (Join-Path $fixture 'NapCatWinBootMain.exe') -Force
New-Item -ItemType File -Path (Join-Path $fixture 'QQ.exe') -Force | Out-Null
$output = Join-Path $fixture 'arguments.txt'
if (Test-Path -LiteralPath $output) { Remove-Item -LiteralPath $output }
$startInfo = [Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = $env:ComSpec
$startInfo.Arguments = '/d /s /c ""' + (Join-Path $fixture $launcher) + '" -q "123456" "argument with spaces" "literal!value""'
$startInfo.WorkingDirectory = $auditRoot
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
$startInfo.RedirectStandardInput = $true
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$startInfo.EnvironmentVariables['PATH'] = $stubDirectory + ';' + $env:PATH
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_UNINSTALL'] = if ($pathKind -eq 'missing-registry') { '' } elseif ($pathKind -eq 'unquoted') { Join-Path $fixture 'Uninstall.exe' } else { '"' + (Join-Path $fixture 'Uninstall.exe') + '"' }
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_NET_STATUS'] = if ($pathKind -eq 'elevation') { '1' } else { '0' }
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_BOOT_STATUS'] = if ($pathKind -eq 'boot-error') { '31' } else { '0' }
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_OUTPUT'] = $output
$process = [Diagnostics.Process]::Start($startInfo)
$stdout = $process.StandardOutput.ReadToEndAsync()
$stderr = $process.StandardError.ReadToEndAsync()
$process.StandardInput.WriteLine('')
$process.StandardInput.Close()
if (-not $process.WaitForExit(10000)) {
& taskkill.exe /PID $process.Id /T /F | Out-Null
throw "$launcher $pathKind timed out"
}
$expected = @((Join-Path $fixture 'QQ.exe'), (Join-Path $fixture 'NapCatWinBootHook.dll'), '-q', '123456', 'argument with spaces', 'literal!value')
if ($pathKind -eq 'missing-registry') { $expected = @() }
if ($pathKind -eq 'elevation') {
$terminal = if ($launcher -eq 'launcher.bat') { 'wt.exe' } else { 'powershell.exe' }
$expected = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $fixture 'launcher-elevate.ps1'), $terminal, (Join-Path $fixture $launcher), '-q', '123456', 'argument with spaces', 'literal!value')
}
$actual = @()
if (Test-Path -LiteralPath $output) {
$actual = @(Get-Content -LiteralPath $output -Encoding UTF8 | Select-Object -Skip 1 | ForEach-Object { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($_)) })
}
$passed = $actual.Count -eq $expected.Count
for ($argumentIndex = 0; $argumentIndex -lt $expected.Count -and $passed; $argumentIndex++) {
$passed = $actual[$argumentIndex] -ceq $expected[$argumentIndex]
}
$expectedExit = if ($pathKind -eq 'missing-registry') { 1 } elseif ($pathKind -eq 'boot-error') { 31 } else { 0 }
$passed = $passed -and $process.ExitCode -eq $expectedExit
$result = [PSCustomObject]@{ launcher=$launcher; path=$pathKind; passed=$passed; exit=$process.ExitCode; actual=$actual; stdout=$stdout.Result; stderr=$stderr.Result }
$results.Add($result)
$result | Select-Object launcher,path,passed,exit | ConvertTo-Json -Compress
}
}
function Start-Process {
param([string]$FilePath, [string]$ArgumentList, [string]$Verb)
$global:napcatAuditElevationRequest = @{ file=$FilePath; arguments=$ArgumentList; verb=$Verb }
}
foreach ($terminal in @('wt.exe', 'powershell.exe')) {
$testScript = "C:\路径 & () ! # '\launcher.bat"
$testArguments = @('-q', '123456', 'argument with spaces', 'literal!value', 'literal$()', 'quote"value')
& (Join-Path $sourceRoot 'launcher-elevate.ps1') $terminal $testScript @testArguments
$encodedCommand = ($global:napcatAuditElevationRequest.arguments -split ' ')[-1]
$command = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encodedCommand))
$parseTokens = $null
$parseErrors = $null
[Management.Automation.Language.Parser]::ParseInput($command, [ref]$parseTokens, [ref]$parseErrors) | Out-Null
$match = [regex]::Match($command, "FromBase64String\('([A-Za-z0-9+/=]+)'\)")
$payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($match.Groups[1].Value)) | ConvertFrom-Json
$passed = $parseErrors.Count -eq 0 -and $payload.script -ceq $testScript -and $global:napcatAuditElevationRequest.verb -eq 'RunAs'
$passed = $passed -and ($payload.arguments | ConvertTo-Json -Compress) -ceq ($testArguments | ConvertTo-Json -Compress)
$result = [PSCustomObject]@{ launcher='launcher-elevate.ps1'; path=$terminal; passed=$passed; exit=0 }
$results.Add($result)
$result | ConvertTo-Json -Compress
}
$results | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $auditRoot 'results.json') -Encoding UTF8
if ($results.Where({ -not $_.passed }).Count) { exit 1 }
@@ -0,0 +1,24 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
public class NapCatLauncherAudit {
public static int Main(string[] arguments) {
string name = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);
if (name == "reg") {
string uninstall = Environment.GetEnvironmentVariable("NAPCAT_AUDIT_UNINSTALL");
if (String.IsNullOrEmpty(uninstall)) return 1;
Console.OutputEncoding = new UTF8Encoding(false);
Console.WriteLine(" UninstallString REG_SZ " + uninstall);
return 0;
}
if (name == "net") return Int32.Parse(Environment.GetEnvironmentVariable("NAPCAT_AUDIT_NET_STATUS"));
string output = Environment.GetEnvironmentVariable("NAPCAT_AUDIT_OUTPUT");
using (StreamWriter writer = new StreamWriter(output, false, new UTF8Encoding(false))) {
writer.WriteLine(name);
foreach (string argument in arguments) writer.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(argument)));
}
return Int32.Parse(Environment.GetEnvironmentVariable("NAPCAT_AUDIT_BOOT_STATUS") ?? "0");
}
}
@@ -0,0 +1,3 @@
cmake_minimum_required(VERSION 3.20)
project(NapCatWindowsLoaderTest LANGUAGES CXX)
add_executable(windows-loader-test probe.cpp)
+96
View File
@@ -0,0 +1,96 @@
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using QueryByName = BOOL(WINAPI *)(PCWSTR, FILE_INFO_BY_NAME_CLASS, PVOID, ULONG);
int wmain(int argumentCount, wchar_t **arguments)
{
if (argumentCount != 3)
return 2;
const wchar_t *providers[] = {L"kernel32.dll", L"kernelbase.dll", L"api-ms-win-core-file-l2-1-4.dll"};
HMODULE providerModules[3]{};
QueryByName nativeQueries[3]{};
unsigned char nativeCode[3][12]{};
unsigned char nativeInfo[3][4][1024]{};
BOOL nativeResults[3][4]{};
DWORD nativeErrors[3][4]{};
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
providerModules[providerIndex] = LoadLibraryW(providers[providerIndex]);
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
if (!query)
return 3;
nativeQueries[providerIndex] = query;
std::memcpy(nativeCode[providerIndex], reinterpret_cast<void *>(query), sizeof(nativeCode[providerIndex]));
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
SetLastError(ERROR_SUCCESS);
nativeResults[providerIndex][infoClass] = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), nativeInfo[providerIndex][infoClass], sizeof(nativeInfo[providerIndex][infoClass]));
nativeErrors[providerIndex][infoClass] = GetLastError();
}
}
FILE_STAT_BASIC_INFORMATION expected{};
if (!nativeQueries[0](arguments[2], FileStatBasicByNameInfo, &expected, sizeof(expected)))
return 4;
if (_wputenv_s(L"NAPCAT_LOAD_PATH", arguments[2]) || _wputenv_s(L"NAPCAT_PATCH_PACKAGE", arguments[2]))
return 5;
if (!LoadLibraryW(arguments[1]))
{
std::printf("LoadLibrary failed: %lu\n", GetLastError());
return 6;
}
const std::wstring missingRoot = L"C:\\napcat-loader-test-" + std::to_wstring(GetCurrentProcessId());
const std::wstring loaderPath = missingRoot + L"\\loadNapCat.js";
const std::wstring packagePath = missingRoot + L"\\resources\\app\\package.json";
const std::wstring unrelatedPath = missingRoot + L"\\unrelated.txt";
const wchar_t *redirectedPaths[] = {loaderPath.c_str(), packagePath.c_str()};
int failures = 0;
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
bool preserved = std::memcmp(nativeCode[providerIndex], reinterpret_cast<void *>(nativeQueries[providerIndex]), sizeof(nativeCode[providerIndex])) == 0;
std::wprintf(L"%ls native code preserved: %ls\n", providers[providerIndex], preserved ? L"PASS" : L"FAIL");
failures += !preserved;
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
unsigned char actual[1024]{};
SetLastError(ERROR_SUCCESS);
BOOL result = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), actual, sizeof(actual));
DWORD error = GetLastError();
bool passed = result == nativeResults[providerIndex][infoClass] &&
(result ? std::memcmp(actual, nativeInfo[providerIndex][infoClass], sizeof(actual)) == 0 : error == nativeErrors[providerIndex][infoClass]);
std::wprintf(L"%ls information class %d native parity: %ls\n", providers[providerIndex], infoClass, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
for (const auto *redirectedPath : redirectedPaths)
{
FILE_STAT_BASIC_INFORMATION actual{};
BOOL result = query(redirectedPath, FileStatBasicByNameInfo, &actual, sizeof(actual));
bool passed = result && actual.EndOfFile.QuadPart == expected.EndOfFile.QuadPart &&
actual.FileId.QuadPart == expected.FileId.QuadPart && actual.FileAttributes == expected.FileAttributes;
std::wprintf(L"%ls redirect %ls: %ls\n", providers[providerIndex], redirectedPath, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION missing{};
SetLastError(ERROR_SUCCESS);
BOOL nativeResult = nativeQueries[providerIndex](unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
DWORD nativeError = GetLastError();
SetLastError(ERROR_SUCCESS);
BOOL result = query(unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
bool passed = !result && result == nativeResult && GetLastError() == nativeError;
std::wprintf(L"%ls unrelated missing file: %ls\n", providers[providerIndex], passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION direct{};
BOOL result = GetFileInformationByName(loaderPath.c_str(), FileStatBasicByNameInfo, &direct, sizeof(direct));
bool passed = result && direct.FileId.QuadPart == expected.FileId.QuadPart && direct.EndOfFile.QuadPart == expected.EndOfFile.QuadPart;
std::printf("static import redirection: %s\n", passed ? "PASS" : "FAIL");
failures += !passed;
return failures ? 1 : 0;
}
+31 -4
View File
@@ -9,6 +9,26 @@ on:
permissions: write-all
jobs:
windows-loader-test:
name: Windows Loader Test
needs: build
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell
path: shell-dist
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/shell-dist/NapCatWinBootHook.dll" "$pwd/shell-dist/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
typecheck-and-test:
name: Type Check & Test
runs-on: ubuntu-latest
@@ -17,14 +37,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 +73,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 +96,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 }}
+187 -178
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,215 +108,200 @@ 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 }} # 构建版本号
permissions:
contents: read
actions: write
steps:
# 【安全】先从 base 分支 checkout 构建脚本
# 这样即使 PR 中修改了脚本,也不会被执行
- name: Checkout scripts from base
- name: Checkout scripts
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
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 获取最新 release tag 并生成版本号
- 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: |
# 获取最近的 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="${{ inputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
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}"
# 执行构建,使用 base 分支的脚本处理 workspace 中的代码
- name: Build
id: build
working-directory: workspace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ''
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
continue-on-error: true # 允许失败,后续更新评论时处理
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 # 保留 5 天(仓库上限)
retention-days: 5
# ---------------------------------------------------------------------------
# Job 4: 构建 Shell 包
# ---------------------------------------------------------------------------
# 执行 napcat-shell 的构建流程(与 Framework 并行执行)
# ---------------------------------------------------------------------------
build-shell:
needs: [check-build, update-comment-building]
if: needs.check-build.outputs.should_build == 'true'
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
status: ${{ steps.build.outcome }} # 构建结果:success/failure
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
version: ${{ steps.version.outputs.version }} # 构建版本号
status: ${{ steps.build.outcome }}
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
persist-credentials: false
# 将 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 }}
repository: ${{ inputs.pr_head_repo }}
ref: ${{ inputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
# 获取最新 release tag 并生成版本号
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
run_install: false
- 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="${{ inputs.pr_sha }}"
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
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: ${{ secrets.GITHUB_TOKEN }}
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 # 保留 5 天(仓库上限)
retention-days: 5
# ---------------------------------------------------------------------------
# Job 5: 更新评论为构建结果
# ---------------------------------------------------------------------------
# 汇总所有构建结果,更新 PR 评论显示最终状态
# 使用 always() 确保即使构建失败/取消也会执行
# ---------------------------------------------------------------------------
update-comment-result:
needs: [check-build, update-comment-building, build-framework, build-shell, publish-pr-release]
if: always() && needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: 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: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.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 }}
# PR Release 信息(用于在评论中显示安装命令)
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
# ---------------------------------------------------------------------------
# Job 6: 发布 PR 构建产物到 napcat-pr-release 仓库
# ---------------------------------------------------------------------------
# 将所有构建产物打包 + 从 NapCat-Installer 拉取并修改安装脚本,
# 一起发布为 GitHub Release(公开可下载,无需登录)。
# Release 会由 napcat-pr-release 仓库的定时任务在 24h 后自动清理。
# 可信后处理:只下载/打包/发布 artifact,不执行 artifact 中的代码
# ---------------------------------------------------------------------------
publish-pr-release:
needs: [check-build, build-framework, build-shell]
if: always() && needs.check-build.outputs.should_build == 'true' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
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 }} # 'success' | 'failure' | 'skipped'
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
@@ -354,8 +327,8 @@ jobs:
continue-on-error: true
env:
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
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: |
@@ -365,7 +338,6 @@ jobs:
fi
node --experimental-strip-types .github/scripts/pr-publish-release.ts
# 将修改后的安装脚本也上传为 CI artifact(自动过期)
- name: Upload install script as artifact
if: steps.publish.outcome == 'success'
uses: actions/upload-artifact@v6
@@ -375,22 +347,59 @@ jobs:
retention-days: 5
if-no-files-found: ignore
# ---------------------------------------------------------------------------
# Job 7: 触发 NapCat-Docker 仓库的 PR 测试镜像构建
# ---------------------------------------------------------------------------
# 仅当 Shell 构建成功、且 Release 已发布时触发。
# Docker 构建从公开 Release 下载产物,无需跨仓 artifact PAT。
# ---------------------------------------------------------------------------
trigger-docker:
needs: [check-build, build-shell, publish-pr-release]
if: needs.check-build.outputs.should_build == 'true' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
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 || '' }}
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
@@ -402,9 +411,9 @@ jobs:
env:
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
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_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: |
+56
View File
@@ -0,0 +1,56 @@
name: macOS native compatibility
on:
push:
paths:
- packages/napcat-native/**
- .github/tests/macos-native/**
- .github/workflows/macos-native.yml
pull_request:
paths:
- packages/napcat-native/**
- .github/tests/macos-native/**
- .github/workflows/macos-native.yml
workflow_dispatch:
permissions:
contents: read
jobs:
native:
runs-on: ${{ matrix.runner }}
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15
arch: arm64
- runner: macos-15-intel
arch: x64
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
architecture: ${{ matrix.arch }}
- name: Build QQ ABI mock
working-directory: .github/tests/macos-native
run: |
npm install --prefix headers --ignore-scripts --no-package-lock node-api-headers@1.6.0
clang++ -std=c++17 -O0 -g -bundle -undefined dynamic_lookup -I headers/node_modules/node-api-headers/include wrapper.cpp -o wrapper.node
codesign --force --sign - wrapper.node
- name: Exercise native packet hooks
run: node --test .github/tests/macos-native/hooks.test.cjs
- uses: actions/checkout@v4
with:
repository: NapNeko/ffmpegAddon
ref: 7a68e99b52921a47f7f6d99864ed6217a0a90e7d
path: ffmpeg-native-tests
- name: Verify packaged FFmpeg
working-directory: ffmpeg-native-tests
env:
FFMPEG_ADDON_PATH: ${{ github.workspace }}/packages/napcat-native/ffmpeg/ffmpegAddon.darwin.${{ matrix.arch }}.node
run: |
npm ci --ignore-scripts
npm test
+65
View File
@@ -0,0 +1,65 @@
name: macOS QQ runtime
on:
push:
paths:
- .github/tests/macos-qq/**
- .github/workflows/macos-qq-runtime.yml
workflow_dispatch:
inputs:
napcat_version:
description: NapCat release to run without login
type: string
default: v4.18.36
permissions:
contents: read
jobs:
runtime:
runs-on: ${{ matrix.runner }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15
arch: arm64
- runner: macos-15-intel
arch: x64
env:
NAPCAT_VERSION: ${{ inputs.napcat_version || 'v4.18.36' }}
QQ_SHA256: d270b78f0b210532637076532a883dc8659851b6daa92451983985ab9f3216f0
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
id: qq-cache
with:
path: QQ.dmg
key: macos-qq-d270b78f0b210532
- name: Download verified QQ and NapCat
env:
GH_TOKEN: ${{ github.token }}
run: |
if [ ! -f QQ.dmg ]; then
curl -fLsS --connect-timeout 20 --max-time 300 \
https://github.com/A-Randomm-User/macOS-save/releases/download/qq/QQ_v7.0.2.53644.dmg -o QQ.dmg
fi
echo "$QQ_SHA256 QQ.dmg" | shasum -a 256 -c -
gh release download "$NAPCAT_VERSION" --repo NapNeko/NapCatQQ --pattern NapCat.Shell.zip
mkdir NapCat
unzip -q NapCat.Shell.zip -d NapCat
- name: Extract original signed QQ
run: |
mkdir qq-volume
hdiutil attach QQ.dmg -readonly -nobrowse -mountpoint "$PWD/qq-volume"
ditto qq-volume/QQ.app QQ.app
hdiutil detach "$PWD/qq-volume"
codesign --verify --deep --strict QQ.app
- name: Verify real QQ native loading and hooks
run: python3 .github/tests/macos-qq/runtime.py "$PWD/QQ.app" "$PWD/NapCat"
- uses: actions/upload-artifact@v4
if: always()
with:
name: macos-qq-runtime-${{ matrix.arch }}
path: qq-runtime-evidence
+5 -3
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.36/beta/9ee04bef/linuxqq_3.2.34-53644_x86_64.AppImage'
QQ_URL_ARM64: 'https://qqdl.gtimg.cn/qqfile/QQNT/9.9.36/beta/9ee04bef/linuxqq_3.2.34-53644_arm64.AppImage'
jobs:
get-version:
@@ -86,17 +86,19 @@ jobs:
git push
shell-docker:
needs: get-version
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
-d '{"ref":"main"}'
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\"}}"
framework-docker:
runs-on: ubuntu-latest
+76 -15
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:
@@ -42,8 +47,8 @@ jobs:
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ inputs.version }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
@@ -61,6 +66,11 @@ jobs:
assemble-windows-node:
needs: build
runs-on: ubuntu-latest
env:
# QQ 9.9.31.49738; SHA256 matches the microsoft/winget-pkgs installer manifest.
QQ_URL: https://github.com/Rodert/qq-versions/releases/download/qq-packages-20260528-3e8913a2/QQ_9.9.31_260528_x64_01.exe
QQ_SHA256: 0beb5cb4ff776cba822caa0abadbd53f5892f12628a86dabea1b372c82c086bc
NODE_VERSION: '22.11.0'
steps:
- uses: actions/checkout@v5
with:
@@ -76,12 +86,18 @@ jobs:
sudo apt update
sudo apt install -y aria2 unzip zip p7zip-full curl jq
- name: Generate download cache key
id: download-cache-key
run: |
DOWNLOAD_HASH=$(printf '%s\n' "$QQ_URL" "$QQ_SHA256" "$NODE_VERSION" | sha256sum | cut -d ' ' -f 1)
echo "key=napcat-downloads-v2-$DOWNLOAD_HASH" >> "$GITHUB_OUTPUT"
- name: Cache QQ and Node.js downloads
id: cache-downloads
uses: actions/cache@v4
with:
path: /tmp/napcat-downloads
key: napcat-downloads-qq9.9.27.45627-node22.11.0
key: ${{ steps.download-cache-key.outputs.key }}
- name: Download QQ and Node.js
if: steps.cache-downloads.outputs.cache-hit != 'true'
@@ -90,15 +106,20 @@ 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"
echo "Downloading QQ installer..."
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
# Retry download errors, including HTTP 404 responses.
curl --fail --location --retry 5 --retry-all-errors --retry-delay 5 \
--connect-timeout 30 --max-time 600 --user-agent "Mozilla/5.0" \
--output "QQ_x64.exe" "$QQ_URL"
NODE_VER="22.11.0"
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
echo "Downloading Node.js $NODE_VER..."
NODE_URL="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-win-x64.zip"
echo "Downloading Node.js $NODE_VERSION..."
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
- name: Verify QQ installer
run: |
echo "$QQ_SHA256 /tmp/napcat-downloads/QQ_x64.exe" | sha256sum --check --strict -
- name: Assemble NapCat.Shell.Windows.Node.zip
run: |
set -euo pipefail
@@ -133,9 +154,14 @@ jobs:
# -----------------------------
# 5) 拷贝 QQ 文件到 NapCat.Shell.Windows.Node
# -----------------------------
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "crypto.dll" "ssl.dll" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
for name in "${QQ_TARGETS[@]}"; do
find "$QQ_EXTRACT" -iname "$name" -exec cp -a {} "$OUT_DIR" \; || true
source_file=$(find "$QQ_EXTRACT" -type f -iname "$name" -print -quit)
if [ -z "$source_file" ]; then
echo "Missing required QQ file: $name" >&2
exit 1
fi
cp -a "$source_file" "$OUT_DIR/"
done
# -----------------------------
@@ -155,8 +181,7 @@ jobs:
# -----------------------------
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
# -----------------------------
NODE_VER="22.11.0"
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
cp -a "$NODE_EXTRACT/node-v$NODE_VERSION-win-x64/node.exe" "$OUT_DIR/" || true
- name: Upload Artifact
uses: actions/upload-artifact@v6
@@ -164,8 +189,39 @@ jobs:
name: NapCat.Shell.Windows.Node
path: NapCat.Shell.Windows.Node
validate-windows-node:
needs: assemble-windows-node
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell.Windows.Node
path: windows-node
- name: Verify bundled Node and QQ native dependencies
shell: pwsh
working-directory: windows-node
run: |
& .\node.exe --check .\index.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\node.exe -e "const wrapper = require('./wrapper.node'); if (!wrapper.NodeQQNTWrapperUtil) throw new Error('Missing NodeQQNTWrapperUtil'); console.log('wrapper.node native-load PASS'); process.exit(0);"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/windows-node/napcat/NapCatWinBootHook.dll" "$pwd/windows-node/napcat/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
release-napcat:
needs: [build, assemble-windows-node]
needs: [build, assemble-windows-node, validate-windows-node]
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -414,12 +470,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 \
+32
View File
@@ -0,0 +1,32 @@
name: Windows launcher
on:
push:
paths:
- packages/napcat-shell-loader/launcher*
- .github/tests/windows-launcher/**
- .github/workflows/windows-launcher.yml
pull_request:
paths:
- packages/napcat-shell-loader/launcher*
- .github/tests/windows-launcher/**
- .github/workflows/windows-launcher.yml
workflow_dispatch:
permissions:
contents: read
jobs:
launchers:
runs-on: windows-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- name: Check paths, registry, arguments and elevation
shell: pwsh
run: ./.github/tests/windows-launcher/validation.ps1
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-launcher-results
path: ${{ runner.temp }}/napcat-windows-launcher-tests/results.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,
+16 -4
View File
@@ -1,6 +1,7 @@
import { GeneralCallResult, InstanceContext, NapCatCore } from '@/napcat-core';
import {
createFlashTransferResult,
DEFAULT_FLASH_VALIDITY_SECONDS,
FileListResponse,
FlashFileSetInfo,
SendStatus,
@@ -22,8 +23,9 @@ export class NTQQFlashApi {
* @param fileListToUpload 上传文件绝对路径的列表,可以是文件夹!!
* @param thumbnailPath
* @param filesetName
* @param validitySeconds 文件集有效期(秒),默认 1209600(14 天),可选 90 天 / 180 天,必须传否则新版内核段错误
*/
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string): Promise<GeneralCallResult & {
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string, validitySeconds: number = DEFAULT_FLASH_VALIDITY_SECONDS): Promise<GeneralCallResult & {
createFlashTransferResult: createFlashTransferResult;
seq: number;
}> {
@@ -33,14 +35,17 @@ export class NTQQFlashApi {
const selfInfo = this.core.selfInfo;
const fileUploadArg = {
screen: 1, // 1
scene: 1, // 1
name: filesetName,
uploaders: [{
uin: selfInfo.uin,
nickname: selfInfo.nick,
uid: selfInfo.uid,
sendEntrance: '',
nickname: selfInfo.nick,
}],
permission: {
code: 0,
},
coverPath: thumbnailPath,
paths: fileListToUpload,
excludePaths: [],
@@ -56,8 +61,15 @@ export class NTQQFlashApi {
uploadSceneType: UploadSceneType.KUPLOADSCENEAIOFILESELECTOR, // 不知道怎么枚举 先硬编码吧 (PC QQ 10)
detectPrivacyInfoResult: {
exists: false,
allDetectResults: new Map(),
allDetectResults: {},
},
announcement: {
announcementSegments: [],
modifyTime: '',
avatarUrl: '',
},
albumFilePathList: [],
validitySeconds,
};
const uploadResult = await flashService.createFlashTransferUploadTask(timestamp, fileUploadArg);
+110 -5
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 {
@@ -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;
@@ -243,6 +297,9 @@ export class NTQQGroupApi {
const updateCache = async () => {
try {
const members = await this.getGroupMemberAll(groupCode, true);
if (!members?.result?.infos) {
throw new Error(`errCode: ${members?.errCode}, errMsg: ${members?.errMsg}`);
}
this.groupMemberCache.set(groupCode, members.result.infos);
} catch (e) {
this.context.logger.logError(`刷新群成员缓存失败, 群号: ${groupCode}, 错误: ${e}`);
@@ -272,31 +329,57 @@ export class NTQQGroupApi {
// 获取群成员缓存
let members = this.groupMemberCache.get(groupCodeStr);
const cached = !!members;
if (!members) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
}
// 刚入的群可能拉不到成员列表,这时 members 为空,不能直接抛错,否则整条群消息都上报不出去
const getMember = () => {
if (!members) {
return undefined;
}
if (isNumeric(memberUinOrUidStr)) {
return Array.from(members!.values()).find(member => member.uin === memberUinOrUidStr);
return Array.from(members.values()).find(member => member.uin === memberUinOrUidStr);
} else {
return members!.get(memberUinOrUidStr);
return members.get(memberUinOrUidStr);
}
};
let member = getMember();
// 如果缓存中不存在该成员,尝试刷新缓存
if (!member) {
// 缓存里没有该成员(比如新入群),刷新一次;上面刚刷新过就不再重复拉取
if (!member && cached) {
members = (await this.refreshGroupMemberCache(groupCodeStr, true));
member = getMember();
}
return member;
}
// 从已缓存的群成员里按 QQ 号找 uid,供 uin 转 uid 兜底
getUidFromMemberCache (uin: string) {
for (const members of this.groupMemberCache.values()) {
for (const [uid, member] of members) {
if (member.uin === uin) {
return uid;
}
}
}
return undefined;
}
async getGroupRecommendContactArkJson (groupCode: string) {
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 +513,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',
@@ -461,6 +562,10 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().quitGroup(groupCode);
}
async destroyGroup (groupCode: string) {
return this.context.session.getGroupService().destroyGroup(groupCode);
}
async kickMember (groupCode: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
return this.context.session.getGroupService().kickMember(groupCode, kickUids, refuseForever, kickReason);
}
+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;
+1
View File
@@ -198,6 +198,7 @@ export class NTQQUserApi {
.add(() => this.context.session.getUixConvertService().getUid([uin]).then((data) => data.uidInfo.get(uin)))
.add(() => this.context.session.getProfileService().getUidByUin('FriendsServiceImpl', [uin]).get(uin))
.add(() => this.context.session.getGroupService().getUidByUins([uin]).then((data) => data.uids.get(uin)))
.add(() => this.core.apis.GroupApi.getUidFromMemberCache(uin))
.add(() => this.getUserDetailInfoByUin(uin).then((data) => data.detail.uid));
const uid = await fallback.run().catch(() => '');
+368 -36
View File
@@ -8,11 +8,25 @@ import {
WebHonorType, NapCatCore,
} from '@/napcat-core/index';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { basename } from 'node:path';
import { qunAlbumControl } from '../data/webapi';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { open, unlink, writeFile, type FileHandle } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
import { basename, join } from 'node:path';
import { qunAlbumControl, qunAlbumVideoControl, qunAlbumVideoCoverControl, QunAlbumBatch, nextQunAlbumBatchId } from '../data/webapi';
import { createAlbumCommentRequest, createAlbumFeedPublish, createAlbumMediaFeed } from '../data/album';
import { FFmpegService } from '../helper/ffmpeg/ffmpeg';
import { defaultVideoThumbB64 } from '../helper/ffmpeg/video';
import {
buildQzoneDeleteBody,
buildQzonePublishBody,
buildQzoneUploadImageBody,
parseQzoneDeleteResponse,
parseQzonePublishResponse,
parseQzoneUploadImageResponseText,
toQzoneRichval,
QzoneDeleteResponse,
QzonePublishResponse,
} from '../data/qzone';
export interface SetNoticeRetSuccess {
ec: number;
em: string;
@@ -24,6 +38,34 @@ export interface SetNoticeRetSuccess {
srv_code: number;
}
// 群相册分片上传的并发数
const QUN_ALBUM_SLICE_CONCURRENCY = 8;
// 服务端没给分片大小时的下限,以及防止异常值的上限
const QUN_ALBUM_SLICE_MIN = 16384;
const QUN_ALBUM_SLICE_MAX = 4 * 1024 * 1024;
// 流式计算文件摘要,避免为了算 MD5/SHA1 把整个文件读进内存(视频可能有几十上百 MB)
function hashFile (path: string, algorithm: 'md5' | 'sha1'): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash(algorithm);
createReadStream(path)
.on('data', chunk => hash.update(chunk))
.on('end', () => resolve(hash.digest('hex')))
.on('error', reject);
});
}
// 按需读取单个分片:并发上传时的内存占用只有「并发数 × 分片大小」
async function readSlice (handle: FileHandle, offset: number, length: number): Promise<Buffer> {
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, offset);
// 读不满说明文件在上传过程中被改短了,继续传只会传上去一段补零的数据
if (bytesRead !== length) {
throw new Error(`读取分片失败: offset=${offset} 预期 ${length} 字节,实际 ${bytesRead} 字节`);
}
return buffer;
}
export class NTQQWebApi {
context: InstanceContext;
core: NapCatCore;
@@ -371,9 +413,11 @@ export class NTQQWebApi {
return response.data.album;
}
async createQunAlbumSession (gc: string, sAlbumID: string, sAlbumName: string, path: string, skey: string, pskey: string, img_md5: string, uin: string) {
const img = readFileSync(path);
const img_size = img.length;
async createQunAlbumSession (
gc: string, sAlbumID: string, sAlbumName: string, path: string,
skey: string, pskey: string, img_md5: string, uin: string, batch?: QunAlbumBatch
) {
const img_size = statSync(path).size;
const img_name = basename(path);
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
@@ -386,42 +430,76 @@ export class NTQQWebApi {
img_name,
sAlbumName,
sAlbumID,
// 同批多图共用 batchId,并按「第几张 / 共几张」上报,相册里才会合并成同一条
batchId: batch?.batchId,
batchIndex: batch?.index,
photo_num: batch?.count,
batch_num: batch?.count,
});
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${img_md5}?g_tk=${GTK}`;
const post = await RequestUtil.HttpGetJson<{ data: { session: string; }, ret: number, msg: string; }>(api, 'POST', body, {
const post = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(api, 'POST', body, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
async uploadQunAlbumSlice (path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number) {
// 服务端会在会话响应里给出建议的分片大小;取不到或异常时退回 16384。
private resolveQunAlbumSliceSize (raw: unknown) {
const value = Number(raw);
if (!Number.isFinite(value) || value < QUN_ALBUM_SLICE_MIN) return QUN_ALBUM_SLICE_MIN;
return Math.min(value, QUN_ALBUM_SLICE_MAX);
}
async uploadQunAlbumSlice (
path: string, session: string, skey: string, pskey: string, uin: string, slice_size: number,
options: { appid?: string, cmd?: string; } = {}
) {
const appid = options.appid ?? 'qun';
const cmd = options.cmd ?? 'FileUpload';
const img_size = statSync(path).size;
let seq = 0;
let offset = 0;
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const stream = createReadStream(path, { highWaterMark: slice_size });
// 只记分片位置,不预先读内容;再并发上传(串行上传在几 MB 的图上要几十秒)
const slices: { seq: number, offset: number, end: number; }[] = [];
let seq = 0;
let offset = 0;
while (offset < img_size) {
const end = Math.min(offset + slice_size, img_size);
slices.push({ seq, offset, end });
offset = end;
seq++;
}
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
// 视频分片响应里会带 sVid,封面二段上传要靠它把封面挂到视频上
let sVid: string | undefined;
const handle = await open(path, 'r');
const uploadSlice = async (slice: { seq: number, offset: number, end: number; }) => {
const chunk = await readSlice(handle, slice.offset, slice.end - slice.offset);
const form = new FormData();
form.append('uin', uin);
form.append('appid', 'qun');
form.append('appid', appid);
form.append('session', session);
form.append('offset', offset.toString());
form.append('offset', slice.offset.toString());
form.append('data', new Blob([chunk], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('seq', slice.seq.toString());
form.append('end', slice.end.toString());
form.append('cmd', cmd);
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${GTK}`;
// 分片路径必须与 cmd 一致:视频走 /sliceUpload/FileUploadVideo,
// 否则服务端按图片处理,分片会「成功」但响应里没有 sVid
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/${cmd}?seq=${slice.seq}&retry=0&offset=${slice.offset}&end=${slice.end}&total=${img_size}&type=form&g_tk=${GTK}`;
const response = await fetch(api, {
method: 'POST',
headers: {
@@ -434,24 +512,153 @@ export class NTQQWebApi {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string; }; if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
const post = await response.json() as { ret: number, msg: string, data?: { biz?: { sVid?: string; }; }; };
if (post.ret !== 0) {
throw new Error(`分片 ${slice.seq} 上传失败: ${post.msg}`);
}
offset += chunk.length;
seq++;
if (!sVid && typeof post.data?.biz?.sVid === 'string' && post.data.biz.sVid) {
sVid = post.data.biz.sVid;
}
};
try {
// 最后一片要等前面的全部传完再发:服务端收到最后一片就认为文件传完了,
// 并发时它可能比前面的分片先到
const lastSlice = slices.pop();
let next = 0;
let failure: { error: unknown; } | undefined;
// 固定数量的 worker 各自领下一片,慢的分片不会拖住整批
const worker = async () => {
while (!failure) {
const slice = slices[next++];
if (!slice) break;
try {
await uploadSlice(slice);
} catch (error) {
if (!failure) failure = { error };
}
}
};
await Promise.all(Array.from({ length: Math.min(QUN_ALBUM_SLICE_CONCURRENCY, slices.length) }, worker));
if (failure) throw failure.error;
if (lastSlice) await uploadSlice(lastSlice);
} finally {
await handle.close();
}
return { success: true, message: '上传完成' };
return { success: true, message: '上传完成', sVid };
}
// 多张图片一次上传:共用同一个 batchId,相册里显示为同一条
async uploadImagesToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, paths: string[]) {
if (!paths.length) throw new Error('上传列表为空');
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 batchId = nextQunAlbumBatchId();
const count = paths.length.toString();
for (const [index, path] of paths.entries()) {
const img_md5 = await hashFile(path, 'md5');
const post = await this.createQunAlbumSession(
gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin,
{ batchId, count, index: index.toString() }
);
if (!post.data?.session) throw new Error(`创建群相册会话失败: ${post.msg || post.ret}`);
await this.uploadQunAlbumSlice(path, post.data.session, skey, pskey, uin, this.resolveQunAlbumSliceSize(post.data.slice_size));
}
}
async uploadImageToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
await this.uploadImagesToQunAlbum(gc, sAlbumID, sAlbumName, [path]);
}
/**
* 上传视频到群相册。
*
* 分三步:
* 1. 建视频会话:appid=video_qun / cmd=FileUploadVideo / SHA1 校验,此时不带相册
* 2. 分片上传视频,从分片响应里拿 sVid
* 3. 按图片上传封面并用 vid 关联视频,相册和批次号在这一步带上,视频随封面进相册
*/
async uploadVideoToQunAlbum (gc: string, sAlbumID: string, sAlbumName: string, path: string) {
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 img_md5 = createHash('md5').update(readFileSync(path)).digest('hex');
const uin = this.core.selfInfo.uin || '10001';
const session = (await this.createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin)).data.session;
if (!session) throw new Error('创建群相册会话失败');
await this.uploadQunAlbumSlice(path, session, skey, pskey, uin, 16384);
const GTK = this.getBknFromSKey(skey);
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const video_sha1 = await hashFile(path, 'sha1');
// 时长:ffmpeg 不可用时上报 0
let playTime = 0;
try {
playTime = Math.max(0, Math.round(await FFmpegService.getDuration(path)));
} catch (e) {
this.context.logger.logWarn('获取视频时长失败,iPlayTime 上报 0', e);
}
// 1) 视频主体(不带相册,只传成素材)
const videoSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${video_sha1}?g_tk=${GTK}`, 'POST', qunAlbumVideoControl({
uin,
group_id: gc,
pskey,
video_sha1,
video_size: statSync(path).size,
play_time: playTime,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!videoSession.data?.session) throw new Error(`创建群相册视频会话失败: ${videoSession.msg || videoSession.ret}`);
const uploaded = await this.uploadQunAlbumSlice(path, videoSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(videoSession.data.slice_size), { appid: 'video_qun', cmd: 'FileUploadVideo' });
if (!uploaded.sVid) throw new Error('视频上传完成但未取得 sVid,无法挂进相册');
// 2) 封面:抽首帧,失败(含 ffmpeg 不可用)回落内置默认封面
// 用 .png:Native Addon 路径产出的就是 png(日志里可见 Detected format: png),
// 而命令行路径会按扩展名编码,两条路都能得到真正的 PNG
const coverPath = join(this.core.NapCatTempPath, `${randomUUID()}.png`);
try {
try {
await FFmpegService.extractThumbnail(path, coverPath);
} catch (e) {
this.context.logger.logWarn('提取视频封面失败,使用默认封面', e);
await writeFile(coverPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
// 3) 封面二段上传:这一步才带相册和批次号,视频靠它进相册
const cover_md5 = await hashFile(coverPath, 'md5');
const coverSession = await RequestUtil.HttpGetJson<{
data: { session: string; slice_size?: number | string; },
ret: number,
msg: string;
}>(`https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${cover_md5}?g_tk=${GTK}`, 'POST', qunAlbumVideoCoverControl({
uin,
group_id: gc,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size: statSync(coverPath).size,
vid: uploaded.sVid,
}), {
Cookie: cookie,
'Content-Type': 'application/json',
});
if (!coverSession.data?.session) throw new Error(`创建群相册视频封面会话失败: ${coverSession.msg || coverSession.ret}`);
await this.uploadQunAlbumSlice(coverPath, coverSession.data.session, skey, pskey, uin,
this.resolveQunAlbumSliceSize(coverSession.data.slice_size));
} finally {
if (existsSync(coverPath)) {
await unlink(coverPath);
}
}
}
async getAlbumMediaListByNTQQ (gc: string, albumId: string, attach_info: string = '') {
@@ -507,20 +714,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,
+12 -2
View File
@@ -214,15 +214,19 @@ export enum UploadSceneType {
KUPLOADSCENEAIOFILESELECTOR,
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV,
}
/** 闪传文件集默认有效期(秒):14 天 */
export const DEFAULT_FLASH_VALIDITY_SECONDS = 1209600;
export interface StartFlashTaskRequests {
screen: number; // 1 PC-QQ
scene: number; // 1 PC-QQ
name?: string;
uploaders: UploaderInfo[];
permission?: {};
permission?: { code: number; };
coverPath?: string;
paths: string[]; // 文件的绝对路径,可以是文件夹
excludePaths?: string[];
expireLeftTime?: number, // 0
validitySeconds: number, // 文件集有效期(秒):14 天 1209600 / 90 天 7776000 / 180 天 15552000,必须传,否则新版内核段错误
isNeedDelDeviceInfo: boolean,
isNeedDelLocation: boolean,
coverOriginalInfos?: {
@@ -234,6 +238,12 @@ export interface StartFlashTaskRequests {
exists: boolean,
allDetectResults: {};
};
announcement: {
announcementSegments: unknown[],
modifyTime: string,
avatarUrl: string;
};
albumFilePathList: unknown[];
}
export enum BusiScene {
KBUSISCENEINVALID,
+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 };
}
+265 -55
View File
@@ -18,20 +18,64 @@ export interface BizReq {
iBatchID: number;
iBitmap: number;
iDistinctUse: number;
iNeedFeeds: number;
iNeedFeeds?: number;
iPicHight: number;
iPicWidth: number;
iUploadTime: number;
iUploadType: number;
iUpPicType: number;
iWaterType: number;
mapExt: MapExt;
mapExt?: MapExt;
mutliPicInfo?: MutliPicInfo;
sAlbumID: string;
sAlbumName: string;
sPicDesc: string;
sPicPath: string;
sPicTitle: string;
stExtendInfo: StExtendInfo;
stExtendInfo?: StExtendInfo;
// 视频主体上传专用
extend_info?: VideoExtendInfo;
iFlag?: number;
iIsFormatF20?: number;
iIsNew?: number;
iIsOriginalVideo?: number;
iPlayTime?: number;
sCoverUrl?: string;
sDesc?: string;
sTitle?: string;
// 视频封面二段上传专用
stExternalMapExt?: StExternalMapExt;
sExif_CameraMaker?: string;
sExif_CameraModel?: string;
sExif_Latitude?: string;
sExif_LatitudeRef?: string;
sExif_Longitude?: string;
sExif_LongitudeRef?: string;
sExif_Time?: string;
}
// 多图同批上传时描述「本批共几张 / 当前第几张」,相册里据此合并成同一条
export interface MutliPicInfo {
iBatUploadNum: string;
iCurUpload: string;
iSuccNum: number;
iFailNum: number;
}
// 视频主体上传用(视频不走 stExtendInfo.mapParams,而是这段扩展信息)
export interface VideoExtendInfo {
video_type: string;
domainid: string;
photo_num: string;
video_num: string;
batch_num: string;
qun_id: string;
}
// 视频封面二段上传用:声明这是客户端上传的封面,且与图片混合在同一条动态里
export interface StExternalMapExt {
is_client_upload_cover: string;
is_pic_video_mix_feeds: string;
}
export interface MapExt {
@@ -47,6 +91,8 @@ export interface MapParams {
batch_num: string;
photo_num: string;
video_num: string;
// 视频封面二段上传时用它把封面挂到已上传的视频上
vid?: string;
}
export interface Env {
@@ -60,6 +106,96 @@ export interface Token {
type: number;
}
// 一次上传的批次信息:同批的多张图必须共用 batchId,相册里才会显示成同一条。
export interface QunAlbumBatch {
batchId: number,
count: string,
index: string
}
let lastQunAlbumBatchId = 0;
// 批次号取秒级时间戳。同一秒里发起的两次上传要错开,不然会被相册并成同一条
export function nextQunAlbumBatchId () {
lastQunAlbumBatchId = Math.max(Math.floor(Date.now() / 1000), lastQunAlbumBatchId + 1);
return lastQunAlbumBatchId;
}
// control_req 的外层(鉴权、来源、会话),图片、视频、封面都一样
function buildQunAlbumControlReq (
{ uin, pskey, appid, checksum, check_type, file_len, refer = 'qzone', cmd }: {
uin: string,
pskey: string,
appid: string,
checksum: string,
check_type: number,
file_len: number,
refer?: string,
cmd?: string
},
biz_req: BizReq
): ControlReq {
const req: ControlReq = {
uin,
token: { type: 4, data: pskey, appid: 5 },
appid,
checksum,
check_type,
file_len,
env: { refer, deviceInfo: 'h5' },
model: 0,
biz_req,
session: '',
asy_upload: 0,
};
if (cmd) req.cmd = cmd;
return req;
}
// biz_req 里三种上传都要带的基础字段
function buildQunAlbumBizBase (
{ iUploadType, sAlbumName = '', sAlbumID = '', iBatchID = 0, sPicTitle = '' }: {
iUploadType: number,
sAlbumName?: string,
sAlbumID?: string,
iBatchID?: number,
sPicTitle?: string
}
): BizReq {
return {
sPicTitle,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType,
iUpPicType: 0,
iBatchID,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iUploadTime: Math.floor(Date.now() / 1000),
};
}
// 进相册的那一步(图片、视频封面)要带的群与批次信息
function buildQunAlbumFeedFields (group_id: string, mapParams: MapParams, batchIndex: string) {
return {
iNeedFeeds: 1,
mapExt: { appid: 'qun', userid: group_id },
stExtendInfo: { mapParams },
mutliPicInfo: {
iBatUploadNum: mapParams.batch_num,
iCurUpload: batchIndex,
iSuccNum: 0,
iFailNum: 0,
},
};
}
export function qunAlbumControl ({
uin,
group_id,
@@ -72,6 +208,8 @@ export function qunAlbumControl ({
photo_num = '1',
video_num = '0',
batch_num = '1',
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
}: {
uin: string,
group_id: string,
@@ -83,64 +221,21 @@ export function qunAlbumControl ({
sAlbumID: string,
photo_num?: string,
video_num?: string,
batch_num?: string
batch_num?: string,
batchId?: number,
batchIndex?: string
}
): {
control_req: ControlReq[]
} {
const timestamp = Math.floor(Date.now() / 1000);
return {
control_req: [
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: pic_md5, check_type: 0, file_len: img_size, cmd: 'FileUpload' },
{
uin,
token: {
type: 4,
data: pskey,
appid: 5,
},
appid: 'qun',
checksum: pic_md5,
check_type: 0,
file_len: img_size,
env: {
refer: 'qzone',
deviceInfo: 'h5',
},
model: 0,
biz_req: {
sPicTitle: img_name,
sPicDesc: '',
sAlbumName,
sAlbumID,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: {
appid: 'qun',
userid: group_id,
},
stExtendInfo: {
mapParams: {
photo_num,
video_num,
batch_num,
},
},
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
...buildQunAlbumBizBase({ iUploadType: 0, sAlbumName, sAlbumID, iBatchID: batchId, sPicTitle: img_name }),
...buildQunAlbumFeedFields(group_id, { photo_num, video_num, batch_num }, batchIndex),
}
)],
};
}
@@ -174,3 +269,118 @@ export function createStreamUpload (
},
};
}
/**
* 视频主体上传的控制体。
*
* 视频这一步不进相册(相册留空,iBatchID 为 0),只是先把视频传成素材;
* 分片响应里拿到 sVid 后,再由封面上传(qunAlbumVideoCoverControl)把视频挂进相册。
*/
export function qunAlbumVideoControl ({
uin,
group_id,
pskey,
video_sha1,
video_size,
play_time = 0,
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
video_sha1: string,
video_size: number,
play_time?: number,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'video_qun', checksum: video_sha1, check_type: 1, file_len: video_size, cmd: 'FileUploadVideo' },
{
...buildQunAlbumBizBase({ iUploadType: 3 }),
sTitle: '',
sDesc: '',
sCoverUrl: '',
iFlag: 0,
iPlayTime: play_time,
iIsNew: 111,
iIsOriginalVideo: 0,
iIsFormatF20: 0,
extend_info: {
video_type: '3',
domainid: '5',
photo_num,
video_num,
batch_num,
qun_id: group_id,
},
}
)],
};
}
/**
* 视频封面上传的控制体。
*
* 按图片上传,但 iUploadType 为 2,并用 mapParams.vid 指向已上传的视频。
* 相册和批次号只在这一步出现,视频是靠封面进的相册。
*/
export function qunAlbumVideoCoverControl ({
uin,
group_id,
pskey,
sAlbumName,
sAlbumID,
cover_md5,
cover_size,
vid,
batchId = nextQunAlbumBatchId(),
batchIndex = '0',
photo_num = '0',
video_num = '1',
batch_num = '1',
}: {
uin: string,
group_id: string,
pskey: string,
sAlbumName: string,
sAlbumID: string,
cover_md5: string,
cover_size: number,
vid: string,
batchId?: number,
batchIndex?: string,
photo_num?: string,
video_num?: string,
batch_num?: string
}): {
control_req: ControlReq[]
} {
return {
control_req: [buildQunAlbumControlReq(
{ uin, pskey, appid: 'qun', checksum: cover_md5, check_type: 0, file_len: cover_size, refer: 'huodong' },
{
...buildQunAlbumBizBase({ iUploadType: 2, sAlbumName, sAlbumID, iBatchID: batchId }),
...buildQunAlbumFeedFields(group_id, { vid, photo_num, video_num, batch_num }, batchIndex),
// 标明封面由客户端上传,且允许和图片出现在同一条动态里
stExternalMapExt: {
is_client_upload_cover: '1',
is_pic_video_mix_feeds: '1',
},
sExif_CameraMaker: '',
sExif_CameraModel: '',
sExif_Time: '',
sExif_LatitudeRef: '',
sExif_Latitude: '',
sExif_LongitudeRef: '',
sExif_Longitude: '',
}
)],
};
}
+218 -14
View File
@@ -395,12 +395,16 @@
"appid": 537319840,
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
},
"3.2.20-40768-arm64": {
"appid": 537319841,
"qua": "V1_LNX_NQ_3.2.20_40768_GW_B"
},
"9.9.22-40768": {
"appid": 537319804,
"qua": "V1_WIN_NQ_9.9.22_40768_GW_B"
},
"6.9.82-40768": {
"appid": 537319829,
"appid": 537319828,
"qua": "V1_MAC_NQ_6.9.82_40768_GW_B"
},
"3.2.20-40824": {
@@ -416,23 +420,27 @@
"qua": "V1_MAC_NQ_6.9.82_40824_GW_B"
},
"6.9.82-40990": {
"appid": 537319880,
"appid": 537319879,
"qua": "V1_MAC_NQ_6.9.82_40990_GW_B"
},
"9.9.22-40990": {
"appid": 537319855,
"qua": "V1_WIN_NQ_9.9.22.40990_GW_B"
"qua": "V1_WIN_NQ_9.9.22_40990_GW_B"
},
"3.2.20-40990": {
"appid": 537319891,
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
},
"3.2.20-40990-arm64": {
"appid": 537319892,
"qua": "V1_LNX_NQ_3.2.20_40990_GW_B"
},
"9.9.23-41679": {
"appid": 537320110,
"qua": "V1_WIN_NQ_9.9.23_41679_GW_B"
},
"6.9.83-41679": {
"appid": 537320135,
"appid": 537320134,
"qua": "V1_MAC_NQ_6.9.83_41679_GW_B"
},
"9.9.23-41785": {
@@ -440,7 +448,7 @@
"qua": "V1_WIN_NQ_9.9.23_41785_GW_B"
},
"6.9.83-41785": {
"appid": 537320135,
"appid": 537320134,
"qua": "V1_MAC_NQ_6.9.83_41785_GW_B"
},
"9.9.23-41857": {
@@ -451,20 +459,28 @@
"appid": 537320197,
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
},
"3.2.21-41857-arm64": {
"appid": 537320198,
"qua": "V1_LNX_NQ_3.2.21_41857_GW_B"
},
"6.9.83-41857": {
"appid": 537320186,
"appid": 537320185,
"qua": "V1_MAC_NQ_6.9.83_41857_GW_B"
},
"3.2.21-42086": {
"appid": 537320248,
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
},
"3.2.21-42086-arm64": {
"appid": 537320249,
"qua": "V1_LNX_NQ_3.2.21_42086_GW_B"
},
"9.9.23-42086": {
"appid": 537320212,
"qua": "V1_WIN_NQ_9.9.23_42086_GW_B"
},
"6.9.85-42086": {
"appid": 537320237,
"appid": 537320236,
"qua": "V1_MAC_NQ_6.9.85_42086_GW_B"
},
"9.9.23-42430": {
@@ -473,30 +489,34 @@
},
"9.9.25-42744": {
"appid": 537328470,
"qua": "V1_WIN_NQ_9.9.23_42744_GW_B"
"qua": "V1_WIN_NQ_9.9.25_42744_GW_B"
},
"6.9.86-42744": {
"appid": 537328495,
"qua": "V1_MAC_NQ_6.9.85_42744_GW_B"
"appid": 537328494,
"qua": "V1_MAC_NQ_6.9.86_42744_GW_B"
},
"9.9.25-42905": {
"appid": 537328521,
"qua": "V1_WIN_NQ_9.9.25_42905_GW_B"
},
"6.9.86-42905": {
"appid": 537328546,
"appid": 537328545,
"qua": "V1_MAC_NQ_6.9.86_42905_GW_B"
},
"3.2.22-42941": {
"appid": 537328659,
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
},
"3.2.22-42941-arm64": {
"appid": 537328660,
"qua": "V1_LNX_NQ_3.2.22_42941_GW_B"
},
"9.9.25-42941": {
"appid": 537328623,
"qua": "V1_WIN_NQ_9.9.25_42941_GW_B"
},
"6.9.86-42941": {
"appid": 537328648,
"appid": 537328647,
"qua": "V1_MAC_NQ_6.9.86_42941_GW_B"
},
"9.9.26-44175": {
@@ -511,6 +531,14 @@
"appid": 537336639,
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
},
"3.2.23-44343-arm64": {
"appid": 537336640,
"qua": "V1_LNX_NQ_3.2.23_44343_GW_B"
},
"6.9.87-44343": {
"appid": 537336627,
"qua": "V1_MAC_NQ_6.9.87_44343_GW_B"
},
"9.9.26-44498": {
"appid": 537337416,
"qua": "V1_WIN_NQ_9.9.26_44498_GW_B"
@@ -524,13 +552,21 @@
"qua": "V1_WIN_NQ_9.9.27_45627_GW_B"
},
"6.9.88-44725": {
"appid": 537337594,
"appid": 537337593,
"qua": "V1_MAC_NQ_6.9.88_44725_GW_B"
},
"3.2.25-45758": {
"appid": 537340249,
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"3.2.25-45758-arm64": {
"appid": 537340250,
"qua": "V1_LNX_NQ_3.2.25_45758_GW_B"
},
"6.9.89-45758": {
"appid": 537340237,
"qua": "V1_MAC_NQ_6.9.89_45758_GW_B"
},
"9.9.27-45758": {
"appid": 537340213,
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
@@ -539,6 +575,10 @@
"appid": 537345891,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"3.2.26-46494-arm64": {
"appid": 537345892,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"9.9.28-46494": {
"appid": 537345855,
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
@@ -548,13 +588,25 @@
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
},
"3.2.26-46928": {
"appid": 537345993,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"3.2.26-46928-arm64": {
"appid": 537345994,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"6.9.91-46928": {
"appid": 537345981,
"qua": "V1_MAC_NQ_6.9.91_46928_GW_B"
},
"9.9.28-46928": {
"appid": 537345957,
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
},
"3.2.27-47256": {
"appid": 537346857,
"qua": "V1_LNX_NQ_3.2.27_47256_GW_B"
},
"3.2.27-47354": {
"appid": 537346908,
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
@@ -574,5 +626,157 @@
"3.2.28-48517": {
"appid": 537352510,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"3.2.28-48517-arm64": {
"appid": 537352511,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
},
"6.9.95-48517": {
"appid": 537352498,
"qua": "V1_MAC_NQ_6.9.95_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": 537355866,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"3.2.29-49738-arm64": {
"appid": 537355867,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
},
"6.9.96-49738": {
"appid": 537355854,
"qua": "V1_MAC_NQ_6.9.96_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"
},
"3.2.30-50828-arm64": {
"appid": 537358776,
"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"
},
"3.2.30-50969-arm64": {
"appid": 537376345,
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
},
"3.2.31-51102": {
"appid": 537376497,
"qua": "V1_LNX_NQ_3.2.31_51102_GW_B"
},
"3.2.31-51102-arm64": {
"appid": 537376498,
"qua": "V1_LNX_NQ_3.2.31_51102_GW_B"
},
"6.9.98-51102": {
"appid": 537376485,
"qua": "V1_MAC_NQ_6.9.98_51102_GW_B"
},
"9.9.32-51246": {
"appid": 537376512,
"qua": "V1_WIN_NQ_9.9.32_51246_GW_B"
},
"3.2.32-51728": {
"appid": 537376803,
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
},
"3.2.32-51728-arm64": {
"appid": 537376804,
"qua": "V1_LNX_NQ_3.2.32_51728_GW_B"
},
"3.2.32-51802": {
"appid": 537376854,
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
},
"3.2.32-51802-arm64": {
"appid": 537376855,
"qua": "V1_LNX_NQ_3.2.32_51802_GW_B"
},
"6.9.99-51802": {
"appid": 537376842,
"qua": "V1_MAC_NQ_6.9.99_51802_GW_B"
},
"9.9.33-51802": {
"appid": 537376818,
"qua": "V1_WIN_NQ_9.9.33_51802_GW_B"
},
"9.9.33-52230": {
"appid": 537379411,
"qua": "V1_WIN_NQ_9.9.33_52230_GW_B"
},
"3.2.32-52194": {
"appid": 537379447,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"3.2.32-52194-arm64": {
"appid": 537379448,
"qua": "V1_LNX_NQ_3.2.32_52194_GW_B"
},
"7.0.0-52194": {
"appid": 537379435,
"qua": "V1_MAC_NQ_7.0.0_52194_GW_B"
},
"9.9.35-52804": {
"appid": 537382717,
"qua": "V1_WIN_NQ_9.9.35_52804_GW_B"
},
"9.9.35-52892": {
"appid": 537382819,
"qua": "V1_WIN_NQ_9.9.35_52892_GW_B"
},
"9.9.36-53489": {
"appid": 537391475,
"qua": "V1_WIN_NQ_9.9.36_53489_GW_B"
},
"3.2.33-52892": {
"appid": 537382855,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"3.2.33-52892-arm64": {
"appid": 537382856,
"qua": "V1_LNX_NQ_3.2.33_52892_GW_B"
},
"7.0.1-52892": {
"appid": 537382843,
"qua": "V1_MAC_NQ_7.0.1_52892_GW_B"
},
"3.2.34-53644": {
"appid": 537391664,
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
},
"3.2.34-53644-arm64": {
"appid": 537391665,
"qua": "V1_LNX_NQ_3.2.34_53644_GW_B"
},
"7.0.2-53644": {
"appid": 537391652,
"qua": "V1_MAC_NQ_7.0.2_53644_GW_B"
},
"9.9.36-53644": {
"appid": 537391628,
"qua": "V1_WIN_NQ_9.9.36_53644_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": [
+254 -6
View File
@@ -64,7 +64,7 @@
"recv": "1D19FF9"
},
"6.9.83-41857-arm64": {
"send": "0815774",
"send": "23B41F0",
"recv": "0958B3C"
},
"3.2.21-41857-x64": {
@@ -85,7 +85,7 @@
},
"6.9.85-42086-arm64": {
"send": "23B0330",
"recv": "0957648"
"recv": "9556B8"
},
"3.2.21-42086-arm64": {
"send": "3D6D98C",
@@ -103,7 +103,7 @@
"send": "0A0D104",
"recv": "1D3E7F9"
},
"6.9.85-42744-arm64": {
"6.9.86-42744-arm64": {
"send": "23DFEF0",
"recv": "095FD80"
},
@@ -147,6 +147,10 @@
"send": "59A27B0",
"recv": "2FFBE90"
},
"6.9.87-44343-arm64": {
"send": "2311B68",
"recv": "9673A4"
},
"9.9.26-44498-x64": {
"send": "0A1051C",
"recv": "1D3BC0D"
@@ -161,7 +165,7 @@
},
"6.9.88-44725-x64": {
"send": "2756EF6",
"recv": "0A36152"
"recv": "A36152"
},
"6.9.88-44725-arm64": {
"send": "2313C68",
@@ -175,6 +179,10 @@
"send": "3EB6554",
"recv": "149AF0C"
},
"6.9.89-45758-arm64": {
"send": "2425228",
"recv": "9B6770"
},
"9.9.27-45758-x64": {
"send": "0A6A6BC",
"recv": "1E87EC1"
@@ -191,6 +199,10 @@
"send": "3EDC654",
"recv": "14A3124"
},
"6.9.90-46494-arm64": {
"send": "2438B4C",
"recv": "9BBE00"
},
"3.2.26-46928-x64": {
"send": "5D30910",
"recv": "31814B0"
@@ -199,10 +211,18 @@
"send": "3EDC654",
"recv": "14A3124"
},
"6.9.91-46928-arm64": {
"send": "2438B4C",
"recv": "9BBE00"
},
"9.9.28-46928-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"3.2.27-47256-x64": {
"send": "5D389C0",
"recv": "318D090"
},
"3.2.27-47354-x64": {
"send": "5D38930",
"recv": "318D090"
@@ -221,7 +241,7 @@
},
"6.9.93-47354-x64": {
"send": "28ADE46",
"recv": "0A8FD5A"
"recv": "A8FD5A"
},
"9.9.30-48517-x64": {
"send": "0A9B1BC",
@@ -234,5 +254,233 @@
"3.2.28-48517-arm64": {
"send": "3F9C7E4",
"recv": "14E1AA8"
},
"6.9.95-48517-arm64": {
"send": "25120A8",
"recv": "9DB00C"
},
"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"
},
"6.9.96-49738-arm64": {
"send": "2785BB8",
"recv": "A29880"
},
"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"
},
"3.2.31-51102-x64": {
"send": "63F4910",
"recv": "34B9F90"
},
"3.2.31-51102-arm64": {
"send": "43A48E4",
"recv": "1608D98"
},
"6.9.98-51102-arm64": {
"send": "2849378",
"recv": "A66CFC"
},
"9.9.32-51246-x64": {
"send": "B2E37C",
"recv": "209C7D9"
},
"3.2.32-51728-arm64": {
"send": "48CA8F8",
"recv": "17D5A78"
},
"3.2.32-51728-x64": {
"send": "6B9ADD0",
"recv": "38F5F30"
},
"3.2.32-51802-x64": {
"send": "6B9B790",
"recv": "38F68F0"
},
"3.2.32-51802-arm64": {
"send": "48CB078",
"recv": "17D620C"
},
"6.9.99-51802-arm64": {
"send": "2B0B384",
"recv": "B4526C"
},
"9.9.33-51802-x64": {
"send": "BDE15F",
"recv": "237BC91"
},
"9.9.33-52230-x64": {
"send": "BF2B5F",
"recv": "23BB4DD"
},
"3.2.32-52194-x64": {
"send": "6C45D20",
"recv": "393DE00"
},
"3.2.32-52194-arm64": {
"send": "493FAD8",
"recv": "17EA1DC"
},
"7.0.0-52194-arm64": {
"send": "2B3FBA4",
"recv": "B4E85C"
},
"9.9.35-52804-x64": {
"send": "C3614F",
"recv": "246F481"
},
"9.9.35-52892-x64": {
"send": "C361DF",
"recv": "246F3A1"
},
"9.9.36-53489-x64": {
"send": "C3ED0F",
"recv": "24A6235"
},
"3.2.33-52892-x64": {
"send": "6DDB4C0",
"recv": "39DA860"
},
"3.2.33-52892-arm64": {
"send": "4A5D658",
"recv": "1813A34"
},
"7.0.1-52892-arm64": {
"send": "2B3FBCC",
"recv": "B64170"
},
"3.2.34-53644-x64": {
"send": "6E5AB20",
"recv": "3A12CD0"
},
"3.2.34-53644-arm64": {
"send": "4AABA5C",
"recv": "182C534"
},
"7.0.2-53644-arm64": {
"send": "2B82DEC",
"recv": "B71088"
},
"9.9.36-53644-x64": {
"send": "C3EE2F",
"recv": "24A6355"
},
"6.9.82-40768-x64": {
"send": "6587B8",
"recv": "C45C6E"
},
"6.9.82-40990-x64": {
"send": "6587B8",
"recv": "C45C6E"
},
"6.9.83-41679-x64": {
"send": "271A206",
"recv": "A1E04A"
},
"6.9.83-41785-x64": {
"send": "2744756",
"recv": "A1DE4A"
},
"6.9.83-41857-x64": {
"send": "2745186",
"recv": "A1E96E"
},
"6.9.85-42086-x64": {
"send": "27462F6",
"recv": "A1FC0A"
},
"6.9.86-42744-x64": {
"send": "27770E6",
"recv": "A2725A"
},
"6.9.86-42905-x64": {
"send": "2786206",
"recv": "A2D6A6"
},
"6.9.86-42941-x64": {
"send": "2786366",
"recv": "A2D2E2"
},
"6.9.87-44343-x64": {
"send": "2750306",
"recv": "A2F432"
},
"6.9.89-45758-x64": {
"send": "288CBB6",
"recv": "A87816"
},
"6.9.90-46494-x64": {
"send": "28A2F96",
"recv": "A8D2FE"
},
"6.9.91-46928-x64": {
"send": "28A2F96",
"recv": "A8D2FE"
},
"6.9.95-48517-x64": {
"send": "28DC616",
"recv": "AAED2A"
},
"6.9.96-49738-x64": {
"send": "2B8C936",
"recv": "AFF03E"
},
"6.9.98-51102-x64": {
"send": "2C6CD06",
"recv": "B42922"
},
"6.9.99-51802-x64": {
"send": "2F6C1AB",
"recv": "C16A4A"
},
"7.0.0-52194-x64": {
"send": "2FAC58B",
"recv": "C20DB2"
},
"7.0.1-52892-x64": {
"send": "304CC8B",
"recv": "C3A54E"
},
"7.0.2-53644-x64": {
"send": "309B1BB",
"recv": "C47262"
}
}
}
+259 -7
View File
@@ -528,8 +528,8 @@
"recv": "7D4D4A8"
},
"6.9.82-40768-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"9.9.22-40824-x64": {
"send": "31C1838",
@@ -540,8 +540,8 @@
"recv": "7D4D4A8"
},
"6.9.82-40824-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"3.2.20-40990-x64": {
"send": "B69CFE0",
@@ -556,8 +556,8 @@
"recv": "31C4FDC"
},
"6.9.82-40990-arm64": {
"send": "202A198",
"recv": "202B718"
"send": "4054330",
"recv": "4056E30"
},
"9.9.23-41679-x64": {
"send": "2C94520",
@@ -603,6 +603,10 @@
"send": "6B13038",
"recv": "6B169C8"
},
"6.9.85-42086-arm64": {
"send": "3D6D028",
"recv": "3D6F938"
},
"9.9.23-42430-x64": {
"send": "2C9A4A0",
"recv": "2C9DA20"
@@ -655,6 +659,10 @@
"send": "6926F60",
"recv": "692A910"
},
"6.9.87-44343-arm64": {
"send": "3D74F50",
"recv": "3D77860"
},
"9.9.26-44498-x64": {
"send": "2CDAE40",
"recv": "2CDE3C0"
@@ -687,6 +695,10 @@
"send": "6D6F9A0",
"recv": "6D73350"
},
"6.9.89-45758-arm64": {
"send": "3F9BD68",
"recv": "3F9E678"
},
"3.2.26-46494-x64": {
"send": "AB341C0",
"recv": "AB37C60"
@@ -699,6 +711,10 @@
"send": "6DBBBB0",
"recv": "6DBF560"
},
"6.9.90-46494-arm64": {
"send": "3FC2CD0",
"recv": "3FC55E0"
},
"3.2.26-46928-arm64": {
"send": "6DBBBB0",
"recv": "6DBF560"
@@ -707,10 +723,18 @@
"send": "AB341C0",
"recv": "AB37C60"
},
"6.9.91-46928-arm64": {
"send": "3FC2CD0",
"recv": "3FC55E0"
},
"9.9.28-46928-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"3.2.27-47256-x64": {
"send": "AB6A7E0",
"recv": "AB6E280"
},
"3.2.27-47354-x64": {
"send": "AB6A6C0",
"recv": "AB6E160"
@@ -742,5 +766,233 @@
"3.2.28-48517-arm64": {
"send": "6F48B70",
"recv": "6F4C520"
},
"6.9.95-48517-arm64": {
"send": "40A0438",
"recv": "40A2D48"
},
"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"
},
"6.9.96-49738-arm64": {
"send": "428B660",
"recv": "428DF70"
},
"9.9.32-50828-x64": {
"send": "3155200",
"recv": "3158788"
},
"3.2.30-50828-arm64": {
"send": "74C3070",
"recv": "74C6A20"
},
"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"
},
"3.2.31-51102-x64": {
"send": "B739780",
"recv": "B73D220"
},
"3.2.31-51102-arm64": {
"send": "75BD390",
"recv": "75C0D40"
},
"6.9.98-51102-arm64": {
"send": "4419468",
"recv": "441BD78"
},
"9.9.32-51246-x64": {
"send": "3199680",
"recv": "319CC08"
},
"3.2.32-51728-arm64": {
"send": "8009330",
"recv": "800CCE0"
},
"3.2.32-51728-x64": {
"send": "C6860E0",
"recv": "C689B80"
},
"3.2.32-51802-x64": {
"send": "C687460",
"recv": "C68AF00"
},
"3.2.32-51802-arm64": {
"send": "800A230",
"recv": "800DBE0"
},
"6.9.99-51802-arm64": {
"send": "499CF40",
"recv": "499FA40"
},
"9.9.33-51802-x64": {
"send": "360A0D8",
"recv": "360D88C"
},
"9.9.33-52230-x64": {
"send": "367FE18",
"recv": "36835CC"
},
"3.2.32-52194-x64": {
"send": "C7DBF80",
"recv": "C7DFA20"
},
"3.2.32-52194-arm64": {
"send": "80F36D0",
"recv": "80F7080"
},
"7.0.0-52194-arm64": {
"send": "4A05FB0",
"recv": "4A08AB0"
},
"9.9.35-52804-x64": {
"send": "37C3298",
"recv": "37C6A4C"
},
"9.9.35-52892-x64": {
"send": "37C30D8",
"recv": "37C688C"
},
"9.9.36-53489-x64": {
"send": "38253B0",
"recv": "3828BF0"
},
"3.2.33-52892-x64": {
"send": "CB06D60",
"recv": "CB0A800"
},
"3.2.33-52892-arm64": {
"send": "832ECA0",
"recv": "8332650"
},
"7.0.1-52892-arm64": {
"send": "4B1E4B8",
"recv": "4B20FB8"
},
"3.2.34-53644-x64": {
"send": "CBF25A0",
"recv": "CBF60E0"
},
"3.2.34-53644-arm64": {
"send": "83D1BD0",
"recv": "83D5610"
},
"7.0.2-53644-arm64": {
"send": "4BA3870",
"recv": "4BA6388"
},
"9.9.36-53644-x64": {
"send": "38255F0",
"recv": "3828E30"
},
"6.9.82-40768-x64": {
"send": "489A168",
"recv": "489CD18"
},
"6.9.82-40990-x64": {
"send": "489A168",
"recv": "489CD18"
},
"6.9.83-41679-x64": {
"send": "450C8E0",
"recv": "450F490"
},
"6.9.83-41785-x64": {
"send": "450C540",
"recv": "450F0F0"
},
"6.9.83-41857-x64": {
"send": "450D998",
"recv": "4510548"
},
"6.9.85-42086-x64": {
"send": "450E430",
"recv": "4510FE0"
},
"6.9.86-42744-x64": {
"send": "4570018",
"recv": "4572BC8"
},
"6.9.86-42905-x64": {
"send": "457E7C0",
"recv": "4581370"
},
"6.9.86-42941-x64": {
"send": "457EA78",
"recv": "4581628"
},
"6.9.87-44343-x64": {
"send": "45126C0",
"recv": "4515270"
},
"6.9.89-45758-x64": {
"send": "478B860",
"recv": "478E410"
},
"6.9.90-46494-x64": {
"send": "47B8018",
"recv": "47BABC8"
},
"6.9.91-46928-x64": {
"send": "47B8018",
"recv": "47BABC8"
},
"6.9.95-48517-x64": {
"send": "48A92C0",
"recv": "48ABE70"
},
"6.9.96-49738-x64": {
"send": "4ACD9D8",
"recv": "4AD0588"
},
"6.9.98-51102-x64": {
"send": "4C953E8",
"recv": "4C97F98"
},
"6.9.99-51802-x64": {
"send": "5293B28",
"recv": "52966D8"
},
"7.0.0-52194-x64": {
"send": "53143C0",
"recv": "5316F70"
},
"7.0.1-52892-x64": {
"send": "54552F8",
"recv": "5457EA8"
},
"7.0.2-53644-x64": {
"send": "54F11F0",
"recv": "54F3DA8"
}
}
}
+9 -38
View File
@@ -1,45 +1,16 @@
import fsPromise from 'fs/promises';
import path from 'node:path';
import { randomUUID } from 'crypto';
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
async function guessDuration (pttPath: string, logger: LogWrapper) {
const pttFileInfo = await fsPromise.stat(pttPath);
const duration = Math.max(1, Math.floor(pttFileInfo.size / 1024 / 3)); // 3kb/s
logger.log('通过文件大小估算语音的时长:', duration);
return duration;
}
export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: LogWrapper) {
try {
const pttPath = path.join(TEMP_DIR, randomUUID());
if (!(await FFmpegService.isSilk(filePath))) {
logger.log(`语音文件${filePath}需要转换成silk`);
await FFmpegService.convertToNTSilkTct(filePath, pttPath);
const duration = await FFmpegService.getDuration(filePath);
logger.log(`语音文件${filePath}转换成功!`, pttPath, '时长:', duration);
return {
converted: true,
path: pttPath,
duration,
};
} else {
let duration = 0;
try {
duration = await FFmpegService.getDuration(filePath);
} catch (e: unknown) {
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, (e as Error).stack);
duration = await guessDuration(filePath, logger);
}
return {
converted: false,
path: filePath,
duration,
};
}
} catch (error: unknown) {
logger.logError('convert silk failed', error);
return {};
export async function encodeSilk (filePath: string, temporaryDirectory: string, logger: LogWrapper) {
const converted = !(await FFmpegService.isSilk(filePath));
const pttPath = converted ? path.join(temporaryDirectory, randomUUID()) : filePath;
if (converted) {
logger.log(`语音文件${filePath}需要转换成silk`);
await FFmpegService.convertToNTSilkTct(filePath, pttPath);
}
const duration = await FFmpegService.getDuration(pttPath);
logger.log('语音文件已就绪:', pttPath, '时长:', duration);
return { converted, path: pttPath, duration };
}
@@ -4,7 +4,8 @@
*/
import { LogWrapper } from '@/napcat-core/helper/log';
import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter';
import { FFmpegAddonAdapter, getAddonPath } from './ffmpeg-addon-adapter';
import { existsSync } from 'node:fs';
import { FFmpegExecAdapter } from './ffmpeg-exec-adapter';
import type { IFFmpegAdapter } from './ffmpeg-adapter-interface';
@@ -58,8 +59,8 @@ export class FFmpegAdapterFactory {
ffprobePath: string,
binaryPath?: string
): Promise<IFFmpegAdapter> {
// 1. 优先尝试使用 Native Addon
if (binaryPath) {
const useCommandLine = Boolean(process.env['FFMPEG_PATH'] || process.env['FFPROBE_PATH']);
if (binaryPath && !useCommandLine && existsSync(getAddonPath(binaryPath))) {
const addonAdapter = new FFmpegAddonAdapter(binaryPath);
logger.log('[FFmpeg] 检查 Native Addon 可用性...');
@@ -68,13 +69,10 @@ export class FFmpegAdapterFactory {
return addonAdapter;
}
logger.log('[FFmpeg] Native Addon 不可用,尝试使用命令行工具');
} else {
logger.log('[FFmpeg] 未提供 binaryPath,跳过 Native Addon 检测');
throw new Error('FFmpeg Native Addon 加载失败: ' + getAddonPath(binaryPath));
}
// 2. 降级到 execFile 实现
const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath, binaryPath, logger);
const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath);
logger.log(`[FFmpeg] 检查命令行工具可用性: ${ffmpegPath}`);
if (await execAdapter.isAvailable()) {
@@ -82,9 +80,7 @@ export class FFmpegAdapterFactory {
return execAdapter;
}
// 3. 都不可用,返回 execAdapter 但会在使用时报错
logger.logError('[FFmpeg] 警告: FFmpeg 不可用,将使用命令行适配器但可能失败');
return execAdapter;
throw new Error('FFmpeg 命令行工具不可用,请检查 ffmpeg 和 ffprobe 路径: ' + ffmpegPath + ', ' + ffprobePath);
}
/**
@@ -105,20 +101,14 @@ export class FFmpegAdapterFactory {
logger: LogWrapper,
ffmpegPath: string,
ffprobePath: string
): Promise<void> {
// 如果当前使用的是 Exec 适配器,更新路径
if (this.instance && this.instance instanceof FFmpegExecAdapter) {
logger.log(`[FFmpeg] 更新 FFmpeg 路径: ${ffmpegPath}`);
this.instance.setFFmpegPath(ffmpegPath);
this.instance.setFFprobePath(ffprobePath);
// 验证新路径是否可用
if (await this.instance.isAvailable()) {
logger.log('[FFmpeg] 新路径验证成功 ✓');
} else {
logger.logError('[FFmpeg] 警告: 新 FFmpeg 路径不可用');
}
): Promise<IFFmpegAdapter> {
const adapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath);
if (!await adapter.isAvailable()) {
throw new Error('FFmpeg 路径不可用: ' + ffmpegPath + ', ' + ffprobePath);
}
this.instance = adapter;
logger.log('[FFmpeg] 已更新命令行工具路径:', ffmpegPath, ffprobePath);
return adapter;
}
/**
@@ -3,9 +3,8 @@
* 使用原生 Node.js Addon 实现的 FFmpeg 适配器
*/
import { platform, arch } from 'node:os';
import path from 'node:path';
import { existsSync, openSync, readSync, closeSync } from 'node:fs';
import { openSync, readSync, closeSync } from 'node:fs';
import { writeFile } from 'node:fs/promises';
import type { FFmpeg } from './ffmpeg-addon';
import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface';
@@ -15,15 +14,9 @@ import { dlopen } from 'node:process';
* 获取 Native Addon 路径
* @param binaryPath 二进制文件路径(来自 pathWrapper.binaryPath)
*/
function getAddonPath (binaryPath: string): string {
const platformName = platform();
const archName = arch();
export function getAddonPath (binaryPath: string): string {
const addonFileName: string = process.platform + '.' + process.arch;
const addonPath = path.join(binaryPath, './native/ffmpeg/', `ffmpegAddon.${addonFileName}.node`);
if (!existsSync(addonPath)) {
throw new Error(`Unsupported platform: ${platformName} ${archName} - Addon not found at ${addonPath}`);
}
return addonPath;
}
@@ -130,9 +123,9 @@ export class FFmpegAddonAdapter implements IFFmpegAdapter {
/**
* 提取缩略图
*/
async extractThumbnail (videoPath: string, thumbnailPath: string): Promise<void> {
async extractThumbnail (videoPath: string, thumbnailPath: string, format: 'jpg' | 'png' = 'jpg'): Promise<void> {
const addon = this.ensureAddon();
const info = await addon.getVideoInfo(videoPath);
const info = await addon.getVideoInfo(videoPath, format);
// 将缩略图写入文件
await writeFile(thumbnailPath, info.image);
@@ -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;
}
@@ -53,7 +53,7 @@ export interface FFmpeg {
/**
* Get video information including resolution, duration, format, codec and first frame thumbnail
*/
getVideoInfo (filePath: string, format?: 'bmp' | 'bmp24'): Promise<VideoInfo>;
getVideoInfo (filePath: string, format?: 'jpg' | 'png'): Promise<VideoInfo>;
/**
* Get duration of audio or video file in seconds
@@ -3,14 +3,10 @@
* 使用 execFile 调用 FFmpeg 命令行工具的适配器实现
*/
import { readFileSync, existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs';
import { dirname, join } from 'path';
import { existsSync, mkdirSync, openSync, readSync, closeSync } from 'fs';
import { dirname } from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { fileTypeFromFile } from 'file-type';
import { imageSizeFallBack } from 'napcat-image-size/src/index';
import { downloadFFmpegIfNotExists } from './download-ffmpeg';
import { LogWrapper } from '@/napcat-core/helper/log';
import type { IFFmpegAdapter, VideoInfoResult } from './ffmpeg-adapter-interface';
const execFileAsync = promisify(execFile);
@@ -30,52 +26,24 @@ function ensureDirExists (filePath: string): void {
*/
export class FFmpegExecAdapter implements IFFmpegAdapter {
public readonly name = 'FFmpegExec';
private downloadAttempted = false;
constructor (
private ffmpegPath: string = 'ffmpeg',
private ffprobePath: string = 'ffprobe',
private binaryPath?: string,
private logger?: LogWrapper
private ffprobePath: string = 'ffprobe'
) { }
/**
* 检查 FFmpeg 是否可用,如果不可用则尝试下载
* 检查 FFmpeg 和 FFprobe 是否可用
*/
async isAvailable (): Promise<boolean> {
// 首先检查当前路径
try {
await execFileAsync(this.ffmpegPath, ['-version']);
await Promise.all([
execFileAsync(this.ffmpegPath, ['-version'], { timeout: 10000, windowsHide: true }),
execFileAsync(this.ffprobePath, ['-version'], { timeout: 10000, windowsHide: true }),
]);
return true;
} catch {
// 如果失败且未尝试下载,尝试下载
if (!this.downloadAttempted && this.binaryPath && this.logger) {
this.downloadAttempted = true;
if (process.env['NAPCAT_DISABLE_FFMPEG_DOWNLOAD']) {
return false;
}
this.logger.log('[FFmpeg] 未找到可用的 FFmpeg,尝试自动下载...');
const result = await downloadFFmpegIfNotExists(this.logger);
if (result.path && result.reset) {
// 更新路径
if (process.platform === 'win32') {
this.ffmpegPath = join(result.path, 'ffmpeg.exe');
this.ffprobePath = join(result.path, 'ffprobe.exe');
this.logger.log('[FFmpeg] 已更新路径:', this.ffmpegPath);
// 再次检查
try {
await execFileAsync(this.ffmpegPath, ['-version']);
return true;
} catch {
return false;
}
}
}
}
return false;
}
}
@@ -98,59 +66,48 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
* 获取视频信息
*/
async getVideoInfo (videoPath: string): Promise<VideoInfoResult> {
// 获取文件大小和类型
const [fileType, duration] = await Promise.all([
fileTypeFromFile(videoPath).catch(() => null),
this.getDuration(videoPath).catch(() => 60),
const [probe, frame] = await Promise.all([
execFileAsync(this.ffprobePath, [
'-v', 'error', '-select_streams', 'v:0',
'-show_entries', 'stream=width,height:format=duration,format_name',
'-of', 'json', videoPath,
], { timeout: 30000, windowsHide: true }),
execFileAsync(this.ffmpegPath, [
'-v', 'error', '-i', videoPath, '-frames:v', '1',
'-f', 'image2pipe', '-vcodec', 'mjpeg', 'pipe:1',
], { encoding: 'buffer', maxBuffer: 16 * 1024 * 1024, timeout: 30000, windowsHide: true }),
]);
// 创建临时缩略图路径
const thumbnailPath = `${videoPath}.thumbnail.bmp`;
let width = 100;
let height = 100;
let thumbnail: Buffer | undefined;
try {
await this.extractThumbnail(videoPath, thumbnailPath);
// 获取图片尺寸
const dimensions = await imageSizeFallBack(thumbnailPath);
width = dimensions.width ?? 100;
height = dimensions.height ?? 100;
// 读取缩略图
if (existsSync(thumbnailPath)) {
thumbnail = readFileSync(thumbnailPath);
}
} catch (_error) {
// 使用默认值
const metadata = JSON.parse(probe.stdout);
const stream = metadata.streams[0];
const duration = Number(metadata.format.duration);
if (!stream || !Number.isFinite(duration) || duration < 0 || frame.stdout.length === 0) {
throw new Error('FFmpeg 无法读取视频信息或首帧: ' + videoPath);
}
return {
width,
height,
width: stream.width,
height: stream.height,
duration,
format: fileType?.ext ?? 'mp4',
thumbnail,
format: metadata.format.format_name,
thumbnail: frame.stdout,
};
}
/**
* 获取时长
*/
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,
]);
], { timeout: 30000, windowsHide: true });
const duration = parseFloat(stdout.trim());
if (isNaN(duration)) {
if (!Number.isFinite(duration) || duration < 0) {
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
}
return duration;
@@ -186,7 +143,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
'-ac', '1',
'-f', 's16le',
pcmPath,
]);
], { timeout: 120000, windowsHide: true });
if (!existsSync(pcmPath)) {
throw new Error('转换PCM失败,输出文件不存在');
@@ -207,25 +164,22 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
const params = format === 'amr'
? [
'-f', 's16le',
'-ar', '24000',
'-ac', '1',
'-i', inputFile,
'-vn', '-ac', '1',
'-ar', '8000',
'-b:a', '12.2k',
'-y',
outputFile,
]
: [
'-f', 's16le',
'-ar', '24000',
'-ac', '1',
'-i', inputFile,
'-vn', '-ac', '1',
...(format === 'spx' ? ['-ar', '32000'] : []),
'-y',
outputFile,
];
await execFileAsync(this.ffmpegPath, params);
await execFileAsync(this.ffmpegPath, params, { timeout: 120000, windowsHide: true });
if (!existsSync(outputFile)) {
throw new Error('转换失败,输出文件不存在');
@@ -245,11 +199,10 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
const { stderr } = await execFileAsync(this.ffmpegPath, [
'-i', videoPath,
'-ss', '00:00:01.000',
'-vframes', '1',
'-y', // 覆盖输出文件
thumbnailPath,
]);
], { timeout: 30000, windowsHide: true });
if (!existsSync(thumbnailPath)) {
throw new Error(`提取缩略图失败,输出文件不存在: ${stderr}`);
@@ -260,7 +213,11 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
}
}
async convertToNTSilkTct (_inputFile: string, _outputFile: string): Promise<void> {
throw new Error('convertToNTSilkTct is not implemented in FFmpegExecAdapter');
async convertToNTSilkTct (inputFile: string, outputFile: string): Promise<void> {
ensureDirExists(outputFile);
await execFileAsync(this.ffmpegPath, [
'-v', 'error', '-y', '-i', inputFile, '-vn', '-ac', '1', '-ar', '24000',
'-c:a', 'ntsilk_s16le', '-f', 'ntsilk_s16le', outputFile,
], { timeout: 120000, windowsHide: true });
}
}
+66 -62
View File
@@ -1,20 +1,29 @@
import { statSync, existsSync, writeFileSync } from 'fs';
import path from 'path';
import type { VideoInfo } from './video';
import { fileTypeFromFile } from 'file-type';
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';
import { FFmpegAddonAdapter } from './ffmpeg-addon-adapter';
const getFFmpegPath = (tool: string, binaryPath?: string): string => {
if (process.platform === 'win32' && binaryPath) {
const exeName = `${tool}.exe`;
const localPath = path.join(binaryPath, 'ffmpeg', exeName);
const isLocalExeExists = existsSync(localPath);
return isLocalExeExists ? localPath : exeName;
export const getFFmpegPath = (tool: 'ffmpeg' | 'ffprobe', binaryPath?: string): string => {
const configuredPath = process.env[tool === 'ffmpeg' ? 'FFMPEG_PATH' : 'FFPROBE_PATH'];
if (configuredPath) return configuredPath;
const executable = tool + (process.platform === 'win32' ? '.exe' : '');
if (binaryPath) {
const localPath = path.join(binaryPath, 'ffmpeg', executable);
if (existsSync(localPath)) return localPath;
}
return tool;
if (process.platform === 'darwin') {
const directories = (process.env['PATH'] ?? '').split(':').filter(Boolean);
directories.push(process.arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin');
for (const directory of directories) {
const candidate = path.join(directory, executable);
if (existsSync(candidate)) return candidate;
}
}
return executable;
};
export let FFMPEG_CMD = 'ffmpeg';
@@ -22,6 +31,7 @@ export let FFPROBE_CMD = 'ffprobe';
export class FFmpegService {
private static adapter: IFFmpegAdapter | null = null;
private static initialized = false;
private static initializationError: unknown;
/**
* 初始化 FFmpeg 服务
@@ -37,20 +47,24 @@ export class FFmpegService {
FFMPEG_CMD = getFFmpegPath('ffmpeg', binaryPath);
FFPROBE_CMD = getFFmpegPath('ffprobe', binaryPath);
// 立即初始化适配器(会触发自动下载等逻辑)
this.adapter = await FFmpegAdapterFactory.getAdapter(
logger,
FFMPEG_CMD,
FFPROBE_CMD,
binaryPath
);
try {
this.adapter = await FFmpegAdapterFactory.getAdapter(
logger,
FFMPEG_CMD,
FFPROBE_CMD,
binaryPath
);
} catch (error) {
this.initializationError = error;
logger.logError('[FFmpeg] 媒体功能初始化失败:', error);
}
this.initialized = true;
}
public static getAdapterName (): string {
if (!this.adapter) {
throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
}
return this.adapter.name;
}
@@ -60,7 +74,7 @@ export class FFmpegService {
*/
private static async getAdapter (): Promise<IFFmpegAdapter> {
if (!this.adapter) {
throw new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
throw this.initializationError ?? new Error('FFmpeg service not initialized. Please call FFmpegService.init() first.');
}
return this.adapter;
}
@@ -75,15 +89,14 @@ export class FFmpegService {
* @deprecated 建议使用 init() 方法初始化
*/
public static async setFfmpegPath (ffmpegPath: string, logger: LogWrapper): Promise<void> {
if (platform() === 'win32') {
FFMPEG_CMD = path.join(ffmpegPath, 'ffmpeg.exe');
FFPROBE_CMD = path.join(ffmpegPath, 'ffprobe.exe');
logger.log('[Check] ffmpeg:', FFMPEG_CMD);
logger.log('[Check] ffprobe:', FFPROBE_CMD);
// 更新适配器路径
await FFmpegAdapterFactory.updateFFmpegPath(logger, FFMPEG_CMD, FFPROBE_CMD);
}
const suffix = process.platform === 'win32' ? '.exe' : '';
const ffmpegCommand = path.join(ffmpegPath, 'ffmpeg' + suffix);
const ffprobeCommand = path.join(ffmpegPath, 'ffprobe' + suffix);
this.adapter = await FFmpegAdapterFactory.updateFFmpegPath(logger, ffmpegCommand, ffprobeCommand);
FFMPEG_CMD = ffmpegCommand;
FFPROBE_CMD = ffprobeCommand;
this.initializationError = undefined;
this.initialized = true;
}
/**
@@ -94,6 +107,20 @@ 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 currentAdapter = await this.getAdapter();
if (currentAdapter instanceof FFmpegAddonAdapter) {
await currentAdapter.extractThumbnail(videoPath, thumbnailPath, 'png');
return;
}
const adapter = new FFmpegExecAdapter(FFMPEG_CMD, FFPROBE_CMD);
await adapter.extractThumbnail(videoPath, thumbnailPath);
}
/**
* 转换音频文件
*/
@@ -132,41 +159,18 @@ export class FFmpegService {
public static async getVideoInfo (videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
const adapter = await this.getAdapter();
try {
// 获取文件大小
const fileSize = statSync(videoPath).size;
// 使用适配器获取视频信息
const videoInfo = await adapter.getVideoInfo(videoPath);
// 如果提供了缩略图路径且适配器返回了缩略图,保存到指定路径
if (thumbnailPath && videoInfo.thumbnail) {
writeFileSync(thumbnailPath, videoInfo.thumbnail);
}
const result: VideoInfo = {
width: videoInfo.width,
height: videoInfo.height,
time: videoInfo.duration,
format: videoInfo.format,
size: fileSize,
filePath: videoPath,
};
return result;
} catch (_error) {
// 降级处理:返回默认值
const fileType = await fileTypeFromFile(videoPath).catch(() => null);
const fileSize = statSync(videoPath).size;
return {
width: 100,
height: 100,
time: 60,
format: fileType?.ext ?? 'mp4',
size: fileSize,
filePath: videoPath,
};
const fileSize = statSync(videoPath).size;
const videoInfo = await adapter.getVideoInfo(videoPath);
if (thumbnailPath && videoInfo.thumbnail) {
writeFileSync(thumbnailPath, videoInfo.thumbnail);
}
return {
width: videoInfo.width,
height: videoInfo.height,
time: videoInfo.duration,
format: videoInfo.format,
size: fileSize,
filePath: videoPath,
};
}
}
+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 }));
}
@@ -0,0 +1,58 @@
export interface OfflineRecoveryOptions {
// 当前账号是否在线
isOnline: () => boolean;
// 刚下线:同步 WebUI 状态
onOffline: (tips: string) => void;
// 静默离线期间账号自己恢复了,不需要重启
onRecovered: () => void;
// 重启 Worker;返回 false 或抛错表示失败,之后可以再次触发
restart: (tips: string) => Promise<boolean>;
// 被踢下线后多久重启。常规状态轮询为 3 秒,留出一个轮询周期,确保浏览器先清除旧二维码
kickedDelayMs?: number;
// 静默离线后多久重启。网络短暂断开时 QQ 也可能报离线,先给它自己重连的机会,
// 不然一次网络抖动就会把整个 Worker 重启掉
selfOfflineDelayMs?: number;
}
/**
* 下线恢复:被踢下线(KickedOffLine)和静默离线(SelfOffline)共用。
* 返回的函数在每次收到下线事件时调用,allowSelfRecovery 为 true 表示静默离线。
*/
export function createOfflineRecovery ({
isOnline,
onOffline,
onRecovered,
restart,
kickedDelayMs = 3_500,
selfOfflineDelayMs = 60_000,
}: OfflineRecoveryOptions) {
let restartRequested = false;
let selfRecoveryTimer: ReturnType<typeof setTimeout> | undefined;
return (tips: string, allowSelfRecovery: boolean) => {
onOffline(tips);
if (restartRequested) {
// 被踢时离线状态可能先到:还在等静默离线自行恢复的话,不用再等了
if (allowSelfRecovery || !selfRecoveryTimer) return;
clearTimeout(selfRecoveryTimer);
}
restartRequested = true;
// 不在 RefreshQRcode 请求里直接重启 Worker,否则请求在返回前就被中断,
// 浏览器只能得到 ERR_EMPTY_RESPONSE;延后调度也让前端先看到「二维码已清空、正在恢复」
const timer = setTimeout(() => {
selfRecoveryTimer = undefined;
if (allowSelfRecovery && isOnline()) {
restartRequested = false;
onRecovered();
return;
}
restart(tips).then((ok) => {
if (!ok) restartRequested = false;
}, () => {
restartRequested = false;
});
}, allowSelfRecovery ? selfOfflineDelayMs : kickedDelayMs);
selfRecoveryTimer = allowSelfRecovery ? timer : undefined;
};
}
+3 -2
View File
@@ -79,10 +79,11 @@ export class QQBasicInfoWrapper {
getAppidV2 (): { appid: string; qua: string; } {
// 通过已有表 性能好
const appidTbale = AppidTable as unknown as QQAppidTableType;
const appidTable = AppidTable as unknown as QQAppidTableType;
const fullVersion = this.getFullQQVersion();
if (fullVersion) {
const data = appidTbale[fullVersion];
// 同一 Linux 版本的 x64 和 arm64 使用不同的 AppID,优先匹配架构。
const data = appidTable[`${fullVersion}-${process.arch}`] ?? appidTable[fullVersion];
if (data) {
return data;
}
+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),
+30 -7
View File
@@ -59,12 +59,30 @@ export enum NapCatCoreWorkingEnv {
Framework = 2,
}
function dlopenWrapper (wrapperPath: string): WrapperNodeApi {
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
try {
process.dlopen(nativemodule, wrapperPath);
} catch (error) {
// QQNT.dll 依赖媒体基础(mfplat.dll 等),Windows Server 默认不装这个组件。
// 缺了它系统只会报 The specified module could not be found,看不出缺的是什么
const mfplatPath = path.join(process.env['SystemRoot'] || 'C:\\Windows', 'System32', 'mfplat.dll');
if (os.platform() === 'win32' && !fs.existsSync(mfplatPath)) {
throw new Error(
'加载 wrapper.node 失败:系统缺少「媒体基础」组件(找不到 mfplat.dll),Windows Server 默认不安装它。' +
'请在服务器管理器的「添加角色和功能」里勾选「媒体基础」,' +
'或在管理员 PowerShell 中执行 Install-WindowsFeature Server-Media-Foundation,重启后再启动。' +
`原始错误:${(error as Error).message}`
);
}
throw error;
}
return nativemodule.exports;
}
export function loadQQWrapper (execPath: string | undefined, QQVersion: string): WrapperNodeApi {
if (process.env['NAPCAT_WRAPPER_PATH']) {
const wrapperPath = process.env['NAPCAT_WRAPPER_PATH'];
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperPath);
return nativemodule.exports;
return dlopenWrapper(process.env['NAPCAT_WRAPPER_PATH']);
}
if (!execPath) {
throw new Error('无法加载Wrapper,execPath未定义');
@@ -85,10 +103,9 @@ export function loadQQWrapper (execPath: string | undefined, QQVersion: string):
if (!fs.existsSync(wrapperNodePath)) {
wrapperNodePath = path.join(path.dirname(execPath), `./resources/app/versions/${QQVersion}/wrapper.node`);
}
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperNodePath);
const exports = dlopenWrapper(wrapperNodePath);
process.env['NAPCAT_WRAPPER_PATH'] = wrapperNodePath;
return nativemodule.exports;
return exports;
}
export function getMajorPath (execPath: string, QQVersion: string): string {
// major.node
@@ -261,8 +278,14 @@ export class NapCatCore {
};
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => {
if (Info.status === 20) {
// 静默离线:服务端判定会话失效,但不会下发 KickedOffLine 通知。
// 仅在 在线 -> 离线 的跳变上广播一次,供上层复用下线恢复链路。
const wasOnline = this.selfInfo.online === true;
this.selfInfo.online = false;
this.context.logger.log('账号状态变更为离线');
if (wasOnline) {
this.event.emit('SelfOffline', '[SelfOffline] 账号状态变更为离线(未收到 KickedOffLine 通知)');
}
} else {
this.selfInfo.online = true;
}
@@ -38,13 +38,19 @@ 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;
}
this.available = false;
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40768');
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 (
@@ -72,8 +78,9 @@ export class NativePacketClient {
data: (ret as { rspbuffer: Buffer; }).rspbuffer,
}));
let timeoutHandle: ReturnType<typeof setTimeout>;
const timeoutPromise = new Promise<RecvPacketData>((_resolve, reject) => {
setTimeout(
timeoutHandle = setTimeout(
() =>
reject(
new Error(
@@ -84,7 +91,11 @@ export class NativePacketClient {
);
});
return Promise.race([sendPromise, timeoutPromise]);
try {
return await Promise.race([sendPromise, timeoutPromise]);
} finally {
clearTimeout(timeoutHandle!);
}
}
async sendOidbPacket (pkt: OidbPacket, rsp = false, timeout = 5000): Promise<RecvPacketData> {
@@ -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}`
);
}
+11 -2
View File
@@ -14,7 +14,7 @@ interface OffsetType {
const typedOffset: OffsetType = offset;
// 0 send 1 recv
export interface NativePacketExportType {
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => boolean;
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => string;
}
export type PacketType = 0 | 1; // 0: send, 1: recv
@@ -38,10 +38,15 @@ export class NativePacketHandler {
this.logger = logger;
try {
const platform = process.platform + '.' + process.arch;
if (!this.supportedPlatforms.includes(platform)) {
this.logger.logWarn(`NativePacketClient: 不支持的平台: ${platform}`);
return;
}
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/packet/MoeHoo.' + platform + '.node');
if (!fs.existsSync(moehoo_path)) {
this.logger.logWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
this.loaded = false;
return;
}
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
this.loaded = true;
@@ -213,9 +218,13 @@ export class NativePacketHandler {
return false;
}
this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
const result = this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
this.emitPacket(type, uin, cmd, seq, hex_data);
}, o3HookMode);
if (result !== 'success') {
this.logger.logError(`[PacketHandler] 初始化失败: ${result}`);
return false;
}
this.logger.log('[PacketHandler] 初始化成功');
return true;
} catch (error) {
@@ -3,5 +3,7 @@ import { TypedEventEmitter } from './typeEvent';
export interface AppEvents {
'event:emoji_like': { groupId: string; senderUin: string; emojiId: string, msgSeq: string, isAdd: boolean, count: number; };
KickedOffLine: string;
// 静默离线:服务端会话已失效,但没有下发 KickedOffLine 通知
SelfOffline: string;
}
export const appEvent = new TypedEventEmitter<AppEvents>();
@@ -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,
@@ -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[];
}
+2
View File
@@ -78,6 +78,7 @@ export interface WebApiGroupNoticeFeed {
remind_ts: number
tip_window_type: number
confirm_required: number
inst_no_pinned?: number // 仅 inst 条目有:0 = 置顶中,1 = 未置顶
};
read_num: number;
is_read: number;
@@ -92,6 +93,7 @@ export interface WebApiGroupNoticeRet {
read_only: number
role: number
feeds: WebApiGroupNoticeFeed[]
inst?: WebApiGroupNoticeFeed[] // 「发给新成员」类公告,不在 feeds 里
group: {
group_id: number
class_ext: number
+5 -1
View File
@@ -1 +1,5 @@
node.exe ./index.js
@echo off
setlocal
cd /d "%~dp0" || exit /b 1
"%~dp0node.exe" "%~dp0index.js" %*
exit /b %errorlevel%
+2 -1
View File
@@ -1,6 +1,7 @@
const process = require('process');
const os = require('os');
const path = require('path');
const { pathToFileURL } = require('url');
// 保存原始dlopen
const dlopenOrig = process.dlopen;
@@ -50,7 +51,7 @@ async function initializeNapCat () {
console.log('[NapCat] [Info] 开始初始化NapCat');
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework, getWebUiUrl } = await import('file://' + path.join(currentPath, './napcat.mjs'));
const { NCoreInitFramework, getWebUiUrl } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
getWebUiUrlFunc = getWebUiUrl;
await NCoreInitFramework(wrapperSession, wrapperLoginService, (callback) => { ncCallback = callback; });
} catch (error) {
+68 -1
View File
@@ -9,6 +9,7 @@ import { logSubscription, LogWrapper } from 'napcat-core/helper/log';
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
import { InstanceContext, loadQQWrapper, NapCatCore, NapCatCoreWorkingEnv, NodeIKernelLoginListener, NodeIKernelLoginService, NodeIQQNTWrapperSession, SelfInfo, WrapperNodeApi } from '@/napcat-core';
import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
import { statusHelperSubscription } from '@/napcat-core/helper/status';
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
@@ -105,6 +106,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 +126,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 +156,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 +209,44 @@ export async function NCoreInitFramework (
const oneBotAdapter = adapterManager.getOneBotAdapter();
if (oneBotAdapter) {
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
if (WebUiDataRuntime.getQQLoginStatus()) {
WebUiDataRuntime.setQQLoginPhase('ready');
}
}
// 监听下线并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
// KickedOffLine:账号被踢下线;SelfOffline:静默离线(服务端会话语义失效但无通知)。
// 两者复用同一条恢复链路:同步 WebUI -> 重启 Worker -> 快速登录。
const handleOffline = createOfflineRecovery({
isOnline: () => loaderObject.core.selfInfo.online === true,
onOffline: (tips) => {
WebUiDataRuntime.setQQLoginStatus(false);
// 下线后的二维码已失效,绝不能继续交给页面展示或扫码。
WebUiDataRuntime.setQQLoginQrcodeURL('');
WebUiDataRuntime.setQQLoginError(tips);
WebUiDataRuntime.setQQLoginPhase('reconnecting');
},
onRecovered: () => {
WebUiDataRuntime.setQQLoginStatus(true);
WebUiDataRuntime.setQQLoginError('');
WebUiDataRuntime.setQQLoginPhase('ready');
},
restart: async (tips) => {
try {
const restartResult = await WebUiDataRuntime.requestRestartProcess();
logger.logWarn('[NapCat] [Framework] 账号已离线,正在重启 Worker 以重新创建 QQ 登录服务', restartResult);
if (restartResult.result) return true;
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${restartResult.message}`);
} catch (error) {
WebUiDataRuntime.setQQLoginPhase('offline');
WebUiDataRuntime.setQQLoginError(`${tips}\n登录服务重启失败:${(error as Error).message}`);
}
return false;
},
});
loaderObject.core.event.on('KickedOffLine', (tips: string) => handleOffline(tips, false));
loaderObject.core.event.on('SelfOffline', (tips: string) => handleOffline(tips, true));
}
function registerWebUiLoginCallbacks (
@@ -204,7 +256,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 未接受二维码刷新请求');
}
});
// 快速登录
+2 -1
View File
@@ -1,5 +1,6 @@
// const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
async function initializeNapCat (session, loginService, registerCallback) {
// const logFile = path.join(currentPath, 'napcat.log');
@@ -12,7 +13,7 @@ async function initializeNapCat (session, loginService, registerCallback) {
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework } = await import('file://' + path.join(currentPath, './napcat.mjs'));
const { NCoreInitFramework } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
await NCoreInitFramework(session, loginService, (callback) => { registerCallback(callback); });
} catch (error) {
console.log('[NapCat] [Error] 初始化NapCat', error);
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
@@ -1,8 +1,10 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
set NAPCAT_DEBUG_CONSOLE=1
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
@@ -27,4 +29,4 @@ set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
pause
pause
+6 -4
View File
@@ -1,8 +1,10 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -24,4 +26,4 @@ if not exist "%QQpath%" (
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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
);
}
}
@@ -0,0 +1,66 @@
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 } from 'node:fs';
import { unlink } from 'node:fs/promises';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
files: Type.Array(Type.String(), { description: '图片路径、URL或Base64 数组,一次上传多张' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadImagesToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadImagesToQunAlbum;
override actionSummary = '上传多张图片到群相册';
override actionDescription = '一次上传多张图片,这些图片在群相册里显示为同一条上传';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
files: ['/path/to/1.jpg', '/path/to/2.jpg'],
};
override returnExample = {
result: null,
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
if (!payload.files.length) throw new Error('files 不能为空');
const localPaths: string[] = [];
const tempPaths: string[] = [];
try {
for (const file of payload.files) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
localPaths.push(downloadResult.path);
if (!downloadResult.isLocal && downloadResult.path) {
tempPaths.push(downloadResult.path);
}
}
return await this.core.apis.WebApi.uploadImagesToQunAlbum(
payload.group_id,
payload.album_id,
payload.album_name,
localPaths
);
} finally {
for (const path of tempPaths) {
if (existsSync(path)) {
await unlink(path);
}
}
}
}
}
@@ -0,0 +1,55 @@
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 } from 'node:fs';
import { unlink } from 'node:fs/promises';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
file: Type.String({ description: '视频路径、URL或Base64' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadVideoToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadVideoToQunAlbum;
override actionSummary = '上传视频到群相册';
override actionDescription = '上传视频到群相册,封面自动抽取首帧(失败时使用内置默认封面)';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
file: '/path/to/video.mp4',
};
override returnExample = {
result: null,
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
try {
return await this.core.apis.WebApi.uploadVideoToQunAlbum(
payload.group_id,
payload.album_id,
payload.album_name,
downloadResult.path
);
} finally {
if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
await unlink(downloadResult.path);
}
}
}
}
@@ -2,6 +2,7 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import path from 'node:path';
import { DEFAULT_FLASH_VALIDITY_SECONDS } from '@/napcat-core/data/flash';
const richMediaList = [
'.mp4', '.mov', '.avi', '.wmv', '.mpeg', '.mpg', '.flv', '.mkv',
@@ -15,6 +16,7 @@ export const CreateFlashTaskPayloadSchema = Type.Object({
], { description: '文件列表或单个文件路径' }),
name: Type.Optional(Type.String({ description: '任务名称' })),
thumb_path: Type.Optional(Type.String({ description: '缩略图路径' })),
validitySeconds: Type.Optional(Type.Number({ description: '文件集有效期(秒),可选 14 天 1209600 / 90 天 7776000 / 180 天 15552000,默认 1209600' })),
});
export type CreateFlashTaskPayload = Static<typeof CreateFlashTaskPayloadSchema>;
@@ -27,6 +29,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
override payloadExample = {
files: 'C:\\test.jpg',
name: 'test_task',
validitySeconds: DEFAULT_FLASH_VALIDITY_SECONDS,
};
override returnExample = {
@@ -67,6 +70,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
} else {
normalPath = toPlatformPath(thumbPath);
}
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '');
const validitySeconds = payload.validitySeconds ?? DEFAULT_FLASH_VALIDITY_SECONDS;
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '', validitySeconds);
}
}
@@ -55,7 +55,7 @@ export default class GetFriendMsgHistory extends OneBotAction<PayloadType, Retur
}));
// 烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
).filter((msg): msg is OB11Message => msg !== undefined);
return { messages: ob11MsgList };
}
@@ -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,
};
}
}
@@ -43,7 +43,8 @@ export class GetGroupFilesByFolder extends OneBotAction<PayloadType, ReturnType>
return {
files: ret.filter(item => item.fileInfo)
.map(item => OB11Construct.file(item.peerId, item.fileInfo!)),
folders: [],
folders: ret.filter(item => item.folderInfo)
.map(item => OB11Construct.folder(item.peerId, item.folderInfo!)),
};
}
}
@@ -26,7 +26,7 @@ export class SetQQProfile extends OneBotAction<SetQQProfilePayload, any> {
return await this.core.apis.UserApi.modifySelfProfile({
nick: payload.nickname,
longNick: (payload?.personal_note ?? OldProfile?.longNick) || '',
sex: parseInt(payload?.sex ? payload?.sex.toString() : OldProfile?.sex!.toString()),
sex: parseInt(payload.sex != null && payload.sex !== '' ? payload.sex.toString() : OldProfile?.sex!.toString()),
birthday: {
birthday_year: OldProfile?.birthday_year!.toString(),
birthday_month: OldProfile?.birthday_month!.toString(),
@@ -48,7 +48,7 @@ export default class DelEssenceMsg extends OneBotAction<PayloadType, ReturnType>
const data = this.core.apis.GroupApi.essenceLRU.getValue(+payload.message_id);
if (!data) throw new Error('消息不存在');
const { msg_seq, msg_random, group_id } = JSON.parse(data) as { msg_seq: string, msg_random: string, group_id: string; };
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_seq, msg_random);
return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_random, msg_seq);
}
return await this.core.apis.GroupApi.removeGroupEssence(
msg.Peer.peerUid,
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more