Fix merge conflict and remove one group avatar implement

This commit is contained in:
H3CoF6 committed 2026-05-16 12:39:00 +08:00
commit 16bdf1be1e
111 files changed
+6830 -2916

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
# 贡献者公约 (Contributor Covenant Code of Conduct)
本文档改编自 [Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/),是 SnowLuma 社区共同遵守的行为准则。
## 我们的承诺
身为社区成员、贡献者、维护者,我们承诺:让每一个参与 SnowLuma 项目和社区的人,不因年龄、体型、可见或不可见的身体差异、身心障碍、族裔、性别特征、性别认同与表达、经验水平、教育背景、社会经济地位、国籍、外貌、种族、宗教信仰、或性取向,而遭受骚扰。
我们承诺以营造开放、热情、多元、包容、健康社区的方式行事和互动。
## 我们的准则
有助于建立正向社区环境的行为包括但不限于:
- 对他人展现同理心与善意
- 尊重不同的意见、观点与经验
- 给予并优雅地接受建设性反馈
- 承担责任并向受我们错误影响的人致歉,并从中吸取教训
- 关注的不仅是个人,更是整个社区的最大利益
不可接受的行为包括但不限于:
- 使用情色化的语言或意象,及任何形式的性关注或性骚扰
- 嘲讽、侮辱或贬损性的评论,以及人身或政治攻击
- 公开或私下的骚扰
- 未经明确许可,公布他人的私人信息,例如物理或电子邮件地址
- 其他在专业场合中可被合理认定为不当的行为
## 适用范围
本行为准则适用于所有社区场所,也适用于个人在公开场合代表社区时的言行。代表本社区的情形包括但不限于:使用项目官方电子邮件地址、通过项目官方社交媒体账号发文、以指定代表身份出席线上或线下活动。
具体到 SnowLuma,本准则适用于:
- 本仓库(含 issue、PR、discussion、commit message、code review 评论)
- 项目相关的 QQ 群、Telegram 群以及未来可能新增的官方社群
- 任何以 SnowLuma 名义对外发起的活动或交流
## 执行责任
社区维护者负责诠释并执行我们所认定的可接受行为标准,并将对任何他们认为不当、具威胁性、冒犯性或有害的行为采取适当且公正的纠正措施。
社区维护者有权且有责任删除、编辑或拒绝任何不符合本行为准则的评论、提交、代码、wiki 编辑、issue 及其他贡献,并将在适当时机说明做出审核决策的理由。
## 举报方式
如果你目击或亲身经历了不当行为,请通过以下任一渠道**私下**联系维护者:
- QQ:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)(私聊管理员,请勿在群内公开)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)(私聊管理员)
请勿在 GitHub issue 或公开频道直接发布举报内容,以免对相关方造成二次伤害。
所有投诉都会被及时和公平地审查与调查。所有社区维护者都有义务尊重举报者的隐私与人身安全。
## 执行准则
社区维护者将依据以下「社区影响指引」来判定违反本行为准则之行为的处置方式:
### 1. 更正 (Correction)
**社区影响**:使用了不恰当的言语,或其他在社区中被视为不专业或不受欢迎的行为。
**后果**:由社区维护者私下提出书面警告,明确指出该行为违反规则之处并解释为何不妥。可能要求公开致歉。
### 2. 警告 (Warning)
**社区影响**:通过单一事件或一系列行为造成违规。
**后果**:警告并说明持续行为的后果。在指定时间内禁止与相关人员互动,包括主动联系本行为准则执行者。这包括避免在社区场所及外部渠道(如社交媒体)的互动。违反这些条款可能导致临时或永久封禁。
### 3. 临时封禁 (Temporary Ban)
**社区影响**:严重违反社区准则,包括持续的不当行为。
**后果**:在指定时间内禁止与社区进行任何形式的互动或公开交流。在此期间不得与相关人员有任何公开或私下的互动,包括主动联系本行为准则执行者。违反这些条款可能导致永久封禁。
### 4. 永久封禁 (Permanent Ban)
**社区影响**:表现出违反社区准则的模式,包括持续的不当行为、骚扰个人、或对某类群体进行攻击或贬低。
**后果**:永久禁止在社区内进行任何形式的公开互动。
## 致谢
本行为准则改编自 [Contributor Covenant 2.1 版](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html)。
社区影响指引灵感来自 [Mozilla 的行为准则执行阶梯](https://github.com/mozilla/diversity)。
如需了解本准则的常见问题,请参阅 [FAQ](https://www.contributor-covenant.org/faq)。中文版译本可参考 [Contributor Covenant 中文翻译](https://www.contributor-covenant.org/zh-cn/version/2/1/code_of_conduct/)。
+212 -31
View File
@@ -1,49 +1,233 @@
# 贡献指南
## 分支模型
欢迎!如果你正在阅读这份文档,多半是因为你想给 SnowLuma 提一个 PR、修一个 bug,或者只是想了解这个项目是怎么运作的。无论你是第一次接触开源、还是已经有十年经验,我们都希望让你尽快上手。
参与项目即视为你同意遵守 [行为准则(Code of Conduct)](./CODE_OF_CONDUCT.md)。在开始之前请花两分钟读一下,它定义了我们希望社区维持的氛围。
---
## 在动手之前
SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时可能变化**。如果你打算做较大的改动,强烈建议先在 issue 或者社群里和维护者对齐一下方向,避免做了一半发现已经被另一条路替代。
不知道从哪里入手?以下几类贡献最容易被合并:
- 修复你在使用中遇到的具体 bug,附最小复现步骤。
- 改善错误提示、文档、注释、类型签名。
- 给已有模块补测试,尤其是 `packages/core` 下覆盖率较低的部分。
- 实现 [RoadMap.md](./RoadMap.md) 中列出的、还没被认领的项。
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
---
## 项目结构速览
这是一个 pnpm workspace monorepo,主要 package 如下:
| 路径 | 作用 |
| --- | --- |
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
| `packages/runtime` | 运行时辅助包 |
| `packages/websocket` | WebSocket 实现 |
| `packages/webui` | 基于 Vite + React 的前端控制台 |
| `tools/` | 版本管理、发布脚本 |
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
---
## 本地开发环境
### 系统要求
- **Node.js ≥ 22**(`engines` 字段强制,低版本会报错)
- **pnpm 10.28.0+**(项目通过 `packageManager` 字段锁定,建议用 `corepack enable` 安装匹配版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
### 拉代码、装依赖、跑起来
```bash
# 1. Fork 仓库后克隆你自己的 fork
git clone https://github.com/<你的用户名>/SnowLuma.git
cd SnowLuma
# 2. 切到 dev 分支(所有开发都基于 dev,不是 main)
git checkout dev
# 3. 安装依赖
pnpm install
# 4. 跑类型检查,确认环境 OK
pnpm typecheck
# 5. 跑测试
pnpm test
# 6. 启动开发模式
pnpm dev # core
pnpm dev:web # webui
```
如果 `pnpm install` 卡住或报错,先确认 Node 版本和 pnpm 版本,再看 `.npmrc` 里是否配置了你环境下可用的 registry。
---
## 第一次提交 PR
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
```bash
git checkout dev
git pull upstream dev # 假设你把官方仓库设为 upstream remote
git checkout -b fix/onebot-mention-encoding
```
分支命名没有强制规则,但建议用 `fix/...`、`feat/...`、`docs/...`、`refactor/...` 这种前缀,便于一眼看出意图。
### 2. 写代码
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
提交之前请本地跑一遍:
```bash
pnpm typecheck
pnpm test
```
CI 上跑的是同一套检查,本地通过几乎能保证 CI 通过。
### 3. 提交信息
我们大致遵循 [Conventional Commits](https://www.conventionalcommits.org/zh-hans/v1.0.0/):
```
<type>(<scope>): <subject>
<body>
```
`type` 常用:`feat` / `fix` / `docs` / `refactor` / `test` / `chore` / `perf`。
`scope` 常用:`core` / `sdk` / `webui` / `onebot` / `bridge` / `protocol` 等模块名。
示例:
```
fix(onebot): handle empty mention segments in group messages
refactor(bridge): extract BridgeInterface as the OneBot-facing seam
docs: clarify dev environment setup steps
```
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
### 4. 推送并发起 PR
```bash
git push origin fix/onebot-mention-encoding
```
到 GitHub 上发起 PR,**目标分支选 `dev`**。请在 PR 描述里写明:
- 这个 PR 解决什么问题 / 实现什么功能。
- 主要的实现思路(如果有非显然的取舍)。
- 测试方式(你跑了什么、怎么验证有效)。
- 关联的 issue(如有)。
### 5. Code Review 与合并
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
---
## 风格与约定
### 代码风格
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
### 测试
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
### 文档
- 用户/贡献者可见的行为变化,需要相应更新 README 或对应 package 下的文档。
- SDK 的破坏性变更必须更新 `packages/sdk/CHANGELOG.md` 和 `packages/sdk/VERSIONING.md`。
---
## 报告 Bug / 请求功能
- **Bug 报告**:开 issue,附最小复现步骤、期望行为、实际行为、版本号、运行环境。能附上日志最好。
- **功能请求**:先描述你想解决的实际场景,再描述你想要的接口。维护者更在意"为什么需要"而不是"具体怎么做"。
- **安全问题**:请勿公开发 issue,先通过社群私聊联系维护者。
社群入口(见 [README](./README.md)):
- QQ:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
---
## 维护者参考:release & 自动合并流程
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
### 分支模型
SnowLuma 使用 **`main` + `dev`** 双分支模型:
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先提交到 `dev`。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
## 把 `dev` 合并到 `main`
### 把 `dev` 合并到 `main`
新增工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。三种触发方式:
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
无论使用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
### 1. 提交信息前缀(推荐日常使用)
#### 1. 提交信息前缀(推荐日常使用)
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
> 注意:是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
### 2. 推送 `chore.*` Tag
#### 2. 推送 `chore.*` Tag
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发本工作流。这是和发布 tag 解耦的「合并触发 tag」:
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
- `v*` → 仅触发 `release.yml`(构建发布产物)
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已经过完所有检查的 `main` HEAD 构建。
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
### 3. 手动触发
#### 3. 手动触发
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
工作流会按照当前 `dev` 与 `main` 的差异开 / 更新 PR。
### 启用 `main` 分支保护(必做)
## 启用 `main` 分支保护(必做)
仓库管理员需要在 GitHub 上为 `main` 配置一条规则集(Repository Rules)或经典分支保护,至少满足:
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
2. 选择 `main` 作为目标分支。
@@ -62,7 +246,7 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
## 必需的 Secrets
### 必需的 Secrets
`promote-dev-to-main.yml` 复用 `SnowLumaNative/build-native.yml` 同一个 GitHub App。请确认 SnowLuma 仓库(或 organization)级别已经配置:
@@ -71,22 +255,9 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
## 本地工作流速查
### 本地工作流速查(维护者)
```bash
# 切到 dev 开发
git checkout dev
git pull
# 写代码 / 跑测试
pnpm install
pnpm typecheck
pnpm -s --filter @snowluma/core test
# 普通提交(不会触发 promote)
git commit -m "fix: something"
git push
# 把 dev 合入 main(三选一)
# 方式 A:commit-msg 前缀
@@ -104,3 +275,13 @@ git checkout main && git pull
git tag v1.7.0
git push origin v1.7.0 # → 仅触发 release.yml
```
---
## 还有问题?
- 看一下已有的 issue 和 PR,可能你的问题已经被讨论过。
- 去社群问一句(QQ / TG 链接见上方)。
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.7.9",
"version": "1.8.1",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -17,7 +17,8 @@
"typecheck": "pnpm -r --if-present typecheck",
"lint": "pnpm -r --if-present lint",
"start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs"
"bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
},
"devDependencies": {
"cross-env": "^10.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.7.9",
"version": "1.8.1",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+155
View File
@@ -0,0 +1,155 @@
// Tier-2 napcat-parity actions ported as pure oidb calls. Each function
// here corresponds to one napcat PacketApi.pkt.operation.* entry; the
// schemas live in proto/oidb-action.ts. Nothing in this file touches
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbGroupTodoSchema,
OidbStrangerStatusReqSchema,
OidbStrangerStatusRespSchema,
OidbAiVoiceListReqSchema,
OidbAiVoiceListRespSchema,
OidbAiVoiceReqSchema,
OidbAiVoiceRespSchema,
} from '../proto/oidb-action';
import type { MediaIndexNode } from './shared';
// ─────────────── Group todo (0xF90) ───────────────
export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_1',
oidbCmd: 0xF90, subCmd: 1,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_2',
oidbCmd: 0xF90, subCmd: 2,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_3',
oidbCmd: 0xF90, subCmd: 3,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
export interface StrangerStatus {
status: number;
ext_status: number;
}
/**
* Mirror napcat's GetStrangerStatus: decode the extBigInt status word.
* Values ≤10 fold into a 10×status; everything else is split into the
* high-byte / low-byte ext_status the OneBot dialect uses.
*
* Returns null on transport / decode failure rather than throwing, so
* the OneBot action can produce a clean retcode without try/catch
* gymnastics.
*/
export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<StrangerStatus | null> {
try {
const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
},
response: { schema: OidbStrangerStatusRespSchema },
});
const raw = resp?.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
if (extBig <= 10n) {
return { status: Number(extBig) * 10, ext_status: 0 };
}
const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
return { status: 10, ext_status: status };
} catch {
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export async function fetchAiVoiceList(
bridge: Bridge,
groupId: number,
chatType: AiVoiceChatType,
): Promise<AiVoiceCategory[]> {
const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929d_0',
oidbCmd: 0x929D, subCmd: 0,
request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } },
response: { schema: OidbAiVoiceListRespSchema },
});
return resp?.content ?? [];
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* `bridge.fetchGroupPttUrlByNode`, which already handles every other
* download-URL fetch in SnowLuma.
*/
export async function fetchAiVoice(
bridge: Bridge,
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const resp = await runOidb<{
statusCode?: number;
msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> };
}>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929b_0',
oidbCmd: 0x929B, subCmd: 0,
request: {
schema: OidbAiVoiceReqSchema,
value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
},
response: { schema: OidbAiVoiceRespSchema },
});
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index;
if (node) return node;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
+5 -5
View File
@@ -7,7 +7,7 @@ import type { Bridge } from '../bridge';
import { gunzipSync, gzipSync } from 'zlib';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { buildSendElems } from '../element-builder';
import { parseMsgPush } from '../msg-push-handler';
import { parseMsgPush } from '../msg-push';
import type { ForwardNodePayload } from '../events';
import type { PacketInfo } from '../../protocol/types';
import {
@@ -29,7 +29,7 @@ async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
): Promise<Record<string, unknown>> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.qqInfo.uin);
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin);
@@ -41,7 +41,7 @@ async function buildForwardPushBody(
return {
responseHead: {
fromUin,
toUid: bridge.qqInfo.selfUid ?? '',
toUid: bridge.identity.selfUid ?? '',
forward: {
friendName: nickname,
},
@@ -173,14 +173,14 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const pkt: PacketInfo = {
pid: 0,
uin: bridge.qqInfo.uin,
uin: bridge.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: wrapped,
};
const events = parseMsgPush(pkt, bridge.qqInfo);
const events = parseMsgPush(pkt, bridge.identity);
const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue;
+33 -22
View File
@@ -3,7 +3,7 @@
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
@@ -13,32 +13,40 @@ import {
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await resolveUserUid(bridge, parseInt(uidOrFlag, 10));
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
}
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb5d_44', 0xB5D, 44,
{ accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb5d_44',
oidbCmd: 0xB5D, subCmd: 44,
request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } },
});
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await resolveUserUid(bridge, userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0,
{
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
const targetUid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x126b_0',
oidbCmd: 0x126B, subCmd: 0,
request: {
schema: OidbDeleteFriendSchema,
value: {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
block,
field4: false,
},
},
OidbDeleteFriendSchema);
});
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
@@ -47,7 +55,10 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2,
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema);
const uid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb6e_2',
oidbCmd: 0xB6E, subCmd: 2,
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
});
}
+107 -44
View File
@@ -4,7 +4,7 @@
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
@@ -26,26 +26,50 @@ import {
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1,
{ groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1253_1',
oidbCmd: 0x1253, subCmd: 1,
request: {
schema: OidbMuteMemberSchema,
value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } },
},
});
}
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
});
}
// ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0AddOptionSchema,
value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 },
},
});
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0,
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0SearchSchema,
value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 },
},
});
}
export async function setGroupAddRequest(
@@ -54,53 +78,92 @@ export async function setGroupAddRequest(
): Promise<void> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await sendOidbAndCheck(bridge, cmd, 0x10C8, subCmd,
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
OidbGroupRequestActionSchema, true);
await runOidb(bridge, {
cmd,
oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
}
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: OidbKickMemberSchema,
value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason },
},
});
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => resolveUserUid(bridge, userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema);
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: Oidb0x8a0ReqSchema,
value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 },
},
});
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1,
{ groupUin: groupId }, OidbLeaveGroupSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
}
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1,
{ groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1096_1',
oidbCmd: 0x1096, subCmd: 1,
request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } },
});
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3,
{ groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_3',
oidbCmd: 0x8FC, subCmd: 3,
request: {
schema: OidbRenameMemberSchema,
value: { groupUin: groupId, body: { targetUid: uid, targetName: card } },
},
});
}
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_15', 0x89A, 15,
{ groupUin: groupId, body: { targetName: name } }, OidbRenameGroupSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_15',
oidbCmd: 0x89A, subCmd: 15,
request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } },
});
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2,
{ groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema);
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
});
}
// ─────────────── personal-side metadata ───────────────
@@ -109,8 +172,11 @@ export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, user
// here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1,
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
}
// ─────────────── group-level quota query ───────────────
@@ -123,20 +189,17 @@ export async function getGroupAtAllRemain(
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.qqInfo.uin),
uin: BigInt(bridge.identity.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x8a7_0',
0x8A7,
0,
req,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a7_0',
oidbCmd: 0x8A7, subCmd: 0,
request: { schema: Oidb0x8a7ReqSchema, value: req },
response: { schema: Oidb0x8a7RespSchema },
});
if (!result) {
throw new Error('get group at all remain result empty');
+201 -200
View File
@@ -7,7 +7,7 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import {
@@ -27,6 +27,7 @@ import {
NTV2RichMediaRespSchema,
} from '../proto/oidb-action';
import { FileUploadExtSchema } from '../proto/highway';
import { toHexUpper } from '../../utils/hex';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
// ─────────────── public result types ───────────────
@@ -76,7 +77,7 @@ function normalizeDirectory(dir?: string): string {
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return Buffer.from(data).toString('hex').toUpperCase();
return toHexUpper(data);
}
function normalizeUploadFileName(name: string, fallback: string): string {
@@ -241,16 +242,12 @@ async function fetchNtv2DownloadUrl(
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const resp = await sendOidbAndDecode<any>(
bridge,
serviceCmd,
oidbCmd,
200,
payload,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
true,
);
const resp = await runOidb<any>(bridge, {
cmd: serviceCmd,
oidbCmd, subCmd: 200,
request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
@@ -266,11 +263,15 @@ async function fetchNtv2DownloadUrl(
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await sendOidbAndDecode<any>(bridge,
'OidbSvcTrpcTcp.0x6d8_3', 0x6D8, 3,
{ count: { groupUin: groupId, appId: 7, busId: 0 } },
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_3',
oidbCmd: 0x6D8, subCmd: 3,
request: {
schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
@@ -293,31 +294,31 @@ export async function uploadGroupFile(
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_0',
0x6D6,
0,
{
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_0',
oidbCmd: 0x6D6, subCmd: 0,
request: {
schema: OidbGroupFileReqSchema,
value: {
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
@@ -327,7 +328,7 @@ export async function uploadGroupFile(
if (!fileId) throw new Error('group file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(bridge.qqInfo.uin);
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
@@ -368,48 +369,48 @@ export async function uploadPrivateFile(
const loaded = await loadBinarySource(source, 'file');
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await resolveUserUid(bridge, userId);
let selfUid = bridge.qqInfo.selfUid;
const targetUid = await bridge.resolveUserUid(userId);
let selfUid = bridge.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(bridge.qqInfo.uin);
const selfUin = toInt(bridge.identity.uin);
if (selfUin > 0) {
selfUid = await resolveUserUid(bridge, selfUin);
selfUid = await bridge.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(bridge.qqInfo.uin);
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1700',
0xE37,
1700,
{
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1700',
oidbCmd: 0xE37, subCmd: 1700,
request: {
schema: OidbPrivateFileUploadReqSchema,
value: {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
);
response: { schema: OidbPrivateFileUploadRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing');
@@ -458,27 +459,27 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d8_1',
0x6D8,
1,
{
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_1',
oidbCmd: 0x6D8, subCmd: 1,
request: {
schema: OidbGroupFileViewReqSchema,
value: {
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
},
isUid: true,
},
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
true,
);
response: { schema: OidbGroupFileViewRespSchema },
});
const list = resp?.list;
if (!list) break;
@@ -489,7 +490,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
const uploader = toInt(file.uploaderUin);
const cached = bridge.qqInfo.findGroupMember(groupId, uploader);
const cached = bridge.identity.findGroupMember(groupId, uploader);
files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '',
@@ -508,7 +509,7 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
} else if (type === 2 && item?.folderInfo) {
const folder = item.folderInfo;
const creator = toInt(folder.creatorUin);
const cached = bridge.qqInfo.findGroupMember(groupId, creator);
const cached = bridge.identity.findGroupMember(groupId, creator);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
@@ -533,23 +534,23 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
// ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_2',
0x6D6,
2,
{
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_2',
oidbCmd: 0x6D6, subCmd: 2,
request: {
schema: OidbGroupFileReqSchema,
value: {
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
@@ -568,30 +569,30 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
}
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await resolveUserUid(bridge, userId);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1200',
0xE37,
1200,
{
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
const uid = await bridge.resolveUserUid(userId);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1200',
oidbCmd: 0xE37, subCmd: 1200,
request: {
schema: OidbPrivateFileDownloadReqSchema,
value: {
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
);
response: { schema: OidbPrivateFileDownloadRespSchema },
});
const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : '';
@@ -606,22 +607,22 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId
// ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_3',
0x6D6,
3,
{
delete: {
groupUin: groupId,
busId: 102,
fileId,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_3',
oidbCmd: 0x6D6, subCmd: 3,
request: {
schema: OidbGroupFileReqSchema,
value: {
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group file delete response missing');
@@ -635,25 +636,25 @@ export async function moveGroupFile(
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d6_5',
0x6D6,
5,
{
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_5',
oidbCmd: 0x6D6, subCmd: 5,
request: {
schema: OidbGroupFileReqSchema,
value: {
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
isUid: true,
},
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
true,
);
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.move;
if (!result) throw new Error('group file move response missing');
@@ -663,22 +664,22 @@ export async function moveGroupFile(
// ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_0',
0x6D7,
0,
{
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_0',
oidbCmd: 0x6D7, subCmd: 0,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
isUid: true,
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.create;
if (!result) throw new Error('group folder create response missing');
@@ -686,21 +687,21 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam
}
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_1',
0x6D7,
1,
{
delete: {
groupUin: groupId,
folderId,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_1',
oidbCmd: 0x6D7, subCmd: 1,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
delete: {
groupUin: groupId,
folderId,
},
},
isUid: true,
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing');
@@ -708,22 +709,22 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol
}
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x6d7_2',
0x6D7,
2,
{
rename: {
groupUin: groupId,
folderId,
newFolderName,
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_2',
oidbCmd: 0x6D7, subCmd: 2,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
isUid: true,
},
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
true,
);
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing');
@@ -5,7 +5,7 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
@@ -28,7 +28,7 @@ export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number,
): Promise<void> {
const targetUid = await resolveUserUid(bridge, userUin);
const targetUid = await bridge.resolveUserUid(userUin);
const request = protoEncode({
type: 1,
targetUid,
@@ -53,7 +53,7 @@ export async function markPrivateMessageRead(
msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
const uid = await bridge.resolveUserUid(userId);
const request = protoEncode({
c2cList: [
@@ -96,6 +96,9 @@ export async function markGroupMessageRead(
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await sendOidbAndCheck(bridge, cmd, 0xEAC, subCmd,
{ groupUin: groupId, sequence, random }, OidbEssenceSchema);
await runOidb(bridge, {
cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
}
+38 -13
View File
@@ -3,7 +3,7 @@
// edit message content — they're purely social signals.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
@@ -13,25 +13,45 @@ import {
} from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xed3_1', 0xED3, 1,
{
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
}, OidbPokeSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xed3_1',
oidbCmd: 0xED3, subCmd: 1,
request: {
schema: OidbPokeSchema,
value: {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
},
},
});
}
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104,
{ targetUin: userId, count }, OidbLikeSchema);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7e5_104',
oidbCmd: 0x7E5, subCmd: 104,
request: { schema: OidbLikeSchema, value: { targetUin: userId, count } },
});
}
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd,
{ groupUin: groupId, sequence, code }, OidbGroupReactionSchema);
// Same heuristic NapCat uses: QQ face ids are 1–3 digits ("76"),
// unicode codepoints are longer ("128516"). Server requires the
// type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1;
await runOidb(bridge, {
cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
}
export async function getEmojiLikes(
@@ -53,7 +73,12 @@ export async function getEmojiLikes(
count,
field12: 1,
};
const resp = await sendOidbAndDecode<any>(bridge, 'OidbSvcTrpcTcp.0x9083_1', 0x9083, 1, req, Oidb0x9083ReqSchema, Oidb0x9083RespSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9083_1',
oidbCmd: 0x9083, subCmd: 1,
request: { schema: Oidb0x9083ReqSchema, value: req },
response: { schema: Oidb0x9083RespSchema },
});
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
+20 -29
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
MiniAppShareReqSchema,
MiniAppShareRespSchema,
@@ -30,15 +30,12 @@ export async function translateEn2Zh(
tag12: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x990_2',
0x990,
2,
req,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x990_2',
oidbCmd: 0x990, subCmd: 2,
request: { schema: Oidb0x990ReqSchema, value: req },
response: { schema: Oidb0x990RespSchema },
});
const resp = result?.translateResp;
if (!resp) {
@@ -125,15 +122,12 @@ export async function clickInlineKeyboardButton(
unknown9: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112e_1',
0x112E,
1,
req,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112e_1',
oidbCmd: 0x112E, subCmd: 1,
request: { schema: Oidb0x112eReqSchema, value: req },
response: { schema: Oidb0x112eRespSchema },
});
if (!result) {
throw new Error('click inline keyboard button result empty');
@@ -155,19 +149,16 @@ export async function sendGroupSign(
) {
const req = {
signInInfo: {
uin: String(bridge.qqInfo.uin),
uin: String(bridge.identity.uin),
groupId: String(groupId),
version: '9.0.90',
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xEB7_1',
0xEB7,
1,
req,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
);
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xEB7_1',
oidbCmd: 0xEB7, subCmd: 1,
request: { schema: Oidb0xeb7ReqSchema, value: req },
response: { schema: Oidb0xeb7RespSchema },
});
}
+101 -57
View File
@@ -4,12 +4,13 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
FaceroamOpReqSchema,
FaceroamOpRespSchema,
GroupAvatarExtraSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0x7edReqSchema,
@@ -32,11 +33,39 @@ export async function setOnlineStatus(
extStatus: number = 0,
batteryStatus: number = 100,
): Promise<void> {
const request = protoEncode({
status,
extStatus,
batteryStatus,
}, SetStatusReqSchema);
await dispatchSetStatus(bridge, { status, extStatus, batteryStatus });
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
export async function setDiyOnlineStatus(
bridge: Bridge,
faceId: number,
wording: string,
faceType: number,
): Promise<void> {
await dispatchSetStatus(bridge, {
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
async function dispatchSetStatus(
bridge: Bridge,
value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
},
): Promise<void> {
const request = protoEncode(value, SetStatusReqSchema);
const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request);
@@ -60,7 +89,7 @@ export async function setProfile(
nickname?: string,
personalNote?: string,
): Promise<void> {
const uin = BigInt(bridge.qqInfo.uin);
const uin = BigInt(bridge.identity.uin);
const stringProfiles: any[] = [];
const intProfiles: any[] = [];
@@ -81,14 +110,11 @@ export async function setProfile(
stringProfiles,
};
await sendOidbAndCheck(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
OidbSetProfileSchema,
);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: OidbSetProfileSchema, value: req },
});
}
export async function setSelfLongNick(
@@ -96,22 +122,19 @@ export async function setSelfLongNick(
longNick: string,
) {
const req = {
uin: BigInt(bridge.qqInfo.uin),
uin: BigInt(bridge.identity.uin),
profile: {
tag: 102,
value: String(longNick),
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
);
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: Oidb0x112aReqSchema, value: req },
response: { schema: Oidb0x112aRespSchema },
});
}
export async function setInputStatus(
@@ -119,7 +142,7 @@ export async function setInputStatus(
userId: number,
eventType: number,
) {
const targetUid = await resolveUserUid(bridge, userId);
const targetUid = await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
@@ -133,15 +156,12 @@ export async function setInputStatus(
},
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xcd4_1',
0xCD4,
1,
req,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
);
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xcd4_1',
oidbCmd: 0xCD4, subCmd: 1,
request: { schema: Oidb0xcd4ReqSchema, value: req },
response: { schema: Oidb0xcd4RespSchema },
});
}
export async function setAvatar(
@@ -156,6 +176,36 @@ export async function setAvatar(
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
}
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
export async function setGroupAvatar(
bridge: Bridge,
groupId: number,
source: string,
): Promise<void> {
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protoEncode({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
}, GroupAvatarExtraSchema);
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
export async function getProfileLike(
@@ -167,7 +217,7 @@ export async function getProfileLike(
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, userId);
: await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
@@ -182,15 +232,12 @@ export async function getProfileLike(
limit: limit,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x7ed_12',
0x7ED,
12,
req,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7ed_12',
oidbCmd: 0x7ED, subCmd: 12,
request: { schema: Oidb0x7edReqSchema, value: req },
response: { schema: Oidb0x7edRespSchema },
});
const data = result?.userLikeInfos?.[0];
if (!data) {
@@ -220,7 +267,7 @@ export async function getUnidirectionalFriendList(
bridge: Bridge,
) {
const reqObj = {
uint64_uin: String(bridge.qqInfo.uin),
uint64_uin: String(bridge.identity.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
@@ -230,15 +277,12 @@ export async function getUnidirectionalFriendList(
jsonBody: JSON.stringify(reqObj),
};
const result = await sendOidbAndDecode<any>(
bridge,
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
0xE17,
0,
req,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
);
const result = await runOidb<any>(bridge, {
cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
oidbCmd: 0xE17, subCmd: 0,
request: { schema: Oidb0xe17ReqSchema, value: req },
response: { schema: Oidb0xe17RespSchema },
});
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
@@ -251,7 +295,7 @@ export async function getUnidirectionalFriendList(
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.qqInfo.uin),
uin: BigInt(bridge.identity.uin),
field3: 1,
field6: 1,
};
@@ -265,5 +309,5 @@ export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promi
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
}
const faceIds = (resp as any).item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.qqInfo.uin}/${id}/0`);
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`);
}
+6 -6
View File
@@ -3,7 +3,6 @@
// same five-line utility from every themed file.
import type { Bridge } from '../bridge';
import { resolveUserUid } from '../bridge-oidb';
/**
* Coerce numbers, strings, and bigints to a plain integer.
@@ -37,18 +36,19 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
}
/**
* Look up the bot's own UID. Cached on QQInfo when warmed up, but
* forward/profile actions need a fast path before warmup completes.
* Look up the bot's own UID. Cached on Identity once warmup populates
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.qqInfo.selfUid;
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.qqInfo.uin);
const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await resolveUserUid(bridge, selfUin);
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
+37 -19
View File
@@ -4,7 +4,7 @@ import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode';
import { sendOidbAndDecode } from './bridge-oidb';
import { runOidb } from './bridge-oidb';
import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
@@ -71,9 +71,12 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
body.nextUin = { uin: nextUin };
}
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body,
OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfd4_1',
oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
if (resp?.friends) {
for (const raw of resp.friends) {
@@ -121,9 +124,12 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
},
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body,
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe5_2',
oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
@@ -165,9 +171,12 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
};
if (token) body.token = token;
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body,
OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe7_3',
oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
if (resp?.members) {
for (const raw of resp.members) {
@@ -205,9 +214,12 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
keys: keys.map(k => ({ key: k })),
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body,
OidbUserInfoRequestSchema, OidbUserInfoResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
response: { schema: OidbUserInfoResponseSchema },
});
if (!resp?.body) throw new Error('user info response body missing');
@@ -259,9 +271,12 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await sendOidbAndDecode<any>(
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 },
OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema);
const resp = await runOidb<any>(bridge, {
cmd,
oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) {
@@ -308,9 +323,12 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyIn
},
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body,
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9067_202',
oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
@@ -0,0 +1,152 @@
// BridgeInterface — the surface OneBot (and any other external consumer)
// is allowed to see. The concrete Bridge class additionally exposes raw
// protocol primitives (sendRawPacket, packet dispatch, PID management)
// used by the in-tree action / contacts / highway modules; those internal
// methods deliberately do NOT appear here so that callers depending on
// the interface stay decoupled from the wire format.
//
// Every method below has a matching signature on Bridge; `Bridge
// implements BridgeInterface` is the compile-time enforcement.
import type { BridgeEventBus } from './event-bus';
import type { IdentityService } from './identity-service';
import type {
FriendInfo, QQGroupInfo, GroupMemberInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import type { MessageElement, ForwardNodePayload } from './events';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import type { WebHonorType } from './web/group-honor';
import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
export interface BridgeInterface {
// ─── Shared state ───
readonly identity: IdentityService;
readonly events: BridgeEventBus;
readonly activePid: number | null;
// ─── Resolution ───
resolveUserUid(uin: number, groupId?: number): Promise<string>;
// ─── Raw packet (deliberate escape hatch for `send_packet` action) ───
// OneBot clients use this to debug or invoke commands SnowLuma has no
// typed wrapper for. Every other method on this interface eventually
// routes through here.
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
// ─── Send (messages) ───
sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
// ─── Fetch (contacts / profile / system) ───
fetchFriendList(): Promise<FriendInfo[]>;
fetchGroupList(): Promise<QQGroupInfo[]>;
fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise<GroupMemberInfo[]>;
fetchUserProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupRequests(filtered?: boolean): Promise<GroupRequestInfo[]>;
fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]>;
// ─── Group admin ───
muteGroupMember(groupId: number, userId: number, duration: number): Promise<void>;
muteGroupAll(groupId: number, enable: boolean): Promise<void>;
setGroupAddOption(groupId: number, addType: number): Promise<void>;
setGroupSearch(groupId: number): Promise<void>;
setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason?: string, filtered?: boolean): Promise<void>;
kickGroupMember(groupId: number, userId: number, reject: boolean, reason?: string): Promise<void>;
kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void>;
leaveGroup(groupId: number): Promise<void>;
setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void>;
setGroupCard(groupId: number, userId: number, card: string): Promise<void>;
setGroupName(groupId: number, name: string): Promise<void>;
setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void>;
setGroupRemark(groupId: number, remark: string): Promise<void>;
setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void>;
setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void>;
// ─── Friend ───
setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void>;
deleteFriend(userId: number, block?: boolean): Promise<void>;
setFriendRemark(userId: number, remark: string): Promise<void>;
// ─── Files ───
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
fetchGroupFiles(groupId: number, folderId?: string): Promise<GroupFilesResult>;
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string>;
fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string>;
deleteGroupFile(groupId: number, fileId: string): Promise<void>;
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void>;
createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise<void>;
deleteGroupFileFolder(groupId: number, folderId: string): Promise<void>;
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Group Album ───
getGroupAlbumList(groupId: number): Promise<any>;
uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void>;
getGroupAlbumMediaList(groupId: number, albumId: string): Promise<any>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
// ─── Message ops ───
recallGroupMessage(groupId: number, sequence: number): Promise<void>;
recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void>;
markGroupMsgAsRead(groupId: number, sequence: number): Promise<void>;
markPrivateMsgAsRead(userId: number, sequence: number): Promise<void>;
// ─── Interaction ───
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void>;
sendLike(userId: number, count: number): Promise<void>;
getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }>;
// ─── Web-backed ───
getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any>;
forceFetchClientKey(): Promise<ClientKeyInfo>;
getGroupEssence(groupId: number, pageStart?: number, pageLimit?: number): Promise<any>;
getGroupEssenceAll(groupId: number): Promise<any>;
sendGroupNotice(groupId: number, content: string, options?: any): Promise<any>;
getGroupNotice(groupId: number): Promise<any>;
deleteGroupNotice(groupId: number, fid: string): Promise<boolean>;
getCookiesStr(domain: string): Promise<string>;
getCsrfToken(): Promise<number>;
getCredentials(domain: string): Promise<any>;
// ─── Personal profile ───
setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise<void>;
setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void>;
setProfile(nickname?: string, personalNote?: string): Promise<void>;
setSelfLongNick(longNick: string): Promise<any>;
setInputStatus(userId: number, eventType: number): Promise<any>;
setAvatar(source: string): Promise<void>;
setGroupAvatar(groupId: number, source: string): Promise<void>;
fetchCustomFace(count?: number): Promise<string[]>;
getProfileLike(userId?: number, start?: number, limit?: number): Promise<any>;
getUnidirectionalFriendList(): Promise<any>;
getGroupAtAllRemain(groupId: number): Promise<any>;
// ─── Misc ───
translateEn2Zh(words: string[]): Promise<any>;
getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any>;
clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise<any>;
sendGroupSign(groupId: number): Promise<any>;
// ─── Tier-2 napcat parity extras ───
setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>;
fetchAiVoiceList(groupId: number, chatType: number): Promise<Array<{ category: string; voices: Array<{ voiceId: string; voiceDisplayName: string; voiceExampleUrl: string }> }>>;
fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise<MediaIndexNode>;
}
+68 -69
View File
@@ -1,91 +1,90 @@
// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution.
// One deep entry point for a single OIDB round-trip: build the envelope,
// dispatch via Bridge.sendRawPacket, validate the response status, and
// optionally decode the body. Replaces the three positional helpers
// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to
// scatter the same five-step pattern across every action file.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb';
/**
* Build a raw OIDB request buffer (base envelope wrapping a typed body).
*/
export function makeOidbRequest(
command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, isUid = false,
): Uint8Array {
const baseSchema = makeOidbBaseSchema(bodySchema);
return protoEncode({
command,
subCommand,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
}, baseSchema);
export interface OidbCall<TResp = void> {
/** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
cmd: string;
/** OIDB command number, e.g. 0x1253. */
oidbCmd: number;
/** OIDB sub-command, e.g. 1. */
subCmd: number;
request: {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
*/
isUid?: boolean;
};
/** Omit to skip decoding the response body (fire-and-check). */
response?: {
schema: ProtoSchema;
};
}
/**
* Send an OIDB packet and verify it succeeded (no decode of body).
* Issue one OIDB request. Without `response`, returns void after
* verifying the envelope's retCode. With `response`, decodes the
* envelope, validates retCode, and returns the inner body.
*
* Throws on transport failure, missing response, decode failure, or any
* non-zero envelope retCode. Action modules layer their own retCode
* checks (on inner sub-replies like `upload.retCode`) on top of this.
*/
export async function sendOidbAndCheck(
bridge: Bridge,
serviceCmd: string, command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, isUid = false,
): Promise<void> {
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
const envelope = encodeOidbEnvelope(call);
const result = await bridge.sendRawPacket(call.cmd, envelope);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (call.response) {
if (!result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'no response');
}
const baseSchema = makeOidbBaseSchema(call.response.schema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
throwIfOidbError(resp);
return (resp as any).body as TResp;
}
// Fire-and-check: response data is optional, but if present we still
// peek at the envelope so a server-side retCode doesn't silently slip past.
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
// Check OIDB error code if response present
if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase);
if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
if (resp) throwIfOidbError(resp);
}
}
/**
* Send an OIDB packet and decode the response body with the given schema.
*/
export async function sendOidbAndDecode<T>(
bridge: Bridge,
serviceCmd: string, command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false,
): Promise<T> {
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response');
const baseSchema = makeOidbBaseSchema(responseSchema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
if ((resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
return (resp as any).body as T;
function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
const baseSchema = makeOidbBaseSchema(call.request.schema);
return protoEncode({
command: call.oidbCmd,
subCommand: call.subCmd,
errorCode: 0,
body: call.request.value,
errorMsg: '',
reserved: call.request.isUid ? 1 : 0,
}, baseSchema);
}
/**
* Resolve a UIN to a UID string, using cache or fetching as needed.
* Mirrors C++ resolve_user_uid_for_action.
*/
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
// Try group member first
if (groupId !== undefined) {
const uid = bridge.identity.findUidByUin(uin, groupId);
if (uid) return uid;
// Try fetching member list
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const uid2 = bridge.identity.findUidByUin(uin, groupId);
if (uid2) return uid2;
function throwIfOidbError(resp: unknown): void {
const code = (resp as any).errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
}
// Try cached
const uid = bridge.identity.findUidByUin(uin);
if (uid) return uid;
// Fetch profile
const profile = await bridge.fetchUserProfile(uin);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${uin}`);
}
+64 -269
View File
@@ -5,12 +5,13 @@
import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push-handler';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service';
import type { BridgeInterface } from './bridge-interface';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
@@ -18,7 +19,6 @@ import {
} from './proto/action';
// Delegated modules
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
@@ -43,7 +43,6 @@ import {
setGroupSpecialTitle as setGroupSpecialTitle_,
setGroupRemark as setGroupRemark_,
getGroupAtAllRemain as getGroupAtAllRemain_,
setGroupAvatar as setGroupAvatar_,
} from './actions/group-admin';
import {
uploadGroupFile as uploadGroupFile_,
@@ -86,10 +85,12 @@ import {
} from './actions/friend';
import {
setOnlineStatus as setOnlineStatus_,
setDiyOnlineStatus as setDiyOnlineStatus_,
setProfile as setProfile_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
setAvatar as setAvatar_,
setGroupAvatar as setGroupAvatar_,
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
@@ -100,6 +101,20 @@ import {
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
} from './actions/misc';
import {
setGroupTodo as setGroupTodo_,
completeGroupTodo as completeGroupTodo_,
cancelGroupTodo as cancelGroupTodo_,
getStrangerStatus as getStrangerStatus_,
fetchAiVoiceList as fetchAiVoiceList_,
fetchAiVoice as fetchAiVoice_,
AiVoiceChatType,
type AiVoiceCategory,
type AiVoiceChatType as AiVoiceChatTypeT,
type StrangerStatus,
} from './actions/extras';
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import {
getGroupHonorInfo as getGroupHonorInfo_,
forceFetchClientKey as forceFetchClientKey_,
@@ -119,8 +134,6 @@ import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
export interface SendMessageReceipt {
messageId: number;
sequence: number;
@@ -143,26 +156,21 @@ export interface ClientKeyInfo {
keyIndex: string
}
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
export class Bridge {
export class Bridge implements BridgeInterface {
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
private qqInfo_: QQInfo;
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and `emitEvent` fans out in parallel.
* care about and the pipeline fans out in parallel.
*/
readonly events = new BridgeEventBus();
private cmdHandlers_ = new Map<string, CmdParser[]>();
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private memberRefreshTasks_ = new Map<number, Promise<void>>();
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
// and serves a fresh result for `kMemberListTtlMs` to all callers.
// Without this, a busy OneBot client (e.g. MaiBot calling
@@ -177,14 +185,21 @@ export class Bridge {
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) {
this.qqInfo_ = qqInfo;
constructor(identity: IdentityService) {
this.identity = identity;
this.registerDefaultHandlers();
this.identity.setFetcher({
fetchProfile: (uin) => this.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
get qqInfo(): QQInfo { return this.qqInfo_; }
dispose(): void {
this.identity.close();
this.events.clear();
@@ -194,18 +209,12 @@ export class Bridge {
this.packetClient_ = client;
}
private registerDefaultHandlers(): void {
this.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
return this.pipeline.handlesCmd(cmd);
}
// --- PID management ---
@@ -226,183 +235,14 @@ export class Bridge {
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.qqInfo_);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.triggerMemberCacheRefresh(event);
printEvent(event);
this.emitEvent(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.triggerMemberCacheRefresh(event, refreshed);
printEvent(event);
this.emitEvent(event);
}
private emitEvent(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.events.emit(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.refreshMemberCache(
event.groupId,
!this.qqInfo_.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.resolveUidFromCache(event.groupId, event.userUid);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.resolveUidFromCache(event.groupId, event.operatorUid);
if (uin !== null) event.operatorUin = uin;
}
}
private resolveUidFromCache(groupId: number, uid: string): number | null {
return this.identity.findUinByUid(uid, groupId);
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.qqInfo_.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.qqInfo_.selfUid);
}
private triggerMemberCacheRefresh(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.qqInfo_.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.qqInfo_.findGroup(groupId)) return false;
if (!this.identity.findGroup(groupId)) return false;
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
@@ -557,7 +397,7 @@ export class Bridge {
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return resolveUserUid_(this, uin, groupId);
return this.identity.resolveUid(uin, groupId);
}
// --- Delegated: Contact / info queries ---
@@ -635,7 +475,6 @@ export class Bridge {
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
async setGroupRemark(groupId: number, remark: string): Promise<void> { return setGroupRemark_(this, groupId, remark); }
async setGroupAvatar(groupId: number, source: string): Promise<void> { return setGroupAvatar_(this, groupId, source); }
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
return getGroupHonorInfo_(this, groupId, type);
}
@@ -681,6 +520,9 @@ export class Bridge {
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
}
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
return setDiyOnlineStatus_(this, faceId, wording, faceType);
}
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
return setProfile_(this, nickname, personalNote);
}
@@ -714,82 +556,35 @@ export class Bridge {
async setAvatar(source: string): Promise<void> {
return setAvatar_(this, source);
}
async setGroupAvatar(groupId: number, source: string): Promise<void> {
return setGroupAvatar_(this, groupId, source);
}
async fetchCustomFace(count?: number): Promise<string[]> {
return fetchCustomFace_(this, count);
}
async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) {
return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie);
}
}
// --- Module-level helper functions ---
// --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) ---
function elementsToText(elements: MessageElement[]): string {
return elements.map(e => {
switch (e.type) {
case 'text': return e.text ?? '';
case 'at': return `@${e.targetUin ?? 'all'}`;
case 'face': return `[表情:${e.faceId}]`;
case 'mface': return `[${e.summary ?? '表情'}]`;
case 'image': return '[图片]';
case 'video': return '[视频]';
case 'record': return '[语音]';
case 'file': return `[文件:${e.fileName ?? ''}]`;
case 'json': return '[JSON卡片]';
case 'xml': return '[XML卡片]';
case 'reply': return `[回复:${e.replySeq}]`;
case 'poke': return '[戳一戳]';
case 'forward': return '[合并转发]';
case 'markdown': return '[Markdown]';
default: return `[${e.type}]`;
}
}).join('');
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return setGroupTodo_(this, groupId, BigInt(msgSeq));
}
async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return completeGroupTodo_(this, groupId, BigInt(msgSeq));
}
async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return cancelGroupTodo_(this, groupId, BigInt(msgSeq));
}
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
return getStrangerStatus_(this, uin);
}
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise<AiVoiceCategory[]> {
return fetchAiVoiceList_(this, groupId, chatType);
}
async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) {
return fetchAiVoice_(this, groupId, voiceId, text, chatType);
}
}
+8 -2
View File
@@ -208,11 +208,14 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 22,
businessType: isGroup ? 22 : 12,
} as any,
};
}
@@ -226,11 +229,14 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 21,
businessType: isGroup ? 21 : 11,
} as any,
};
}
@@ -191,7 +191,7 @@ export async function uploadHighwayHttp(
bridge: Bridge, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
const socket = await tcpConnect(session.host, session.port);
try {
@@ -201,7 +201,7 @@ export async function uploadHighwayHttp(
const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
const frame = packHighwayFrame(head, chunk);
@@ -487,7 +487,11 @@ export async function uploadVideoMsgInfo(
subFileType: 100,
},
],
compatQmsgSceneType: 2,
// Scene tag the NTV2 upload registers under. image-upload and
// ptt-upload both differentiate (group=2, c2c=1); video was
// hardcoded to the group value, which contributed to the c2c
// send-back rejection (PbSendMsg result=79).
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: { bizType: 0, textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
+233 -88
View File
@@ -2,12 +2,25 @@ import fs from 'fs';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } from './qq-info';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger } from '../utils/logger';
const log = createLogger('Identity');
/**
* Hooks Identity uses when its read methods miss every cache layer. Wired in
* after construction (Bridge owns these methods, but Bridge can't exist
* before Identity does). Each call is expected to invoke the matching
* remember* observation on this service as a side effect.
*/
export interface IdentityFetcher {
fetchProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupMemberList?(groupId: number): Promise<unknown>;
}
interface UserInput {
uid?: string;
uin?: number;
@@ -66,16 +79,43 @@ interface MemberRow {
active: number;
}
/**
* Authoritative store for everything we know about QQ actors observed
* during this session: the bot's own identity, friends, groups, group
* members, user profiles, plus the bidirectional UID↔UIN index that
* powers all OIDB-bound translation.
*
* Two layers internally:
* - In-memory state (this file) — O(1) for find* on the hot path.
* - SQLite (optional, opened by openForUin) — survives restarts.
*
* Both layers are kept in sync by the remember* / refresh paths.
* Callers should never reach below the public surface; the cascade and
* storage details are intentionally hidden.
*/
export class IdentityService {
private readonly db: DatabaseSync | null;
// ─── Self identity ───
private readonly uin_: string;
private nickname_ = '';
private selfProfile_: UserProfileInfo | null = null;
// ─── In-memory domain state ───
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private readonly groups_ = new Map<number, QQGroupInfo>();
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
private readonly uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>();
private inTransaction = false;
constructor(
private readonly qqInfo: QQInfo,
dbPath: string | null,
) {
// ─── Persistence + fetcher ───
private readonly db: DatabaseSync | null;
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
constructor(uin: string, dbPath: string | null) {
this.uin_ = uin;
if (!dbPath) {
this.db = null;
return;
@@ -89,12 +129,12 @@ export class IdentityService {
this.loadSnapshot();
}
static openForUin(qqInfo: QQInfo, dataRoot = 'data'): IdentityService {
return new IdentityService(qqInfo, path.join(dataRoot, qqInfo.uin, 'snowluma_identity.db'));
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
}
static memory(qqInfo: QQInfo): IdentityService {
return new IdentityService(qqInfo, null);
static memory(uin: string): IdentityService {
return new IdentityService(uin, null);
}
close(): void {
@@ -105,8 +145,143 @@ export class IdentityService {
return this.db !== null;
}
setFetcher(fetcher: IdentityFetcher): void {
this.fetcher = fetcher;
}
// ─── Self identity surface ───
get uin(): string { return this.uin_; }
get nickname(): string { return this.nickname_; }
set nickname(v: string) { this.nickname_ = v; }
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
// ─── Domain object reads ───
findUserProfile(uin: number): UserProfileInfo | null {
return this.userProfiles_.get(uin) ?? null;
}
get friends(): FriendInfo[] { return this.friends_; }
findFriend(uin: number): FriendInfo | null {
return this.friends_.find((f) => f.uin === uin) ?? null;
}
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
findGroup(groupId: number): QQGroupInfo | null {
return this.groups_.get(groupId) ?? null;
}
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
return this.groups_.get(groupId)?.members.get(uin) ?? null;
}
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.set(member.uin, member);
this.rememberUidUin(member.uid, member.uin);
}
// ─── ID translation ───
/**
* UIN → UID with network fallback. Returns cached value on hit; otherwise
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
* which is expected to write the result back through `rememberUserProfile`
* before this method re-queries the cache. Throws if no UID can be
* obtained from any layer.
*/
async resolveUid(uin: number, groupId?: number): Promise<string> {
const normalized = normalizeUin(uin);
if (normalized === null) throw new Error(`invalid uin: ${uin}`);
const cached = this.findUidByUin(normalized, groupId);
if (cached) return cached;
if (groupId !== undefined && this.fetcher?.fetchGroupMemberList) {
try { await this.fetcher.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const afterMembers = this.findUidByUin(normalized, groupId);
if (afterMembers) return afterMembers;
}
if (!this.fetcher) throw new Error(`failed to resolve UID for UIN ${normalized}: no fetcher`);
const profile = await this.fetcher.fetchProfile(normalized);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${normalized}`);
}
findUinByUid(uid: string, groupId?: number): number | null {
const normalized = normalizeUid(uid);
if (!normalized) return null;
if (groupId !== undefined) {
const member = this.findGroupMemberByUid(groupId, normalized);
if (member) return member.uin;
}
const mapped = this.uinByUid.get(normalized);
if (mapped !== undefined) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uin: number | null } | undefined;
const uin = normalizeUin(row?.uin);
if (uin !== null) return uin;
}
const row = this.db.prepare(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
}
findUidByUin(uin: number, groupId?: number): string | null {
const normalized = normalizeUin(uin);
if (normalized === null) return null;
if (groupId !== undefined) {
const member = this.groups_.get(groupId)?.members.get(normalized);
if (member?.uid) return member.uid;
}
const mapped = this.uidByUin.get(normalized);
if (mapped) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uid: string | null } | undefined;
const uid = normalizeUid(row?.uid);
if (uid) return uid;
}
const row = this.db.prepare(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
}
// ─── Observation (write side) ───
rememberFriends(friends: FriendInfo[]): void {
this.qqInfo.setFriends(friends);
this.friends_ = friends;
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
this.runWrite('friends', () => this.transaction(() => {
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
@@ -125,7 +300,7 @@ export class IdentityService {
}
rememberGroups(groups: QQGroupInfo[]): void {
this.qqInfo.setGroups(groups);
this.setGroupsInMemory(groups);
this.runWrite('groups', () => this.transaction(() => {
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
.run(nowSeconds());
@@ -143,7 +318,7 @@ export class IdentityService {
}
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
this.qqInfo.setGroupMembers(groupId, members);
this.setGroupMembersInMemory(groupId, members);
for (const member of members) this.rememberUidUin(member.uid, member.uin);
this.runWrite('group members', () => this.transaction(() => {
this.upsertGroup({ groupId, memberCount: members.length });
@@ -169,9 +344,9 @@ export class IdentityService {
}
rememberUserProfile(info: UserProfileInfo): void {
this.qqInfo.setUserProfile(info);
const selfUin = parseInt(this.qqInfo.uin, 10) || 0;
if (info.uin === selfUin) this.qqInfo.setSelfProfile(info);
this.userProfiles_.set(info.uin, info);
const selfUin = parseInt(this.uin_, 10) || 0;
if (info.uin === selfUin) this.selfProfile_ = info;
this.rememberUidUin(info.uid, info.uin);
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
uid: info.uid,
@@ -259,67 +434,7 @@ export class IdentityService {
});
}
findUinByUid(uid: string, groupId?: number): number | null {
const normalized = normalizeUid(uid);
if (!normalized) return null;
if (groupId !== undefined) {
const cached = this.qqInfo.resolveGroupMemberUid(groupId, normalized);
if (cached !== null) return cached;
}
const globalCached = this.qqInfo.resolveUid(normalized);
if (globalCached !== null) return globalCached;
const mapped = this.uinByUid.get(normalized);
if (mapped !== undefined) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uin: number | null } | undefined;
const uin = normalizeUin(row?.uin);
if (uin !== null) return uin;
}
const row = this.db.prepare(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
}
findUidByUin(uin: number, groupId?: number): string | null {
const normalized = normalizeUin(uin);
if (normalized === null) return null;
if (groupId !== undefined) {
const cached = this.qqInfo.findUidByUinInGroup(groupId, normalized);
if (cached) return cached;
}
const globalCached = this.qqInfo.findUidByUin(normalized);
if (globalCached) return globalCached;
const mapped = this.uidByUin.get(normalized);
if (mapped) return mapped;
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.db.prepare(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
LIMIT 1`,
).get(groupId, normalized) as { uid: string | null } | undefined;
const uid = normalizeUid(row?.uid);
if (uid) return uid;
}
const row = this.db.prepare(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
}
// ─── Private helpers ───
private rememberUidUin(uid: unknown, uin: unknown): void {
const normalizedUid = normalizeUid(uid);
@@ -329,6 +444,38 @@ export class IdentityService {
this.uidByUin.set(normalizedUin, normalizedUid);
}
private setGroupsInMemory(groups: QQGroupInfo[]): void {
// Preserve existing member maps where possible so a roster refresh
// doesn't blow away cached members for groups we already track.
const previous = new Map(this.groups_);
this.groups_.clear();
for (const g of groups) {
const existing = previous.get(g.groupId);
this.groups_.set(g.groupId, {
...g,
members: existing?.members ?? g.members ?? new Map(),
});
}
}
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.clear();
for (const m of members) {
g.members.set(m.uin, m);
}
}
private findGroupMemberByUid(groupId: number, uid: string): GroupMemberInfo | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uid === uid) return m;
}
return null;
}
private initSchema(): void {
this.db!.exec(`
CREATE TABLE IF NOT EXISTS users (
@@ -387,12 +534,13 @@ export class IdentityService {
FROM users
WHERE is_friend = 1 AND uin IS NOT NULL`,
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>;
this.qqInfo.setFriends(friendRows.map((row) => ({
this.friends_ = friendRows.map((row) => ({
uid: row.uid ?? '',
uin: row.uin ?? 0,
nickname: row.nickname,
remark: row.remark,
})));
}));
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
const groups = this.db!.prepare(
`SELECT group_id, group_name, remark, member_count, member_max
@@ -405,7 +553,7 @@ export class IdentityService {
member_count: number;
member_max: number;
}>;
this.qqInfo.setGroups(groups.map((row) => ({
this.setGroupsInMemory(groups.map((row) => ({
groupId: row.group_id,
groupName: row.group_name,
remark: row.remark,
@@ -419,7 +567,6 @@ export class IdentityService {
private hydrateActiveMembersForGroups(groupIds: number[]): void {
if (!this.db || groupIds.length === 0) return;
const membersByGroup = new Map<number, GroupMemberInfo[]>();
const select = this.db.prepare(
`SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time
@@ -440,11 +587,9 @@ export class IdentityService {
last_sent_time: number;
shut_up_time: number;
}>;
membersByGroup.set(groupId, rows.map(rowToMemberInfo));
}
for (const [groupId, members] of membersByGroup) {
this.qqInfo.setGroupMembers(groupId, members);
const members = rows.map(rowToMemberInfo);
this.setGroupMembersInMemory(groupId, members);
for (const m of members) this.rememberUidUin(m.uid, m.uin);
}
}
+6 -9
View File
@@ -6,15 +6,13 @@
import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
import { QQInfo } from './qq-info';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
interface QQSession {
qqInfo: QQInfo;
bridge: Bridge;
}
@@ -67,7 +65,7 @@ export class BridgeManager {
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
this.onSessionStarted_(uin, session.bridge);
}
}
}
@@ -92,7 +90,7 @@ export class BridgeManager {
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
this.onSessionStarted_(uin, session.bridge);
}
}
@@ -104,9 +102,8 @@ export class BridgeManager {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const qqInfo = new QQInfo(uin);
const bridge = new Bridge(qqInfo, IdentityService.openForUin(qqInfo));
session = { qqInfo, bridge };
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
@@ -119,7 +116,7 @@ export class BridgeManager {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> {
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
}
@@ -1,886 +0,0 @@
// MsgPush packet handler — parses trpc.msg.olpush.OlPushService.MsgPush
// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp
import { inflateSync } from 'zlib';
import { protoDecode } from '../protobuf/decode';
import { WireMessage } from '../protobuf/wire';
import { PushMsgSchema } from './proto/message';
import {
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
} from './proto/element';
import { FileExtraSchema } from './proto/message';
import {
GroupChangeSchema, GroupAdminSchema, GroupJoinSchema,
GroupInvitationSchema, GroupInviteSchema,
FriendRequestSchema, FriendRecallSchema,
GroupMuteSchema, NotifyMessageBodySchema,
GeneralGrayTipInfoSchema, OperatorInfoSchema,
} from './proto/notify';
import type { QQInfo } from './qq-info';
import type { PacketInfo } from '../protocol/types';
import type {
QQEventVariant, MessageElement,
FriendMessage, GroupMessage, TempMessage,
GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent,
FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent,
FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent,
} from './events';
import type { ProtoDecoded, ProtoSchema } from '../protobuf/decode';
// --- PkgType enum ---
const enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
const enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
const enum Event0x210SubType {
FriendRequestNotice = 35,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
}
// --- Helpers ---
function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
return 'http://gchat.qpic.cn' + origUrl;
}
const HEX_CHARS = '0123456789ABCDEF';
function bytesToHex(data: Uint8Array): string {
let r = '';
for (const b of data) { r += HEX_CHARS[b >> 4]; r += HEX_CHARS[b & 0x0f]; }
return r;
}
function decompressData(data: Uint8Array): string {
if (!data || data.length === 0) return '';
if (data[0] === 0x01 && data.length > 1) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)));
return inflated.toString('utf8');
} catch { return ''; }
}
if (data[0] === 0x00 && data.length > 1) {
return Buffer.from(data.subarray(1)).toString('utf8');
}
return Buffer.from(data).toString('utf8');
}
function isNumericUin(value: string): boolean {
return value.length > 0 && /^\d+$/.test(value);
}
function parseU64OrZero(value: string): number {
if (!value) return 0;
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
}
function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number {
if (!uid) return fallback;
if (isNumericUin(uid)) {
const n = parseInt(uid, 10);
if (!isNaN(n)) return n;
}
if (groupId) {
const uin = qqInfo.resolveGroupMemberUid(groupId, uid);
if (uin !== null) return uin;
}
const uin = qqInfo.resolveUid(uid);
if (uin !== null) return uin;
return fallback;
}
function decodeOperatorUid(bytes: Uint8Array): string {
if (!bytes || bytes.length === 0) return '';
const info = protoDecode(bytes, OperatorInfoSchema);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
}
function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');
}
return map;
}
function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
for (const k of keys) {
const v = map.get(k);
if (v) return v;
}
return '';
}
function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
if (content.length <= 7) return null;
const lenBe = (content[5] << 8) | content[6];
const lenLe = content[5] | (content[6] << 8);
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
return content.subarray(7);
}
// --- Element conversion ---
type ElemDecoded = ProtoDecoded<typeof import('./proto/element').ElemSchema>;
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
let skipNext = false;
for (const elem of elems) {
if (skipNext) { skipNext = false; continue; }
// Reply / quote
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
}
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: ProtoDecoded<typeof MentionExtraSchema> | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
mention = protoDecode(t.pbReserve, MentionExtraSchema);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
if (hasAttr6 || hasMention) {
const me: MessageElement = { type: 'at', text: t.str ?? '' };
if (hasAttr6) {
const buf = t.attr6Buf!;
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
}
result.push(me);
} else {
const text = t.str ?? '';
if (text) result.push({ type: 'text', text });
}
}
// Face
if (elem.face) {
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
}
// MarketFace
if (elem.marketFace) {
result.push({
type: 'mface',
text: elem.marketFace.faceName ?? '',
faceId: elem.marketFace.tabId ?? 0,
subType: elem.marketFace.subType ?? 0,
});
}
// NotOnlineImage (C2C image)
if (elem.notOnlineImage) {
const img = elem.notOnlineImage;
if (img.picMd5 && img.picMd5.length > 0) {
const urlPath = img.origUrl || img.bigUrl || '';
result.push({
type: 'image',
imageUrl: makeImageUrl(urlPath),
fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0,
width: img.picWidth ?? 0,
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: bytesToHex(img.picMd5),
});
}
}
// CustomFace (group image)
if (elem.customFace) {
const img = elem.customFace;
if (img.md5 && img.md5.length > 0) {
result.push({
type: 'image',
imageUrl: makeImageUrl(img.origUrl ?? ''),
fileId: img.filePath ?? '',
fileSize: img.size ?? 0,
width: img.width ?? 0,
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: bytesToHex(img.md5),
});
}
}
// VideoFile
if (elem.videoFile) {
const v = elem.videoFile;
result.push({
type: 'video',
fileId: v.fileUuid ?? '',
fileName: v.fileName ?? '',
fileSize: v.fileSize ?? 0,
duration: v.fileTime ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
mediaNode: {
fileUuid: v.fileUuid ?? '',
info: {
fileSize: v.fileSize ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
fileName: v.fileName ?? '',
width: v.fileWidth ?? 0,
height: v.fileHeight ?? 0,
time: v.fileTime ?? 0,
type: {
type: 2,
videoFormat: v.fileFormat ?? 0,
},
},
},
});
}
// GroupFile
if (elem.groupFile) {
const f = elem.groupFile;
result.push({
type: 'file',
fileId: f.fileId ?? '',
fileName: f.filename ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
});
}
// TransElem type=24 (group file via transport)
if (elem.transElem) {
const te = elem.transElem;
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
type: 'file',
fileName: info.fileName ?? '',
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
fileId: info.fileId ?? '',
});
}
}
}
}
// RichMsg
if (elem.richMsg) {
const rm = elem.richMsg;
if (rm.template1 && rm.template1.length > 0) {
const content = decompressData(rm.template1);
if (content) {
const svcId = rm.serviceId ?? 0;
if (svcId === 35) {
const pos = content.indexOf('m_resid="');
if (pos !== -1) {
const start = pos + 9;
const end = content.indexOf('"', start);
if (end !== -1) {
result.push({ type: 'forward', resId: content.substring(start, end) });
continue;
}
}
result.push({ type: 'xml', text: content, subType: svcId });
} else if (svcId === 1) {
result.push({ type: 'json', text: content });
} else {
result.push({ type: 'xml', text: content, subType: svcId });
}
}
}
}
// LightApp
if (elem.lightApp) {
const la = elem.lightApp;
if (la.data && la.data.length > 0) {
const content = decompressData(la.data);
if (content) result.push({ type: 'json', text: content });
}
}
// CommonElem
if (elem.commonElem) {
const ce = elem.commonElem;
const svcType = ce.serviceType ?? 0;
const bizType = ce.businessType ?? 0;
if (svcType === 2) {
// Poke
result.push({ type: 'poke', subType: bizType });
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
// Flash image
const pb = ce.pbElem;
let pos = 1;
let length = 0, shift = 0;
while (pos < pb.length) {
const b = pb[pos++];
length |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
};
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
if (img.picMd5 && img.picMd5.length > 0) {
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + bytesToHex(img.picMd5) + '/0';
}
result.push(me);
}
}
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
const info = protoDecode(ce.pbElem, MsgInfoSchema);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
const idx = body.index;
const fi = idx.info!;
if (bizType === 10 || bizType === 20) {
// Image
let url = '';
if (body.picture) {
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
const path = body.picture.urlPath ?? '';
if (path) {
url = 'https://' + domain + path;
if (body.picture.ext?.originalParameter) {
url += body.picture.ext.originalParameter;
}
}
}
const me: MessageElement = {
type: 'image', fileId: fi.fileName ?? '',
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
height: fi.height ?? 0, imageUrl: url,
};
if (fi.fileHash) me.md5Hex = fi.fileHash;
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
if (info.extBizInfo?.pic) {
me.subType = info.extBizInfo.pic.bizType ?? 0;
me.summary = info.extBizInfo.pic.textSummary || '[image]';
}
result.push(me);
} else if (bizType === 12 || bizType === 22) {
// Record
result.push({
type: 'record', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
voiceFormat: fi.type?.voiceFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
} else if (bizType === 11 || bizType === 21) {
// Video
result.push({
type: 'video', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
width: fi.width ?? 0,
height: fi.height ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
videoFormat: fi.type?.videoFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
}
}
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
}
}
return result;
}
function extractRichtextExtras(
rt: ProtoDecoded<typeof import('./proto/message').RichTextSchema>,
elements: MessageElement[],
isGroup = false
): void {
// Ptt (voice)
if (rt.ptt) {
const p = rt.ptt;
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '';
const me: MessageElement = {
type: 'record', fileName: p.fileName ?? '',
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
fileHash: md5Hex,
md5Hex,
voiceFormat: p.format ?? 0,
};
if (isGroup && (p.fileId ?? 0n) !== 0n) {
me.fileId = p.groupFileKey ?? '';
} else {
if (p.fileUuid && p.fileUuid.length > 0) {
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
}
}
me.mediaNode = {
fileUuid: me.fileId ?? '',
info: {
fileSize: p.fileSize ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
fileName: p.fileName ?? '',
time: p.time ?? 0,
type: {
type: 3,
voiceFormat: p.format ?? 0,
},
},
};
elements.push(me);
}
// NotOnlineFile (C2C file)
if (rt.notOnlineFile) {
const f = rt.notOnlineFile;
elements.push({
type: 'file', fileId: f.fileUuid ?? '',
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
const extra = protoDecode(msgContent, FileExtraSchema);
if (!extra?.file) return;
const f = extra.file;
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
elements.push({
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash,
});
}
}
// --- Main handler ---
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] {
if (pkt.body.length === 0) return [];
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
if (!push?.message) return [];
const msg = push.message;
if (!msg.contentHead) return [];
const head = msg.contentHead;
const msgType = head.msgType ?? 0;
const subType = head.subType ?? 0;
const sequence = head.sequence ?? 0;
const timestamp = head.timestamp ?? 0;
const msgId = head.msgId ?? 0;
let fromUin = 0;
let fromUid = '';
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
const content = (msg.body?.msgContent) ? msg.body.msgContent : new Uint8Array(0);
const buildElements = (isGroup: boolean): MessageElement[] => {
const elements: MessageElement[] = [];
if (msg.body?.richText) {
const rt = msg.body.richText;
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
extractRichtextExtras(rt, elements, isGroup);
}
if (msg.body?.msgContent && msg.body.msgContent.length > 0) {
extractMsgContent(msg.body.msgContent, elements);
}
return elements;
};
// --- Switch on msgType ---
switch (msgType as PkgType) {
case PkgType.GroupMemberIncreaseNotice: {
const change = protoDecode(content, GroupChangeSchema);
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const ev: GroupMemberJoin = {
kind: 'group_member_join', time: timestamp, selfUin,
groupId,
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
userUid,
operatorUid,
};
return [ev];
}
case PkgType.GroupMemberDecreaseNotice: {
const change = protoDecode(content, GroupChangeSchema);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const ev: GroupMemberLeave = {
kind: 'group_member_leave', time: timestamp, selfUin,
groupId,
userUin: resolveUidToUin(qqInfo, groupId, userUid, 0),
operatorUin: resolveUidToUin(qqInfo, groupId, operatorUid, 0),
userUid,
operatorUid,
isKick: dt !== 0 && dt !== 130,
};
return [ev];
}
case PkgType.GroupAdminChangedNotice: {
const admin = protoDecode(content, GroupAdminSchema);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];
const ev: GroupAdminEvent = {
kind: 'group_admin', time: timestamp, selfUin,
groupId: admin.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
set: admin.body.extraEnable !== undefined,
};
return [ev];
}
case PkgType.GroupRequestJoinNotice: {
const join = protoDecode(content, GroupJoinSchema);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin,
groupId: join.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
fromUid: join.targetUid ?? '',
subType: 'add', message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
}
case PkgType.GroupRequestInvitationNotice: {
const invitation = protoDecode(content, GroupInvitationSchema);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
fromUid: inner.invitorUid ?? '',
subType: 'invite', message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
}
case PkgType.GroupInviteNotice: {
const invite = protoDecode(content, GroupInviteSchema);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
fromUid: invite.invitorUid ?? '',
subType: 'invite', message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
}
case PkgType.Event0x210: {
switch (subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: {
const request = protoDecode(content, FriendRequestSchema);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request', time: timestamp, selfUin,
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
fromUid: sourceUid,
message: request.info.message ?? '', flag: sourceUid,
};
return [ev];
}
case Event0x210SubType.FriendRecallNotice: {
const recall = protoDecode(content, FriendRecallSchema);
if (!recall?.info) return [];
const ev: FriendRecall = {
kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin,
userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
case Event0x210SubType.FriendPokeNotice: {
const grayTip = protoDecode(content, GeneralGrayTipInfoSchema);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = {
kind: 'friend_poke', time: timestamp, selfUin,
userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
}
break;
}
case PkgType.Event0x2DC: {
switch (subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: {
const mute = protoDecode(content, GroupMuteSchema);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin,
groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
};
return [ev];
}
case Event0x2DCSubType.GroupRecallNotice: {
const payload = unwrapGroupNotifyPayload(content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
kind: 'group_recall', time: recalled.time ?? timestamp, selfUin,
groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '', fromUin),
authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
}
case Event0x2DCSubType.GroupGreyTipNotice: {
const payload = unwrapGroupNotifyPayload(content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: GroupPokeEvent = {
kind: 'group_poke', time: timestamp, selfUin,
groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
case Event0x2DCSubType.GroupEssenceNotice: {
const payload = unwrapGroupNotifyPayload(content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
const ev: GroupEssenceEvent = {
kind: 'group_essence', time: essence.timestamp ?? timestamp, selfUin,
groupId: essence.groupUin ?? notify.groupUin ?? 0,
senderUin: essence.memberUin ?? 0,
operatorUin: essence.operatorUin ?? fromUin,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
return [ev];
}
}
break;
}
}
// --- Message types ---
if (msgType === PkgType.GroupMessage) {
const ev: GroupMessage = {
kind: 'group_message', time: timestamp, selfUin,
senderUin: fromUin, msgSeq: sequence,
msgId: msgId & 0x7FFFFFFF,
elements: buildElements(true),
groupId: 0, senderNick: '', senderCard: '', senderRole: '',
};
if (msg.responseHead?.grp) {
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
ev.senderNick = msg.responseHead.grp.memberName ?? '';
}
const member = qqInfo.findGroupMember(ev.groupId, fromUin);
if (member) {
if (!ev.senderNick) ev.senderNick = member.nickname;
ev.senderCard = member.card;
ev.senderRole = member.role;
}
return [ev];
}
if (msgType === PkgType.TempMessage) {
const ev: TempMessage = {
kind: 'temp_message', time: timestamp, selfUin,
senderUin: fromUin, msgSeq: sequence,
elements: buildElements(false),
groupId: 0, senderNick: '',
};
if (msg.responseHead?.grp) {
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
ev.senderNick = msg.responseHead.grp.memberName ?? '';
}
if (!ev.senderNick) {
const friend = qqInfo.findFriend(fromUin);
if (friend) ev.senderNick = friend.nickname;
}
return [ev];
}
if (msgType === PkgType.PrivateMessage ||
msgType === PkgType.ForwardFakePrivateMessage ||
msgType === PkgType.PrivateRecordMessage ||
msgType === PkgType.PrivateFileMessage) {
const ev: FriendMessage = {
kind: 'friend_message', time: timestamp, selfUin,
senderUin: fromUin, msgSeq: sequence,
msgId: msgId & 0x7FFFFFFF,
elements: buildElements(false),
senderNick: '',
};
if (msg.responseHead?.forward?.friendName) {
ev.senderNick = msg.responseHead.forward.friendName;
}
const friend = qqInfo.findFriend(fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev];
}
// const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48)));
return [];
}
@@ -0,0 +1,78 @@
// MsgPushContext — the decoded envelope fields every decoder may need.
// One unified shape: notice decoders pick from `content`, message decoders
// pick from `body` / `responseHead`. Decoders ignore fields they don't need.
import { protoDecode } from '../../protobuf/decode';
import type { ProtoDecoded } from '../../protobuf/decode';
import {
PushMsgSchema, MessageBodySchema, ResponseHeadSchema, ContentHeadSchema,
} from '../proto/message';
import type { PacketInfo } from '../../protocol/types';
import type { IdentityService } from '../identity-service';
export type PushMsgBody = ProtoDecoded<typeof MessageBodySchema>;
export type PushMsgResponseHead = ProtoDecoded<typeof ResponseHeadSchema>;
export type PushMsgContentHead = ProtoDecoded<typeof ContentHeadSchema>;
export interface MsgPushHead {
readonly msgType: number;
readonly subType: number;
readonly sequence: number;
readonly timestamp: number;
readonly msgId: number;
}
export interface MsgPushContext {
readonly head: MsgPushHead;
readonly fromUin: number;
readonly fromUid: string;
readonly selfUin: number;
readonly content: Uint8Array;
readonly body: PushMsgBody | undefined;
readonly responseHead: PushMsgResponseHead | undefined;
readonly identity: IdentityService;
}
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
if (pkt.body.length === 0) return null;
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
if (!push?.message) return null;
const msg = push.message;
if (!msg.contentHead) return null;
const head: MsgPushHead = {
msgType: msg.contentHead.msgType ?? 0,
subType: msg.contentHead.subType ?? 0,
sequence: msg.contentHead.sequence ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
let fromUin = 0;
let fromUid = '';
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
const content = msg.body?.msgContent ?? new Uint8Array(0);
return {
head,
fromUin,
fromUid,
selfUin,
content,
body: msg.body,
responseHead: msg.responseHead,
identity,
};
}
@@ -0,0 +1,73 @@
// Handles Event0x210 wrapper (528). Internal switch on subType dispatches
// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290).
import { protoDecode } from '../../../protobuf/decode';
import {
FriendRequestSchema, FriendRecallSchema, GeneralGrayTipInfoSchema,
} from '../../proto/notify';
import type {
FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
} from '../helpers';
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
}
return [];
};
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protoDecode(ctx.content, FriendRequestSchema);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
}
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
const recall = protoDecode(ctx.content, FriendRecallSchema);
if (!recall?.info) return [];
const ev: FriendRecall = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protoDecode(ctx.content, GeneralGrayTipInfoSchema);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
@@ -0,0 +1,106 @@
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
import { protoDecode } from '../../../protobuf/decode';
import {
GroupMuteSchema, NotifyMessageBodySchema,
} from '../../proto/notify';
import type {
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x2DCSubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
unwrapGroupNotifyPayload,
} from '../helpers';
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
}
return [];
};
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
const mute = protoDecode(ctx.content, GroupMuteSchema);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
kind: 'group_mute',
time: mute.data.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? '', ctx.fromUin),
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
};
return [ev];
}
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
kind: 'group_recall',
time: recalled.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '', ctx.fromUin),
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? '', ctx.fromUin),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
}
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: GroupPokeEvent = {
kind: 'group_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
const ev: GroupEssenceEvent = {
kind: 'group_essence',
time: essence.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: essence.groupUin ?? notify.groupUin ?? 0,
senderUin: essence.memberUin ?? 0,
operatorUin: essence.operatorUin ?? ctx.fromUin,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
return [ev];
}
@@ -0,0 +1,28 @@
// Handles the four PkgTypes that produce a FriendMessage event:
// PrivateMessage (166), ForwardFakePrivateMessage (9),
// PrivateRecordMessage (208), PrivateFileMessage (529). The PkgType
// difference only affects which proto-level elements show up in the
// body — decodeRichBody handles all of them uniformly.
import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements: decodeRichBody(ctx.body, false),
senderNick: '',
};
if (ctx.responseHead?.forward?.friendName) {
ev.senderNick = ctx.responseHead.forward.friendName;
}
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev];
};
@@ -0,0 +1,24 @@
// Handles GroupAdminChangedNotice (44). extraEnable / extraDisable
// distinguishes set vs. unset.
import { protoDecode } from '../../../protobuf/decode';
import { GroupAdminSchema } from '../../proto/notify';
import type { GroupAdminEvent } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { resolveUidToUin } from '../helpers';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protoDecode(ctx.content, GroupAdminSchema);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: admin.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, admin.groupUin ?? 0, extra.adminUid ?? '', ctx.fromUin),
set: admin.body.extraEnable !== undefined,
};
return [ev];
};
@@ -0,0 +1,63 @@
// Handles GroupRequestJoinNotice (84) + GroupRequestInvitationNotice (525)
// + GroupInviteNotice (87). All three produce GroupInviteEvent with
// different subType ('add' / 'invite') and flag prefixes.
import { protoDecode } from '../../../protobuf/decode';
import {
GroupJoinSchema, GroupInvitationSchema, GroupInviteSchema,
} from '../../proto/notify';
import type { GroupInviteEvent } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { resolveUidToUin } from '../helpers';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protoDecode(ctx.content, GroupJoinSchema);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: join.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', ctx.fromUin),
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
};
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protoDecode(ctx.content, GroupInvitationSchema);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', ctx.fromUin),
fromUid: inner.invitorUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
};
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
const invite = protoDecode(ctx.content, GroupInviteSchema);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', ctx.fromUin),
fromUid: invite.invitorUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
};
@@ -0,0 +1,49 @@
// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34).
// Both share GroupChangeSchema; the decreaseType field distinguishes kick vs
// voluntary leave (dt != 0 && dt != 130 means kicked).
import { protoDecode } from '../../../protobuf/decode';
import { GroupChangeSchema } from '../../proto/notify';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protoDecode(ctx.content, GroupChangeSchema);
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
userUid,
operatorUid,
};
return [ev];
};
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const change = protoDecode(ctx.content, GroupChangeSchema);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const ev: GroupMemberLeave = {
kind: 'group_member_leave',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
userUid,
operatorUid,
isKick: dt !== 0 && dt !== 130,
};
return [ev];
};
@@ -0,0 +1,33 @@
// Handles GroupMessage (82). Resolves senderCard / senderRole from the
// group member roster when present.
import type { GroupMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
const ev: GroupMessage = {
kind: 'group_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements: decodeRichBody(ctx.body, true),
groupId: 0,
senderNick: '',
senderCard: '',
senderRole: '',
};
if (ctx.responseHead?.grp) {
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
}
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
if (member) {
if (!ev.senderNick) ev.senderNick = member.nickname;
ev.senderCard = member.card;
ev.senderRole = member.role;
}
return [ev];
};
@@ -0,0 +1,28 @@
// Handles TempMessage (141). Pulls senderNick from group hint first
// then falls back to friend roster.
import type { TempMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
elements: decodeRichBody(ctx.body, false),
groupId: 0,
senderNick: '',
};
if (ctx.responseHead?.grp) {
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
}
if (!ev.senderNick) {
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend) ev.senderNick = friend.nickname;
}
return [ev];
};
@@ -0,0 +1,33 @@
// MsgPush PkgType taxonomy. The top-level msgType field in PushMsg.contentHead
// names a QQ-protocol-defined packet shape; Event0x210 / Event0x2DC are wrapper
// PkgTypes whose payload is further dispatched by subType.
export enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
export enum Event0x210SubType {
FriendRequestNotice = 35,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
}
@@ -0,0 +1,83 @@
// MsgPush decode helpers — pure functions shared across PkgType decoders
// and the rich-body decoder. No state, no I/O.
import { inflateSync } from 'zlib';
import { protoDecode } from '../../protobuf/decode';
import { OperatorInfoSchema } from '../proto/notify';
import type { IdentityService } from '../identity-service';
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
return 'http://gchat.qpic.cn' + origUrl;
}
export function decompressData(data: Uint8Array): string {
if (!data || data.length === 0) return '';
if (data[0] === 0x01 && data.length > 1) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)));
return inflated.toString('utf8');
} catch { return ''; }
}
if (data[0] === 0x00 && data.length > 1) {
return Buffer.from(data.subarray(1)).toString('utf8');
}
return Buffer.from(data).toString('utf8');
}
export function isNumericUin(value: string): boolean {
return value.length > 0 && /^\d+$/.test(value);
}
export function parseU64OrZero(value: string): number {
if (!value) return 0;
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
}
// Cascades group-scoped lookup → in-memory map → SQLite.
// No network fallback on the parse hot path: missing identities fall back to
// `fallback` and downstream events drive a roster refresh asynchronously.
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
if (!uid) return fallback;
if (isNumericUin(uid)) {
const n = parseInt(uid, 10);
if (!isNaN(n)) return n;
}
const uin = identity.findUinByUid(uid, groupId || undefined);
if (uin !== null) return uin;
return fallback;
}
export function decodeOperatorUid(bytes: Uint8Array): string {
if (!bytes || bytes.length === 0) return '';
const info = protoDecode(bytes, OperatorInfoSchema);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
}
export function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');
}
return map;
}
export function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
for (const k of keys) {
const v = map.get(k);
if (v) return v;
}
return '';
}
export function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
if (content.length <= 7) return null;
const lenBe = (content[5] << 8) | content[6];
const lenLe = content[5] | (content[6] << 8);
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
return content.subarray(7);
}
@@ -0,0 +1,48 @@
// MsgPush entry point — assembles the PkgType registry and exposes
// `parseMsgPush(pkt, identity)` as the single CmdParser registered against
// `MSG_PUSH_CMD` on the IncomingPacketPipeline.
import type { PacketInfo } from '../../protocol/types';
import type { IdentityService } from '../identity-service';
import type { QQEventVariant } from '../events';
import { buildContext } from './context';
import { MsgPushRegistry } from './registry';
import { PkgType } from './enums';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave,
} from './decoders/group-member-change';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupJoinRequest, decodeGroupInvitation, decodeGroupInvite,
} from './decoders/group-join-request';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeGroupMessage } from './decoders/group-message';
import { decodeTempMessage } from './decoders/temp-message';
import { decodeFriendMessage } from './decoders/friend-message';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
const registry = new MsgPushRegistry();
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);
registry.register(PkgType.GroupInviteNotice, decodeGroupInvite);
registry.register(PkgType.Event0x210, decodeEvent0x210);
registry.register(PkgType.Event0x2DC, decodeEvent0x2DC);
registry.register(PkgType.GroupMessage, decodeGroupMessage);
registry.register(PkgType.TempMessage, decodeTempMessage);
registry.register([
PkgType.PrivateMessage,
PkgType.ForwardFakePrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
], decodeFriendMessage);
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
const ctx = buildContext(pkt, identity);
if (!ctx) return [];
return registry.decode(ctx);
}
@@ -0,0 +1,40 @@
// MsgPushRegistry — per-PkgType dispatch table. Each PkgType maps to a single
// decoder; double-registration is a programming error (throws at register time).
// Decoder errors are caught and logged with the PkgType so a single bad decoder
// can never silently take down sibling decoders sharing the cmd.
import { createLogger } from '../../utils/logger';
import type { QQEventVariant } from '../events';
import type { MsgPushContext } from './context';
import type { PkgType } from './enums';
const log = createLogger('MsgPush');
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
export class MsgPushRegistry {
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
for (const t of list) {
if (this.decoders_.has(t)) {
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
}
this.decoders_.set(t, decoder);
}
}
decode(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) return [];
try {
return decoder(ctx);
} catch (e) {
log.error('decoder error for PkgType=%d subType=%d: %s',
ctx.head.msgType, ctx.head.subType,
e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
}
}
}
@@ -0,0 +1,447 @@
// Rich body decoder — turns the proto MessageBody (richText.elems +
// richText.ptt/notOnlineFile + msgContent) of a MsgPush message into
// the bridge-internal MessageElement[] sequence. Pure, no identity
// lookups, no I/O. The single small interface `decodeRichBody` hides
// ~400 lines of per-element-type decoding behind it.
import { protoDecode } from '../../protobuf/decode';
import type { ProtoDecoded } from '../../protobuf/decode';
import { ElemSchema } from '../proto/element';
import {
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
} from '../proto/element';
import {
MessageBodySchema, RichTextSchema, FileExtraSchema,
} from '../proto/message';
import type { MessageElement } from '../events';
import { toHexUpper } from '../../utils/hex';
import { decompressData, makeImageUrl } from './helpers';
type ElemDecoded = ProtoDecoded<typeof ElemSchema>;
type RichTextDecoded = ProtoDecoded<typeof RichTextSchema>;
export type PushMsgBody = ProtoDecoded<typeof MessageBodySchema>;
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
if (body?.richText) {
const rt = body.richText;
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
extractRichtextExtras(rt, elements, isGroup);
}
if (body?.msgContent && body.msgContent.length > 0) {
extractMsgContent(body.msgContent, elements);
}
return elements;
}
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
let skipNext = false;
for (const elem of elems) {
if (skipNext) { skipNext = false; continue; }
// Reply / quote
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
}
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: ProtoDecoded<typeof MentionExtraSchema> | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
mention = protoDecode(t.pbReserve, MentionExtraSchema);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
if (hasAttr6 || hasMention) {
const me: MessageElement = { type: 'at', text: t.str ?? '' };
if (hasAttr6) {
const buf = t.attr6Buf!;
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
}
result.push(me);
} else {
const text = t.str ?? '';
if (text) result.push({ type: 'text', text });
}
}
// Face
if (elem.face) {
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
}
// MarketFace
if (elem.marketFace) {
result.push({
type: 'mface',
text: elem.marketFace.faceName ?? '',
faceId: elem.marketFace.tabId ?? 0,
subType: elem.marketFace.subType ?? 0,
});
}
// NotOnlineImage (C2C image)
if (elem.notOnlineImage) {
const img = elem.notOnlineImage;
if (img.picMd5 && img.picMd5.length > 0) {
const urlPath = img.origUrl || img.bigUrl || '';
result.push({
type: 'image',
imageUrl: makeImageUrl(urlPath),
fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0,
width: img.picWidth ?? 0,
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: toHexUpper(img.picMd5),
});
}
}
// CustomFace (group image)
if (elem.customFace) {
const img = elem.customFace;
if (img.md5 && img.md5.length > 0) {
result.push({
type: 'image',
imageUrl: makeImageUrl(img.origUrl ?? ''),
fileId: img.filePath ?? '',
fileSize: img.size ?? 0,
width: img.width ?? 0,
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
md5Hex: toHexUpper(img.md5),
});
}
}
// VideoFile
if (elem.videoFile) {
const v = elem.videoFile;
result.push({
type: 'video',
fileId: v.fileUuid ?? '',
fileName: v.fileName ?? '',
fileSize: v.fileSize ?? 0,
duration: v.fileTime ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
mediaNode: {
fileUuid: v.fileUuid ?? '',
info: {
fileSize: v.fileSize ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
fileName: v.fileName ?? '',
width: v.fileWidth ?? 0,
height: v.fileHeight ?? 0,
time: v.fileTime ?? 0,
type: {
type: 2,
videoFormat: v.fileFormat ?? 0,
},
},
},
});
}
// GroupFile
if (elem.groupFile) {
const f = elem.groupFile;
result.push({
type: 'file',
fileId: f.fileId ?? '',
fileName: f.filename ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
});
}
// TransElem type=24 (group file via transport)
if (elem.transElem) {
const te = elem.transElem;
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
type: 'file',
fileName: info.fileName ?? '',
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
fileId: info.fileId ?? '',
});
}
}
}
}
// RichMsg
if (elem.richMsg) {
const rm = elem.richMsg;
if (rm.template1 && rm.template1.length > 0) {
const content = decompressData(rm.template1);
if (content) {
const svcId = rm.serviceId ?? 0;
if (svcId === 35) {
const pos = content.indexOf('m_resid="');
if (pos !== -1) {
const start = pos + 9;
const end = content.indexOf('"', start);
if (end !== -1) {
result.push({ type: 'forward', resId: content.substring(start, end) });
continue;
}
}
result.push({ type: 'xml', text: content, subType: svcId });
} else if (svcId === 1) {
result.push({ type: 'json', text: content });
} else {
result.push({ type: 'xml', text: content, subType: svcId });
}
}
}
}
// LightApp
if (elem.lightApp) {
const la = elem.lightApp;
if (la.data && la.data.length > 0) {
const content = decompressData(la.data);
if (content) result.push({ type: 'json', text: content });
}
}
// CommonElem
if (elem.commonElem) {
const ce = elem.commonElem;
const svcType = ce.serviceType ?? 0;
const bizType = ce.businessType ?? 0;
if (svcType === 2) {
// Poke
result.push({ type: 'poke', subType: bizType });
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
// Flash image
const pb = ce.pbElem;
let pos = 1;
let length = 0, shift = 0;
while (pos < pb.length) {
const b = pb[pos++];
length |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
};
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
if (img.picMd5 && img.picMd5.length > 0) {
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + toHexUpper(img.picMd5) + '/0';
}
result.push(me);
}
}
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
const info = protoDecode(ce.pbElem, MsgInfoSchema);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
const idx = body.index;
const fi = idx.info!;
if (bizType === 10 || bizType === 20) {
// Image
let url = '';
if (body.picture) {
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
const path = body.picture.urlPath ?? '';
if (path) {
url = 'https://' + domain + path;
if (body.picture.ext?.originalParameter) {
url += body.picture.ext.originalParameter;
}
}
}
const me: MessageElement = {
type: 'image', fileId: fi.fileName ?? '',
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
height: fi.height ?? 0, imageUrl: url,
};
if (fi.fileHash) me.md5Hex = fi.fileHash;
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
if (info.extBizInfo?.pic) {
me.subType = info.extBizInfo.pic.bizType ?? 0;
me.summary = info.extBizInfo.pic.textSummary || '[image]';
}
result.push(me);
} else if (bizType === 12 || bizType === 22) {
// Record
result.push({
type: 'record', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
fileSize: fi.fileSize ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
voiceFormat: fi.type?.voiceFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
} else if (bizType === 11 || bizType === 21) {
// Video
result.push({
type: 'video', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
width: fi.width ?? 0,
height: fi.height ?? 0,
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
videoFormat: fi.type?.videoFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
}
}
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
}
}
return result;
}
function extractRichtextExtras(
rt: RichTextDecoded,
elements: MessageElement[],
isGroup = false
): void {
// Ptt (voice)
if (rt.ptt) {
const p = rt.ptt;
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '';
const me: MessageElement = {
type: 'record', fileName: p.fileName ?? '',
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
fileHash: md5Hex,
md5Hex,
voiceFormat: p.format ?? 0,
};
if (isGroup && (p.fileId ?? 0n) !== 0n) {
me.fileId = p.groupFileKey ?? '';
} else {
if (p.fileUuid && p.fileUuid.length > 0) {
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
}
}
me.mediaNode = {
fileUuid: me.fileId ?? '',
info: {
fileSize: p.fileSize ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '',
fileName: p.fileName ?? '',
time: p.time ?? 0,
type: {
type: 3,
voiceFormat: p.format ?? 0,
},
},
};
elements.push(me);
}
// NotOnlineFile (C2C file)
if (rt.notOnlineFile) {
const f = rt.notOnlineFile;
elements.push({
type: 'file', fileId: f.fileUuid ?? '',
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
const extra = protoDecode(msgContent, FileExtraSchema);
if (!extra?.file) return;
const f = extra.file;
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
elements.push({
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash,
});
}
}
+275
View File
@@ -0,0 +1,275 @@
// Incoming packet pipeline — the chain that turns a single PacketInfo
// arriving from the hook layer into a stream of QQEventVariant
// emissions on the typed event bus. Replaces the inline orchestration
// that previously lived on Bridge.onPacket / triggerMemberCacheRefresh /
// rememberEventIdentity / dispatchAfterIdentityRefresh / etc.
//
// Stage chain per parser output:
// parse → enrich identity (sync, or async refresh)
// → side-effects (remember UID/UIN + schedule roster refresh)
// → log
// → emit on bus
//
// The pipeline owns its cmd handler map and its per-group coalesce table
// for background member-list refreshes. It does NOT own protocol calls
// — `refreshMemberCache` is injected by Bridge because it ultimately
// dispatches OIDB packets through Bridge.fetchGroupList /
// Bridge.fetchGroupMemberList.
import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import { createLogger } from '../utils/logger';
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
}
export class IncomingPacketPipeline {
private cmdHandlers_ = new Map<string, CmdParser[]>();
private memberRefreshTasks_ = new Map<number, Promise<void>>();
constructor(private readonly deps: PacketPipelineDeps) {}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
process(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.deps.identity);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.handleSideEffects(event);
printEvent(event);
this.emit(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private emit(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.deps.events.emit(event);
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.handleSideEffects(event, refreshed);
printEvent(event);
this.emit(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.deps.refreshMemberCache(
event.groupId,
!this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.deps.identity.findUinByUid(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
if (uin !== null) event.operatorUin = uin;
}
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.deps.identity.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.deps.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.deps.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
}
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
}
}
@@ -395,6 +395,11 @@ export const OidbGroupReactionSchema = {
groupUin: { field: 1, type: 'uint32' as const },
sequence: { field: 2, type: 'uint32' as const },
code: { field: 3, type: 'string' as const },
// 1 = legacy QQ face (short numeric id like "76"), 2 = unicode emoji
// (decimal codepoint string like "128516" for 😄). Omitting this
// field used to make unicode reactions fail server-side because the
// server defaulted to type=1 and couldn't resolve a 6-digit code.
type: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0x6D8_1: Group file list ---
@@ -856,6 +861,20 @@ export const OidbGetPskeyRespSchema = {
} satisfies ProtoSchema;
// customExt sub-message of SetStatus. Populated only by
// set_diy_online_status (status=10 + extStatus=2000 + this payload);
// regular set_online_status leaves field 4 unset.
//
// Wire (from napcat packet/transformer/proto/action/action.ts SetStatusCustomExt):
// 1 faceId (uint32) — face icon id, e.g. "Q我吧" sticker
// 2 text (string) — wording shown next to the icon
// 3 field3 (uint32) — face_type / template id; observed values 1..3
export const SetStatusCustomExtSchema = {
faceId: { field: 1, type: 'uint32' as const },
text: { field: 2, type: 'string' as const },
faceType: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SetStatusReqSchema = {
status: { field: 1, type: 'int32' as const },
extStatus: { field: 2, type: 'int32' as const },
@@ -1122,6 +1141,139 @@ export const Oidb0xf16ReqSchema = {
export const Oidb0xf16RespSchema = {} satisfies ProtoSchema;
// --- 0xF90_{1,2,3}: Set / complete / cancel group todo ---
// All three subCmds share the same body (groupUin + msgSeq); only the
// envelope subCmd differs. Sources: napcat
// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts.
export const OidbGroupTodoSchema = {
groupUin: { field: 1, type: 'uint32' as const },
msgSeq: { field: 2, type: 'uint64' as const },
} satisfies ProtoSchema;
// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) ---
export const OidbStrangerStatusKeySchema = {
key: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbStrangerStatusReqSchema = {
uin: { field: 1, type: 'uint32' as const },
key: { field: 3, type: 'repeated_message' as const, schema: OidbStrangerStatusKeySchema },
} satisfies ProtoSchema;
export const OidbStrangerStatusRespStatusSchema = {
key: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'uint64' as const },
} satisfies ProtoSchema;
export const OidbStrangerStatusRespDataSchema = {
status: { field: 2, type: 'message' as const, schema: OidbStrangerStatusRespStatusSchema },
} satisfies ProtoSchema;
export const OidbStrangerStatusRespSchema = {
data: { field: 1, type: 'message' as const, schema: OidbStrangerStatusRespDataSchema },
} satisfies ProtoSchema;
// --- 0x929D_0: Fetch AI voice character list ---
export const OidbAiVoiceListReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
chatType: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceListEntrySchema = {
voiceId: { field: 1, type: 'string' as const },
voiceDisplayName: { field: 2, type: 'string' as const },
voiceExampleUrl: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceListCategorySchema = {
category: { field: 1, type: 'string' as const },
voices: { field: 2, type: 'repeated_message' as const, schema: OidbAiVoiceListEntrySchema },
} satisfies ProtoSchema;
export const OidbAiVoiceListRespSchema = {
content: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceListCategorySchema },
} satisfies ProtoSchema;
// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) ---
export const OidbAiVoiceSessionSchema = {
sessionId: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
voiceId: { field: 2, type: 'string' as const },
text: { field: 3, type: 'string' as const },
chatType: { field: 4, type: 'uint32' as const },
session: { field: 5, type: 'message' as const, schema: OidbAiVoiceSessionSchema },
} satisfies ProtoSchema;
// We only need the fields the OneBot adapter consumes back: the
// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the
// statusCode that the server uses to signal "still rendering, retry".
export const OidbAiVoiceFileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceFileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: OidbAiVoiceFileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceIndexNodeSchema = {
info: { field: 1, type: 'message' as const, schema: OidbAiVoiceFileInfoSchema },
fileUuid: { field: 2, type: 'string' as const },
storeId: { field: 3, type: 'uint32' as const },
uploadTime: { field: 4, type: 'uint32' as const },
ttl: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbAiVoiceMsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: OidbAiVoiceIndexNodeSchema },
} satisfies ProtoSchema;
export const OidbAiVoiceMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceMsgInfoBodySchema },
} satisfies ProtoSchema;
export const OidbAiVoiceRespSchema = {
statusCode: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
msgInfo: { field: 4, type: 'message' as const, schema: OidbAiVoiceMsgInfoSchema },
} satisfies ProtoSchema;
// --- Highway cmdId 3000: GroupAvatarExtra ---
// Ported from Lagrange.Core/Internal/Packets/Service/Highway/GroupAvatarExtra.cs.
// Field values are protocol-prescribed constants (Lagrange comments on each).
export const GroupAvatarExtraField3Schema = {
field1: { field: 1, type: 'uint32' as const }, // observed value: 1
} satisfies ProtoSchema;
export const GroupAvatarExtraSchema = {
type: { field: 1, type: 'uint32' as const }, // observed value: 101
groupUin: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'message' as const, schema: GroupAvatarExtraField3Schema },
field5: { field: 5, type: 'uint32' as const }, // observed value: 3
field6: { field: 6, type: 'uint32' as const }, // observed value: 1
} satisfies ProtoSchema;
///////// --- group album
// --- Request Schemas ---
+4 -145
View File
@@ -1,5 +1,7 @@
// QQ info store — per-UIN state for friends, groups, member lookup.
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp
// Domain object shapes shared by IdentityService and its callers. The
// concrete state (own UIN, friends list, group rosters, profile cache)
// lives inside IdentityService — these interfaces just describe the
// records that flow across remember*/refresh* and find* boundaries.
export interface UserProfileInfo {
uin: number;
@@ -60,146 +62,3 @@ export interface GroupRequestInfo {
comment: string;
filtered: boolean;
}
export class QQInfo {
private uin_: string;
private nickname_ = '';
private selfProfile_: UserProfileInfo | null = null;
private userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private groups_ = new Map<number, QQGroupInfo>();
constructor(uin: string) {
this.uin_ = uin;
}
get uin(): string { return this.uin_; }
get nickname(): string { return this.nickname_; }
set nickname(v: string) { this.nickname_ = v; }
// --- Self profile ---
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
// --- User profiles ---
setUserProfile(info: UserProfileInfo): void {
this.userProfiles_.set(info.uin, info);
}
findUserProfile(uin: number): UserProfileInfo | null {
return this.userProfiles_.get(uin) ?? null;
}
// --- Friends ---
setFriends(friends: FriendInfo[]): void { this.friends_ = friends; }
get friends(): FriendInfo[] { return this.friends_; }
findFriend(uin: number): FriendInfo | null {
return this.friends_.find(f => f.uin === uin) ?? null;
}
// --- Groups ---
setGroups(groups: QQGroupInfo[]): void {
this.groups_.clear();
for (const g of groups) {
this.groups_.set(g.groupId, g);
}
}
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
findGroup(groupId: number): QQGroupInfo | null {
return this.groups_.get(groupId) ?? null;
}
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
return this.groups_.get(groupId)?.members.get(uin) ?? null;
}
setGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.clear();
for (const m of members) {
g.members.set(m.uin, m);
}
}
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.set(member.uin, member);
}
// --- UID resolution ---
resolveUid(uid: string): number | null {
// Check self
if (this.selfProfile_?.uid === uid) {
return this.selfProfile_.uin || parseInt(this.uin_, 10) || null;
}
// Check friends
for (const f of this.friends_) {
if (f.uid === uid) return f.uin;
}
// Check user profiles
for (const [, p] of this.userProfiles_) {
if (p.uid === uid) return p.uin;
}
// Check all group members
for (const [, g] of this.groups_) {
for (const [, m] of g.members) {
if (m.uid === uid) return m.uin;
}
}
return null;
}
resolveGroupMemberUid(groupId: number, uid: string): number | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uid === uid) return m.uin;
}
return null;
}
// --- Reverse UID lookup (UIN → UID) ---
findUidByUin(uin: number): string | null {
// Check self
if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) {
return this.selfProfile_.uid;
}
// Check friends
for (const f of this.friends_) {
if (f.uin === uin && f.uid) return f.uid;
}
// Check user profiles
for (const [, p] of this.userProfiles_) {
if (p.uin === uin && p.uid) return p.uid;
}
// Check all group members
for (const [, g] of this.groups_) {
for (const [, m] of g.members) {
if (m.uin === uin && m.uid) return m.uid;
}
}
return null;
}
findUidByUinInGroup(groupId: number, uin: number): string | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uin === uin && m.uid) return m.uid;
}
return null;
}
}
+16 -22
View File
@@ -4,7 +4,7 @@
// thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge';
import { sendOidbAndDecode } from '../bridge-oidb';
import { runOidb } from '../bridge-oidb';
import {
OidbClientKeyRespSchema,
OidbClientKeyReqSchema,
@@ -14,15 +14,12 @@ import {
import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_1',
0x102A,
1,
{},
OidbClientKeyReqSchema,
OidbClientKeyRespSchema,
);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_1',
oidbCmd: 0x102A, subCmd: 1,
request: { schema: OidbClientKeyReqSchema, value: {} },
response: { schema: OidbClientKeyRespSchema },
});
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
@@ -37,15 +34,12 @@ export async function forceFetchClientKey(bridge: Bridge) {
}
export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x102a_0',
0x102A,
0,
{ domainList },
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_0',
oidbCmd: 0x102A, subCmd: 0,
request: { schema: OidbGetPskeyReqSchema, value: { domainList } },
response: { schema: OidbGetPskeyRespSchema },
});
const domainPskeyMap = new Map<string, string>();
@@ -66,9 +60,9 @@ export async function getCookies(bridge: Bridge, domain: string) {
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
@@ -99,7 +93,7 @@ export async function getSKey(bridge: Bridge): Promise<string> {
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.qqInfo.uin +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
@@ -6,7 +6,7 @@ import { getCookies } from './cookies';
export async function getGroupAlbumListWeb(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const uin = bridge.qqInfo.uin;
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
@@ -22,7 +22,7 @@ export async function uploadImageToGroupAlbumWeb(
filePath: string
): Promise<void> {
const groupCode = groupId.toString();
const uin = bridge.qqInfo.uin;
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
+267 -38
View File
@@ -36,7 +36,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const times = asNumber(params.times) || 1;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.sendLike(userId, times);
await ctx.bridge.sendLike(userId, times);
return okResponse();
});
@@ -94,9 +94,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const essenceDataAll = await ctx.getGroupEssenceAll(groupId);
const essenceDataAll = await ctx.bridge.getGroupEssenceAll(groupId);
const allMsgs = essenceDataAll.flatMap(res => res.data?.msg_list || []);
const allMsgs = essenceDataAll.flatMap((res: any) => res.data?.msg_list || []);
return okResponse(allMsgs);
} catch (e) {
@@ -125,7 +125,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
await ctx.bridge.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
return okResponse();
});
@@ -168,7 +168,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
await ctx.markGroupMsgAsRead(groupId, meta.sequence);
await ctx.bridge.markGroupMsgAsRead(groupId, meta.sequence);
return okResponse();
});
@@ -191,7 +191,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
await ctx.markPrivateMsgAsRead(userId, meta.sequence);
await ctx.bridge.markPrivateMsgAsRead(userId, meta.sequence);
return okResponse();
});
@@ -211,9 +211,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
if (meta.isGroup) {
await ctx.markGroupMsgAsRead(targetId, meta.sequence);
await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence);
} else {
await ctx.markPrivateMsgAsRead(targetId, meta.sequence);
await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence);
}
return okResponse();
});
@@ -221,12 +221,16 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- RKey ---
h.registerAction('get_rkey', async () => {
const handleGetRkey = async () => {
if (ctx.getDownloadRKeys) {
return okResponse(await ctx.getDownloadRKeys());
}
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
});
};
h.registerAction('get_rkey', handleGetRkey);
// napcat exposes the same payload under `nc_get_rkey`; mirror the alias
// so clients that follow napcat's docs work out-of-the-box.
h.registerAction('nc_get_rkey', handleGetRkey);
// --- OCR stubs ---
@@ -258,7 +262,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1,
};
await ctx.sendGroupNotice(groupId, content, options);
await ctx.bridge.sendGroupNotice(groupId, content, options);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -271,7 +275,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const notices = await ctx.getGroupNotice(groupId);
const notices = await ctx.bridge.getGroupNotice(groupId);
return okResponse(notices);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -288,7 +292,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const success = await ctx.deleteGroupNotice(groupId, fid);
const success = await ctx.bridge.deleteGroupNotice(groupId, fid);
if (success) {
return okResponse();
} else {
@@ -427,7 +431,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const cookies = await ctx.getCookiesStr(domain);
const cookies = await ctx.bridge.getCookiesStr(domain);
return okResponse({ cookies });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -437,7 +441,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_csrf_token', async () => {
try {
const token = await ctx.getCsrfToken();
const token = await ctx.bridge.getCsrfToken();
return okResponse({ token });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -449,7 +453,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const creds = await ctx.getCredentials(domain);
const creds = await ctx.bridge.getCredentials(domain);
return okResponse(creds);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -480,7 +484,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const remark = asString(params.remark) ?? '';
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.setFriendRemark(userId, remark);
await ctx.bridge.setFriendRemark(userId, remark);
return okResponse();
});
@@ -488,7 +492,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const remark = asString(params.remark) ?? '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupRemark(groupId, remark);
await ctx.bridge.setGroupRemark(groupId, remark);
return okResponse();
});
@@ -570,7 +574,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setProfile(nickname, personalNote);
await ctx.bridge.setProfile(nickname, personalNote);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -590,17 +594,81 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setOnlineStatus(status, extStatus, batteryStatus);
await ctx.bridge.setOnlineStatus(status, extStatus, batteryStatus);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_group_ignored_notifies', async () => {
return okResponse([]);
// DIY status — same wire packet as set_online_status, only the
// customExt sub-message is populated and status/extStatus are forced
// to the QQ-defined "I have a custom status" values (10 / 2000).
// face_id / face_type accept either number or numeric string (napcat
// parity); wording is the human-readable text shown next to the icon.
h.registerAction('set_diy_online_status', async (params) => {
const faceId = asNumber(params.face_id);
const faceType = asNumber(params.face_type) || 1;
const wording = asString(params.wording);
if (!faceId) return failedResponse(RETCODE.BAD_REQUEST, 'face_id is required');
try {
await ctx.bridge.setDiyOnlineStatus(faceId, wording, faceType);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
// Filtered (机器人/被忽略) group join requests. SnowLuma already
// implements the underlying oidb 0x10c8_2 fetch via fetchGroupRequests;
// these three actions just rename / project the same data for the
// OneBot dialects clients use in the wild.
const fetchFilteredGroupRequests = async () => {
try {
return await ctx.bridge.fetchGroupRequests(true);
} catch {
return [];
}
};
h.registerAction('get_group_ignored_notifies', async () => {
const reqs = await fetchFilteredGroupRequests();
return okResponse(reqs.map((r) => ({
group_id: r.groupId,
group_name: r.groupName,
request_id: r.sequence,
requester_uin: r.targetUin,
requester_nick: r.targetName,
message: r.comment,
checked: r.state !== 1,
actor: r.operatorUin,
invitor_uin: r.invitorUin,
invitor_nick: r.invitorName,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`,
})));
});
// napcat name for the subset of ignored notifies that are join requests
// (notify type==7). We map every entry that flowed through filtered
// 0x10c8_2 into napcat's shape — eventType already encodes the request
// category in our pipeline.
h.registerAction('get_group_ignore_add_request', async () => {
const reqs = await fetchFilteredGroupRequests();
return okResponse(reqs.map((r) => ({
request_id: r.sequence,
invitor_uin: r.invitorUin,
invitor_nick: r.invitorName,
group_id: r.groupId,
message: r.comment,
group_name: r.groupName,
checked: r.state !== 1,
actor: r.operatorUin,
requester_nick: r.targetName,
})));
});
// get_group_shut_list lives behind an oidb we don't yet wrap; honour
// the napcat contract (empty list) so callers don't blow up.
h.registerAction('get_group_shut_list', async () => {
return okResponse([]);
});
@@ -653,7 +721,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('fetch_custom_face', async (params) => {
const count = asNumber(params.count) || 10;
try {
const urls = await ctx.fetchCustomFace(count);
const urls = await ctx.bridge.fetchCustomFace(count);
return okResponse(urls);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -667,7 +735,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
const result = await ctx.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
const result = await ctx.bridge.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -684,7 +752,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
const result = await ctx.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
const result = await ctx.bridge.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
return okResponse({
result: 0,
errMsg: '',
@@ -733,7 +801,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const data = await ctx.getGroupAtAllRemain(groupId);
const data = await ctx.bridge.getGroupAtAllRemain(groupId);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -743,7 +811,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_unidirectional_friend_list', async () => {
try {
const data = await ctx.getUnidirectionalFriendList();
const data = await ctx.bridge.getUnidirectionalFriendList();
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -759,7 +827,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setSelfLongNick(longNick);
await ctx.bridge.setSelfLongNick(longNick);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -780,7 +848,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setAvatar(file);
await ctx.bridge.setAvatar(file);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -802,7 +870,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.setInputStatus(userId, eventType);
await ctx.bridge.setInputStatus(userId, eventType);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -820,7 +888,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const translated = await ctx.translateEn2Zh(words);
const translated = await ctx.bridge.translateEn2Zh(words);
return okResponse({ words: translated });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -828,11 +896,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
h.registerAction('get_clientkey', async () => {
const clientKeyInfo = await ctx.forceFetchClientKey();
const clientKeyInfo = await ctx.bridge.forceFetchClientKey();
if (!clientKeyInfo.clientKey) {
return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error');
}
return okResponse(clientKeyInfo);
return okResponse({ ...clientKeyInfo });
});
h.registerAction('get_mini_app_ark', async (params) => {
@@ -844,7 +912,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const data = await ctx.getMiniAppArk(
const data = await ctx.bridge.getMiniAppArk(
String(type),
String(title),
String(desc),
@@ -870,7 +938,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const data = await ctx.clickInlineKeyboardButton(
const data = await ctx.bridge.clickInlineKeyboardButton(
groupId,
botAppid,
String(buttonId),
@@ -892,7 +960,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
await ctx.sendGroupSign(groupId);
await ctx.bridge.sendGroupSign(groupId);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -934,9 +1002,170 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('.send_packet', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
// --- Raw packet escape hatch (napcat parity) ---
//
// napcat exposes both names; the dot-prefix variant is the original
// gocqhttp-era backdoor, the no-prefix one is the modern API. They do
// the same thing in SnowLuma: encode hex → Bridge.sendRawPacket → hex.
const handleSendPacket = async (params: import('../types').JsonObject) => {
const cmd = asString(params.cmd);
const dataHex = asString(params.data);
const rsp = asBoolean(params.rsp, true);
if (!cmd) return failedResponse(RETCODE.BAD_REQUEST, 'cmd is required');
if (!/^[0-9a-fA-F]*$/.test(dataHex) || dataHex.length % 2 !== 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length');
}
try {
const body = hexToBytes(dataHex);
const result = await ctx.bridge.sendRawPacket(cmd, body);
if (!result.success) {
return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed');
}
if (!rsp) return okResponse(null);
const respHex = result.responseData ? bytesToHex(result.responseData) : '';
return okResponse(respHex);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
};
h.registerAction('send_packet', handleSendPacket);
h.registerAction('.send_packet', handleSendPacket);
// --- Bot lifecycle (napcat parity) ---
h.registerAction('bot_exit', async () => {
// Defer so the OK response actually flushes before the process dies.
setTimeout(() => process.exit(0), 50);
return okResponse();
});
// SnowLuma has no separate packet-backend process (napcat's packet
// service runs out-of-process and can fail independently). Always
// report healthy.
h.registerAction('nc_get_packet_status', async () => {
return okResponse(null);
});
// napcat exposes `delete_group_folder`; SnowLuma's existing
// `delete_group_file_folder` is the same operation. Alias so clients
// following napcat docs work without rewriting payloads.
h.registerAction('delete_group_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.bridge.deleteGroupFileFolder(groupId, folderId);
return okResponse();
});
// --- Group todo (oidb 0xF90) ---
//
// The three subcommands share an identical payload (group + msgSeq);
// we extract once and dispatch by action name. msgSeq comes from the
// message metadata cache (set/complete/cancel always target a real
// message the bot has seen).
type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise<void>;
const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => {
const groupId = asNumber(params.group_id);
const messageId = asNumber(params.message_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
const meta = ctx.getMessageMeta(messageId);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
if (!meta.isGroup || meta.targetId !== groupId) {
return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group');
}
try {
await op(groupId, BigInt(meta.sequence));
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
};
h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.setGroupTodo(g, s)));
h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.completeGroupTodo(g, s)));
h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.cancelGroupTodo(g, s)));
// --- User online/ext status (napcat: nc_get_user_status) ---
h.registerAction('nc_get_user_status', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
const status = await ctx.bridge.getStrangerStatus(userId);
if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status');
return okResponse(status);
});
// --- AI voice (oidb 0x929D / 0x929B) ---
h.registerAction('get_ai_characters', async (params) => {
const groupId = asNumber(params.group_id);
const chatType = asNumber(params.chat_type) || 1;
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
try {
const list = await ctx.bridge.fetchAiVoiceList(groupId, chatType);
return okResponse(list.map((cat) => ({
type: cat.category,
characters: cat.voices.map((v) => ({
character_id: v.voiceId,
character_name: v.voiceDisplayName,
preview_url: v.voiceExampleUrl,
})),
})));
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
h.registerAction('get_ai_record', async (params) => {
const groupId = asNumber(params.group_id);
const character = asString(params.character);
const text = asString(params.text);
const chatType = asNumber(params.chat_type) || 1;
if (!groupId || !character || !text) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required');
}
try {
const node = await ctx.bridge.fetchAiVoice(groupId, character, text, chatType);
const url = await ctx.bridge.fetchGroupPttUrlByNode(groupId, node);
return okResponse(url);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
// napcat's send_group_ai_record is a side-effect-only call: invoking
// fetchAiVoice publishes the voice into the group; the returned
// message_id is always 0 because the oidb call doesn't echo one back.
h.registerAction('send_group_ai_record', async (params) => {
const groupId = asNumber(params.group_id);
const character = asString(params.character);
const text = asString(params.text);
const chatType = asNumber(params.chat_type) || 1;
if (!groupId || !character || !text) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required');
}
try {
await ctx.bridge.fetchAiVoice(groupId, character, text, chatType);
return okResponse({ message_id: 0 });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
function hexToBytes(hex: string): Uint8Array {
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return out;
}
function bytesToHex(buf: Buffer | Uint8Array): string {
const arr = buf instanceof Buffer ? buf : Buffer.from(buf);
return arr.toString('hex');
}
/**
+19 -10
View File
@@ -42,14 +42,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
await ctx.setGroupAddOption(groupId, addType);
await ctx.bridge.setGroupAddOption(groupId, addType);
return okResponse();
});
h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupSearch(groupId);
await ctx.bridge.setGroupSearch(groupId);
return okResponse();
});
@@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupAdmin(groupId, userId, enable);
await ctx.bridge.setGroupAdmin(groupId, userId, enable);
return okResponse();
});
@@ -67,7 +67,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupCard(groupId, userId, card);
await ctx.bridge.setGroupCard(groupId, userId, card);
return okResponse();
});
@@ -75,7 +75,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupName(groupId, name);
await ctx.bridge.setGroupName(groupId, name);
return okResponse();
});
@@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupSpecialTitle(groupId, userId, title);
await ctx.bridge.setGroupSpecialTitle(groupId, userId, title);
return okResponse();
});
@@ -103,11 +103,20 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol).
// `file` accepts everything bridge.setGroupAvatar's underlying
// loadBinarySource handles: local paths, file:// URLs, http(s) URLs,
// and base64:// data URIs — same surface as set_qq_avatar.
h.registerAction('set_group_portrait', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
await ctx.setGroupAvatar(groupId, file);
return okResponse();
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.bridge.setGroupAvatar(groupId, file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
}
@@ -58,7 +58,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
await ctx.deleteGroupFile(groupId, fileId);
await ctx.bridge.deleteGroupFile(groupId, fileId);
return okResponse();
});
@@ -70,7 +70,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
await ctx.bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
@@ -91,7 +91,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.deleteGroupFileFolder(groupId, folderId);
await ctx.bridge.deleteGroupFileFolder(groupId, folderId);
return okResponse();
});
@@ -102,7 +102,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.renameGroupFileFolder(groupId, folderId, newName);
await ctx.bridge.renameGroupFileFolder(groupId, folderId, newName);
return okResponse();
});
@@ -68,7 +68,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
try {
const honorInfo = await ctx.getGroupHonorInfo(groupId, typeStr as WebHonorType);
const honorInfo = await ctx.bridge.getGroupHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
+24 -35
View File
@@ -1,5 +1,6 @@
import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { RETCODE, failedResponse } from './types';
import { register as registerInfo } from './actions/info';
@@ -13,7 +14,7 @@ import { register as registerExtended } from './actions/extended';
import { register as registerGroupAlbum } from './actions/group-album';
import { WebHonorType } from '@/bridge/web/group-honor';
// import {ClientKeyInfo} from "@/bridge/bridge";
import { ClientKeyInfo } from '@/bridge/bridge';
export interface MessageSendResult {
messageId: number;
@@ -32,6 +33,14 @@ export interface GroupEssenceMsgRet {
}
export interface ApiActionContext {
/**
* Direct access to the BridgeInterface. Use for actions that are pure
* 1:1 calls to a Bridge method — no rename, no default args, no
* composition with messageStore / mediaStore. When translation IS
* needed, route through the named adapters declared below instead.
*/
bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
@@ -48,57 +57,39 @@ export interface ApiActionContext {
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo: (userId: number) => Promise<JsonObject | null>;
// Group admin
// Group admin (adapters: rename Bridge methods to OneBot vocabulary)
setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan: (groupId: number, enable: boolean) => Promise<void>;
setGroupAddOption: (groupId: number, addType: number) => Promise<void>;
setGroupSearch: (groupId: number) => Promise<void>;
setGroupAdmin: (groupId: number, userId: number, enable: boolean) => Promise<void>;
setGroupCard: (groupId: number, userId: number, card: string) => Promise<void>;
setGroupName: (groupId: number, name: string) => Promise<void>;
setGroupLeave: (groupId: number) => Promise<void>;
setGroupSpecialTitle: (groupId: number, userId: number, title: string) => Promise<void>;
getGroupAtAllRemain: (groupId: number) => Promise<any>;
// Group file
// Group file (adapters: field extraction + Bridge name translation)
uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>;
deleteGroupFile: (groupId: number, fileId: string) => Promise<void>;
moveGroupFile: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
createGroupFileFolder: (groupId: number, name: string, parentId?: string) => Promise<void>;
deleteGroupFileFolder: (groupId: number, folderId: string) => Promise<void>;
renameGroupFileFolder: (groupId: number, folderId: string, newName: string) => Promise<void>;
getPrivateFileUrl: (userId: number, fileId: string, fileHash: string) => Promise<string>;
// Requests
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
// Requests (adapters: rename to OneBot vocabulary)
handleFriendRequest: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Extended
sendLike: (userId: number, times: number) => Promise<void>;
// Pokes (adapters: flatten isGroup into bridge.sendPoke signature)
sendFriendPoke: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke: (groupId: number, userId: number) => Promise<void>;
// Essence (adapter: bakes the set/unset boolean)
setEssenceMsg: (messageId: number) => Promise<void>;
deleteEssenceMsg: (messageId: number) => Promise<void>;
forceFetchClientKey: () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
getUnidirectionalFriendList: () => Promise<any>;
setSelfLongNick: (longNick: string) => Promise<void>;
setInputStatus: (userId: number, eventType: number) => Promise<void>;
translateEn2Zh: (words: string[]) => Promise<string[]>;
getMiniAppArk: (type: string, title: string, desc: string, picUrl: string, jumpUrl: string) => Promise<any>;
clickInlineKeyboardButton: (groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) => Promise<any>;
sendGroupSign: (groupId: number) => Promise<void>;
// New context methods
setGroupReaction: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
// Profile reads with OneBot-specific default args
getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
// Friend deletion (adapter: rename + force-boolean)
handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>;
// Module wrappers / multi-dep compositions
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
getDownloadRKeys: () => Promise<JsonObject[]>;
// Forward message
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
@@ -108,16 +99,15 @@ export interface ApiActionContext {
setFriendRemark: (userId: number, remark: string) => Promise<void>;
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
setGroupAvatar: (groupId: number, source: string) => Promise<void>;
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead: (userId: number, sequence: number) => Promise<void>;
getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
fetchCustomFace: (count?: number) => Promise<string[]>;
getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
// Web
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise<any>;
getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
getGroupEssenceAll: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
getGroupAlbumList: (groupId: number) => Promise<any>;
uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise<void>;
@@ -128,11 +118,10 @@ export interface ApiActionContext {
getCookiesStr: (domain: string) => Promise<string>;
getCsrfToken: () => Promise<number>;
getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
forceFetchClientKey: () => Promise<ClientKeyInfo>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
// Avatar
setAvatar: (source: string) => Promise<void>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
+61 -53
View File
@@ -1,6 +1,5 @@
import type { WebHonorType } from '@/bridge/web/group-honor';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
@@ -36,6 +35,7 @@ import {
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { BridgeInterface } from '../bridge/bridge-interface';
/**
* Single shared context bag that flows through every OneBot instance-internal
@@ -56,8 +56,7 @@ export interface OneBotInstanceContext {
/** Self UIN parsed once, used in event payloads. */
selfId: number;
qqInfo: QQInfo;
bridge: Bridge;
bridge: BridgeInterface;
messageStore: MessageStore;
mediaStore: MediaStore;
@@ -73,10 +72,25 @@ export interface OneBotInstanceContext {
dispatchEvent(event: JsonObject): void;
}
/**
* Build the ApiActionContext that ApiHandler hands to each action file.
*
* Two flavours of entries live in here:
* - Adapters — rename a Bridge method (setGroupKick → kickGroupMember),
* compose with messageStore / mediaStore / ref, bake in a constant
* (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a
* bridge call into OneBot vocabulary (sendFriendPoke flattens the
* isGroup boolean), or extract a field from the bridge return shape.
* - Pass-throughs used to live here too but added zero value; OneBot
* actions now call `ctx.bridge.<name>` directly when no translation is
* happening (set_group_admin, set_online_status, set_avatar, …).
*/
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, qqInfo, messageStore, mediaStore } = ref;
const { bridge, messageStore, mediaStore } = ref;
return {
bridge,
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId),
@@ -89,29 +103,22 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions.
getFriendList: () => getFriendList(bridge, qqInfo),
getGroupList: (noCache) => getGroupList(bridge, qqInfo, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, qqInfo, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, qqInfo, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, qqInfo, userId),
// OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin.
// Group admin — names translate to OneBot vocabulary.
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.kickGroupMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
setGroupAddOption: (groupId, addType) => bridge.setGroupAddOption(groupId, addType),
setGroupSearch: (groupId) => bridge.setGroupSearch(groupId),
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
getGroupAtAllRemain: (groupId) => bridge.getGroupAtAllRemain(groupId),
// Group file.
// Group file — fileId field extraction + defaults.
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
@@ -122,45 +129,31 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => {
return bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
},
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
// Requests.
// Requests — name translation.
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Extended.
sendLike: (userId, times) => bridge.sendLike(userId, times),
// Pokes — flatten isGroup into the bridge signature.
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
// Essence — bake the set/unset boolean.
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => {
return bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie);
},
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
translateEn2Zh: (words) => bridge.translateEn2Zh(words),
getMiniAppArk: (type, title, desc, picUrl, jumpUrl) => bridge.getMiniAppArk(type, title, desc, picUrl, jumpUrl),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => {
return bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq);
},
sendGroupSign: (groupId) => bridge.sendGroupSign(groupId),
// NapCat-compatible extended actions.
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
// Profile-like / get_group_essence — OneBot-specific defaults that the
// action handlers don't supply.
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.getProfileLike(userId, start, limit),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
// Message-store-backed history reads.
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
// Module wrappers / multi-dep compositions.
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
@@ -168,24 +161,30 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
forceFetchClientKey: () => bridge.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
if (!meta) throw new Error('message not found');
// QQ itself doesn't expose emoji reactions on private chats, so
// there is no wire path to forward this to; fail loudly instead
// of silently no-op'ing.
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.markGroupMsgAsRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => bridge.markPrivateMsgAsRead(userId, sequence),
setOnlineStatus: (status, extStatus, batteryStatus) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname, personalNote) => bridge.setProfile(nickname, personalNote),
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote),
// Web-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId),
getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId),
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath),
@@ -197,11 +196,20 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain) => bridge.getCredentials(domain),
// Extended
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
// Avatar.
setAvatar: (source) => bridge.setAvatar(source),
};
}
// Re-export Bridge type so consumers of OneBotInstanceContext that need it
// (legacy) keep the import surface stable.
export type { Bridge };
// Re-export WebHonorType so legacy spots that imported it via this module
// keep working.
export type { WebHonorType };
+7 -6
View File
@@ -1,5 +1,6 @@
import type { MessageElement } from '../bridge/events';
import type { Bridge, DownloadRKeyInfo } from '../bridge/bridge';
import type { DownloadRKeyInfo } from '../bridge/bridge';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { createLogger } from '../utils/logger';
const log = createLogger('OneBot');
@@ -26,7 +27,7 @@ export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
warmUp(bridge: Bridge, uin: string): void {
warmUp(bridge: BridgeInterface, uin: string): void {
bridge.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
@@ -38,7 +39,7 @@ export class RKeyCache {
);
}
resolveImageUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
@@ -54,7 +55,7 @@ export class RKeyCache {
* Resolve a URL for video/record/file media elements.
* Appends the correct RKey type based on media kind and group/private context.
*/
resolveMediaUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
@@ -93,12 +94,12 @@ export class RKeyCache {
}
}
private findRKey(bridge: Bridge, isGroup: boolean): string | null {
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
private findRKeyForType(bridge: Bridge, primaryType: number): string | null {
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => {
+5 -7
View File
@@ -1,6 +1,5 @@
import path from 'path';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeInterface } from '../bridge/bridge-interface';
import { ApiHandler } from './api-handler';
import type { ConverterContext } from './event-converter';
import { MediaIndexer } from './media-indexer';
@@ -27,8 +26,7 @@ const log = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
readonly qqInfo: QQInfo;
private readonly bridge: Bridge;
private readonly bridge: BridgeInterface;
private readonly apiHandler: ApiHandler;
private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore;
@@ -43,9 +41,10 @@ export class OneBotInstance {
private heartbeatTimer: NodeJS.Timeout | null = null;
private static readonly HEARTBEAT_INTERVAL = 30000;
constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) {
get nickname(): string { return this.bridge.identity.nickname; }
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.qqInfo = qqInfo;
this.bridge = bridge;
this.rkeyCache = new RKeyCache();
@@ -75,7 +74,6 @@ export class OneBotInstance {
const ctx: OneBotInstanceContext = {
uin: this.uin,
selfId: parseInt(this.uin, 10) || 0,
qqInfo: this.qqInfo,
bridge: this.bridge,
messageStore: this.messageStore,
mediaStore: this.mediaStore,
+13 -14
View File
@@ -1,5 +1,4 @@
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { BridgeManager } from '../bridge/manager';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
@@ -12,8 +11,8 @@ export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
bind(bridgeManager: BridgeManager): void {
bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => {
this.onSessionStarted(uin, qqInfo, bridge);
bridgeManager.setSessionStartedCallback((uin, bridge) => {
this.onSessionStarted(uin, bridge);
});
bridgeManager.setSessionClosedCallback((uin) => {
@@ -49,11 +48,11 @@ export class OneBotManager {
this.instances.clear();
}
private onSessionStarted(uin: string, qqInfo: QQInfo, bridge: Bridge): void {
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin);
const instance = new OneBotInstance(uin, qqInfo, bridge, config);
const instance = new OneBotInstance(uin, bridge, config);
const activePid = bridge.activePid;
if (activePid !== null) {
@@ -62,13 +61,13 @@ export class OneBotManager {
// Seed nickname with the UIN so the WebUI never renders blank while
// warmup is in flight or if warmup never resolves a real nickname.
if (!qqInfo.nickname) qqInfo.nickname = uin;
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin);
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
warmUpBridgeState(uin, qqInfo, bridge).catch((err) => {
warmUpBridgeState(uin, bridge).catch((err) => {
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
@@ -84,13 +83,13 @@ export class OneBotManager {
}
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
// Step 1: Fetch friend list + derive self profile when QQ happens to
// include self in the response. Some accounts / versions omit self,
// which used to leave qqInfo.nickname empty — see step 1b for the
// which used to leave identity.nickname empty — see step 1b for the
// explicit fallback.
try {
const friends = await bridge.fetchFriendList();
@@ -98,12 +97,12 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
for (const f of friends) {
if (f.uin === selfUin) {
qqInfo.setSelfProfile({
bridge.identity.setSelfProfile({
uin: f.uin, uid: f.uid,
nickname: f.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
});
qqInfo.nickname = f.nickname || uin;
bridge.identity.nickname = f.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
selfResolved = true;
break;
@@ -120,8 +119,8 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
if (!selfResolved && selfUin > 0) {
try {
const profile = await bridge.fetchUserProfile(selfUin);
qqInfo.setSelfProfile(profile);
qqInfo.nickname = profile.nickname || uin;
bridge.identity.setSelfProfile(profile);
bridge.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
uin, profile.uid, profile.nickname);
} catch (e) {
@@ -12,13 +12,13 @@
//
// Used as the `mediaUrlResolver` callback in `ConverterContext`.
import type { Bridge } from '../bridge/bridge';
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { MessageElement } from '../bridge/events';
import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver {
constructor(
private readonly bridge: Bridge,
private readonly bridge: BridgeInterface,
private readonly rkeyCache: RKeyCache,
) {}
@@ -1,17 +1,17 @@
import type { Bridge } from '../../bridge/bridge';
import type { QQInfo } from '../../bridge/qq-info';
import type { BridgeInterface } from '../../bridge/bridge-interface';
import type { IdentityService } from '../../bridge/identity-service';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
const nickname = ref.bridge.identity.nickname || ref.uin;
return { userId, nickname };
}
// Keep refreshes scoped. A broad "refresh all members in all groups" call can
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promise<void> {
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise<void> {
try {
await bridge.fetchGroupMemberList(groupId);
} catch {
@@ -19,7 +19,7 @@ async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promi
}
}
export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const friends = await bridge.fetchFriendList();
return friends.map(f => ({
@@ -28,7 +28,7 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
remark: f.remark as any,
}));
} catch {
return qqInfo.friends.map(f => ({
return bridge.identity.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
@@ -37,18 +37,17 @@ export async function getFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Jso
}
export async function getGroupList(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
noCache?: boolean,
): Promise<JsonObject[]> {
try {
if (noCache || qqInfo.groups.length === 0) {
if (noCache || bridge.identity.groups.length === 0) {
await bridge.fetchGroupList();
}
} catch {
// Use cached data.
}
return qqInfo.groups.map(g => ({
return bridge.identity.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
@@ -57,19 +56,18 @@ export async function getGroupList(
}
export async function getGroupInfo(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroup(groupId)) {
if (noCache || !bridge.identity.findGroup(groupId)) {
try {
await bridge.fetchGroupList();
} catch {
// Use cached data.
}
}
const g = qqInfo.findGroup(groupId);
const g = bridge.identity.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
@@ -80,41 +78,39 @@ export async function getGroupInfo(
}
export async function getGroupMemberList(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject[]> {
if (noCache) {
await refreshSingleGroupMembers(bridge, groupId);
return getCachedGroupMembers(qqInfo, groupId);
return getCachedGroupMembers(bridge.identity, groupId);
}
try {
const members = await bridge.fetchGroupMemberList(groupId);
return members.map(m => formatGroupMember(groupId, m));
} catch {
return getCachedGroupMembers(qqInfo, groupId);
return getCachedGroupMembers(bridge.identity, groupId);
}
}
export async function getGroupMemberInfo(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
groupId: number,
userId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !qqInfo.findGroupMember(groupId, userId)) {
if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
await refreshSingleGroupMembers(bridge, groupId);
}
const m = qqInfo.findGroupMember(groupId, userId);
const m = bridge.identity.findGroupMember(groupId, userId);
if (!m) return null;
return formatGroupMember(groupId, m);
}
export async function getGroupFiles(
bridge: Bridge,
bridge: BridgeInterface,
groupId: number,
folderId?: string,
): Promise<JsonObject> {
@@ -146,8 +142,7 @@ export async function getGroupFiles(
}
export async function getStrangerInfo(
bridge: Bridge,
qqInfo: QQInfo,
bridge: BridgeInterface,
userId: number,
): Promise<JsonObject | null> {
try {
@@ -159,7 +154,7 @@ export async function getStrangerInfo(
age: p.age as any,
};
} catch {
const p = qqInfo.findUserProfile(userId);
const p = bridge.identity.findUserProfile(userId);
if (!p) return null;
return {
user_id: p.uin as any,
@@ -170,7 +165,7 @@ export async function getStrangerInfo(
}
}
export async function getGroupSystemMessages(bridge: Bridge): Promise<JsonObject[]> {
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const reqs = await bridge.fetchGroupRequests();
return reqs.map(r => ({
@@ -187,7 +182,7 @@ export async function getGroupSystemMessages(bridge: Bridge): Promise<JsonObject
}
}
export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const rkeys = await bridge.fetchDownloadRKeys();
return rkeys.map(r => ({
@@ -201,8 +196,8 @@ export async function getDownloadRKeys(bridge: Bridge): Promise<JsonObject[]> {
}
}
function getCachedGroupMembers(qqInfo: QQInfo, groupId: number): JsonObject[] {
const g = qqInfo.findGroup(groupId);
function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
const g = identity.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, member] of g.members) {
@@ -1,4 +1,4 @@
import type { Bridge } from '../../bridge/bridge';
import type { BridgeInterface } from '../../bridge/bridge-interface';
import { createLogger } from '../../utils/logger';
import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types';
@@ -21,7 +21,7 @@ export async function getImageInfo(
}
export async function getRecordInfo(
bridge: Bridge,
bridge: BridgeInterface,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
@@ -1,4 +1,4 @@
import type { Bridge } from '../../bridge/bridge';
import type { BridgeInterface } from '../../bridge/bridge-interface';
import type { ForwardNodePayload, MessageElement } from '../../bridge/events';
import { createLogger } from '../../utils/logger';
import type { MessageSendResult } from '../api-handler';
@@ -63,7 +63,7 @@ export async function getFriendMsgHistory(
.map(sanitizeMessageEventForApi);
}
export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
if (meta.isGroup) {
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
} else {
@@ -78,7 +78,7 @@ export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise<
}
export async function setEssenceMessage(
bridge: Bridge,
bridge: BridgeInterface,
messageStore: MessageStore,
messageId: number,
enable: boolean,
@@ -1,7 +1,7 @@
import type { Bridge } from '../../bridge/bridge';
import type { BridgeInterface } from '../../bridge/bridge-interface';
export async function handleGroupAddRequest(
bridge: Bridge,
bridge: BridgeInterface,
flag: string,
approve: boolean,
reason: string,
+10
View File
@@ -1,4 +1,5 @@
const HEX_CHARS = '0123456789abcdef';
const HEX_CHARS_UPPER = '0123456789ABCDEF';
export function toHex(data: Uint8Array | Buffer): string {
let h = '';
@@ -9,6 +10,15 @@ export function toHex(data: Uint8Array | Buffer): string {
return h;
}
export function toHexUpper(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS_UPPER[b >> 4];
h += HEX_CHARS_UPPER[b & 0xf];
}
return h;
}
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
const limit = Math.max(0, Math.min(maxBytes, data.length));
const head = toHex(data.subarray(0, limit));
+1 -1
View File
@@ -306,7 +306,7 @@ export async function initWebUI(
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.qqInfo.nickname }));
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
return c.json({ list });
});
+8 -9
View File
@@ -11,19 +11,19 @@ import { vi } from 'vitest';
import type { SendPacketResult } from '../../src/protocol/packet-sender';
export interface MockBridge {
qqInfo: {
identity: {
uin: string;
selfUid: string;
findGroupMember: ReturnType<typeof vi.fn>;
};
identity: {
nickname: string;
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
};
sendRawPacket: ReturnType<typeof vi.fn>;
fetchFriendList: ReturnType<typeof vi.fn>;
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
resolveUserUid: ReturnType<typeof vi.fn>;
}
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
@@ -35,21 +35,20 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
responseData: Buffer.alloc(0),
};
return {
qqInfo: {
identity: {
uin: '10001',
selfUid: 'self-uid',
findGroupMember: vi.fn(() => null),
...(overrides.qqInfo ?? {}),
} as MockBridge['qqInfo'],
identity: {
nickname: 'self-nick',
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
sendRawPacket: vi.fn(async () => defaultResp),
fetchFriendList: vi.fn(async () => []),
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
...overrides,
};
}
+141
View File
@@ -0,0 +1,141 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Same stub-the-oidb-runner pattern as actions/group-admin.test.ts —
// we don't care about wire bytes, just that each function targets the
// right cmd / subCmd / schema.
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
import * as extras from '../../src/bridge/actions/extras';
import * as schemas from '../../src/bridge/proto/oidb-action';
import { mockBridge } from './_helpers';
describe('actions/extras / group todo (0xF90)', () => {
beforeEach(() => vi.mocked(oidb.runOidb).mockClear());
it.each([
['setGroupTodo', extras.setGroupTodo, 'OidbSvcTrpcTcp.0xf90_1', 1],
['completeGroupTodo', extras.completeGroupTodo, 'OidbSvcTrpcTcp.0xf90_2', 2],
['cancelGroupTodo', extras.cancelGroupTodo, 'OidbSvcTrpcTcp.0xf90_3', 3],
] as const)('%s dispatches the right subCmd with shared body', async (_name, fn, cmd, subCmd) => {
const bridge = mockBridge();
await fn(bridge as any, 12345, 9876543210n);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe(cmd);
expect(call.oidbCmd).toBe(0xF90);
expect(call.subCmd).toBe(subCmd);
expect(call.request.schema).toBe(schemas.OidbGroupTodoSchema);
expect(call.request.value).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
});
});
describe('actions/extras / getStrangerStatus (0xFE1_2)', () => {
beforeEach(() => vi.mocked(oidb.runOidb).mockClear());
it('issues the FE1_2 query with key=27372', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 5n } } } as any);
await extras.getStrangerStatus(bridge as any, 100200);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xfe1_2');
expect(call.oidbCmd).toBe(0xFE1);
expect(call.subCmd).toBe(2);
expect(call.request.value).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
});
it('low-band values (≤10) map to status*10 with ext_status=0', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 7n } } } as any);
expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 });
});
it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => {
const bridge = mockBridge();
// value 0x42F100: bits 8-15 (the 0xff00 mask) = 0xF100;
// bits 16-23 (>>16 & 0xff) = 0x42.
// ext_status = 0xF100 + 0x42 = 0xF142.
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 0x42F100n } } } as any);
const status = await extras.getStrangerStatus(bridge as any, 1);
expect(status).toEqual({ status: 10, ext_status: 0xF142 });
});
it('returns null when the runner throws (transport error)', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockRejectedValueOnce(new Error('boom'));
expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull();
});
it('returns null when the server omits the status field', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any);
expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull();
});
});
describe('actions/extras / AI voice (0x929D / 0x929B)', () => {
beforeEach(() => vi.mocked(oidb.runOidb).mockClear());
it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => {
const bridge = mockBridge();
const fake = [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
];
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ content: fake } as any);
const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound);
expect(out).toEqual(fake);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929d_0');
expect(call.request.value).toEqual({ groupUin: 4242, chatType: 1 });
});
it('fetchAiVoiceList returns [] when server replies with no content', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any);
const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any);
expect(out).toEqual([]);
});
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid-1', subType: 0 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ statusCode: 2 } as any)
.mockResolvedValueOnce({ msgInfo: { msgInfoBody: [] } } as any)
.mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound);
expect(out).toBe(node);
expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929b_0');
expect(call.request.value).toMatchObject({
groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1,
});
// sessionId is randomized but must be a uint32.
expect((call.request.value as any).session.sessionId).toBeTypeOf('number');
expect((call.request.value as any).session.sessionId).toBeGreaterThanOrEqual(0);
expect((call.request.value as any).session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
});
it('fetchAiVoice throws after exhausting the retry budget', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue({ statusCode: 1 } as any);
await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow(
/AI voice synthesis did not complete/,
);
expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3);
});
it('fetchAiVoice keeps the same sessionId across retries', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid', subType: 0 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({} as any)
.mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any);
const first = (vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value as any).session.sessionId;
const second = (vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value as any).session.sessionId;
expect(first).toBe(second);
});
});
+1 -4
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
// element-builder reaches into protoEncode with element-specific schemas
+15 -19
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,33 +10,32 @@ import { mockBridge } from './_helpers';
describe('actions/friend', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(oidb.runOidb).mockClear();
});
it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, '10001', true);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
});
it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, 'flag-abc', false);
expect(oidb.resolveUserUid).not.toHaveBeenCalled();
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
});
it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge();
await friend.deleteFriend(bridge as any, 10001, true);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0x126b_0');
expect((call[4] as any).field1.block).toBe(true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
expect((call.request.value as any).field1.block).toBe(true);
expect(bridge.fetchFriendList).toHaveBeenCalled();
});
@@ -54,8 +50,8 @@ describe('actions/friend', () => {
it('setFriendRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge();
await friend.setFriendRemark(bridge as any, 10001, 'best-friend');
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xb6e_2');
expect(call[4]).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
expect(call.request.value).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});
+26 -31
View File
@@ -3,10 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Stub the OIDB shim so we can assert WHICH command + payload each
// action constructs without booting a real Bridge / native pipe.
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -15,21 +12,19 @@ import { mockBridge } from './_helpers';
describe('actions/group-admin', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(oidb.runOidb).mockClear();
});
it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge();
await admin.muteGroupMember(bridge as any, 12345, 67890, 600);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 67890, 12345);
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce();
const args = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(args[1]).toBe('OidbSvcTrpcTcp.0x1253_1');
expect(args[2]).toBe(0x1253);
expect(args[3]).toBe(1);
expect(args[4]).toMatchObject({
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(oidb.runOidb).toHaveBeenCalledOnce();
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1253_1');
expect(call.oidbCmd).toBe(0x1253);
expect(call.subCmd).toBe(1);
expect(call.request.value).toMatchObject({
groupUin: 12345,
type: 1,
body: { targetUid: 'resolved-uid', duration: 600 },
@@ -39,13 +34,13 @@ describe('actions/group-admin', () => {
it('muteGroupAll flips the muteState flag based on enable', async () => {
const bridge = mockBridge();
await admin.muteGroupAll(bridge as any, 12345, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({
expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345,
muteState: { state: 0xFFFFFFFF },
});
await admin.muteGroupAll(bridge as any, 12345, false);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4]).toMatchObject({
expect(vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value).toMatchObject({
muteState: { state: 0 },
});
});
@@ -53,8 +48,8 @@ describe('actions/group-admin', () => {
it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => {
const bridge = mockBridge();
await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour');
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 67890, 12345);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345,
targetUid: 'resolved-uid',
rejectAddRequest: true,
@@ -64,13 +59,13 @@ describe('actions/group-admin', () => {
it('kickGroupMembers resolves each UID in parallel', async () => {
const bridge = mockBridge();
vi.mocked(oidb.resolveUserUid)
vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('uid-a')
.mockResolvedValueOnce('uid-b');
await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false);
expect(oidb.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
expect(payload.targetUids).toEqual(['uid-a', 'uid-b']);
expect(payload.rejectAddRequest).toBe(0);
});
@@ -78,15 +73,15 @@ describe('actions/group-admin', () => {
it('leaveGroup sends 0x1097_1 with the groupUin', async () => {
const bridge = mockBridge();
await admin.leaveGroup(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(call[4]).toMatchObject({ groupUin: 12345 });
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(call.request.value).toMatchObject({ groupUin: 12345 });
});
it('setGroupAdmin resolves UID and sends 0x1096_1', async () => {
const bridge = mockBridge();
await admin.setGroupAdmin(bridge as any, 12345, 67890, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({
expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, uid: 'resolved-uid', isAdmin: true,
});
});
@@ -100,7 +95,7 @@ describe('actions/group-admin', () => {
await admin.setGroupAddOption(bridge as any, 1, 2);
await admin.setGroupSearch(bridge as any, 1);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x8fc_3',
'OidbSvcTrpcTcp.0x89a_15',
@@ -116,23 +111,23 @@ describe('actions/group-admin', () => {
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false);
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x10c8_1',
'OidbSvcTrpcTcp.0x10c8_2',
]);
const firstBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
const firstBody: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
expect(firstBody.accept).toBe(1);
expect(firstBody.body.message).toBe('ok');
const secondBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4];
const secondBody: any = vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value;
expect(secondBody.accept).toBe(2);
});
it('getGroupAtAllRemain decodes the response and converts BigInts', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
canAtAll: 1,
groupRemain: 12n,
uinRemain: 5n,
@@ -147,7 +142,7 @@ describe('actions/group-admin', () => {
it('getGroupAtAllRemain throws when the response is empty', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce(null);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(null);
await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/);
});
});
+28 -25
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
vi.mock('../../src/bridge/highway/highway-client', () => ({
@@ -28,16 +25,15 @@ import { mockBridge } from './_helpers';
describe('actions/group-file', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
count: { fileCount: 42, maxCount: 1000 },
});
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
@@ -46,14 +42,14 @@ describe('actions/group-file', () => {
it('fetchGroupFileCount falls back to defaults on partial response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ count: {} });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ count: {} });
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
});
it('uploadGroupFile skips highway when boolFileExist is true', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: {
retCode: 0,
fileId: 'fid-xyz',
@@ -68,7 +64,7 @@ describe('actions/group-file', () => {
it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: {
retCode: 0,
fileId: 'fid-xyz',
@@ -86,14 +82,14 @@ describe('actions/group-file', () => {
it('uploadGroupFile throws on missing upload response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({});
vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/response missing/);
});
it('uploadGroupFile bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 999, retMsg: 'quota exceeded' },
});
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
@@ -102,22 +98,29 @@ describe('actions/group-file', () => {
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({
qqInfo: { uin: '10001', selfUid: '', findGroupMember: vi.fn(() => null) },
identity: {
uin: '10001',
selfUid: '',
nickname: 'self-nick',
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
},
});
vi.mocked(oidb.resolveUserUid)
vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('target-uid') // target user
.mockResolvedValueOnce('self-uid-resolved'); // self fallback
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true },
});
const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file');
expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' });
expect(oidb.resolveUserUid).toHaveBeenCalledTimes(2);
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
});
it('fetchGroupFiles paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
list: {
retCode: 0,
isEnd: true,
@@ -136,7 +139,7 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: {
retCode: 0,
downloadDns: 'cdn.example.com',
@@ -149,7 +152,7 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: { retCode: 0 },
});
await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'))
@@ -158,29 +161,29 @@ describe('actions/group-file', () => {
it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode)
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ delete: { retCode: 0 } })
.mockResolvedValueOnce({ move: { retCode: 0 } });
await groupFile.deleteGroupFile(bridge as any, 12345, 'fid');
await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[3])).toEqual([3, 5]);
expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].subCmd)).toEqual([3, 5]);
});
it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode)
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ create: { retcode: 0 } })
.mockResolvedValueOnce({ delete: { retcode: 0 } })
.mockResolvedValueOnce({ rename: { retcode: 0 } });
await groupFile.createGroupFileFolder(bridge as any, 1, 'folder');
await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid');
await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[2])).toEqual([0x6D7, 0x6D7, 0x6D7]);
expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].oidbCmd)).toEqual([0x6D7, 0x6D7, 0x6D7]);
});
it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValue({
vi.mocked(oidb.runOidb).mockResolvedValue({
respHead: { retCode: 0 },
download: {
info: { domain: 'media.example.com', urlPath: '/path/x' },
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,8 +10,7 @@ import { mockBridge } from './_helpers';
describe('actions/group-message', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(oidb.runOidb).mockClear();
});
it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => {
@@ -42,7 +38,7 @@ describe('actions/group-message', () => {
it('recallPrivateMessage resolves the target UID before dispatch', async () => {
const bridge = mockBridge();
await msg.recallPrivateMessage(bridge as any, 10001, 100, 200, 123, 1700000000);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
});
@@ -63,7 +59,7 @@ describe('actions/group-message', () => {
const bridge = mockBridge();
await msg.setGroupEssence(bridge as any, 12345, 5, 7, true);
await msg.setGroupEssence(bridge as any, 12345, 5, 7, false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
});
});
+13 -16
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,43 +10,43 @@ import { mockBridge } from './_helpers';
describe('actions/interaction', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
});
it('sendPoke group: groupUin set, friendUin=0', async () => {
const bridge = mockBridge();
await inter.sendPoke(bridge as any, true, 12345, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
});
it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => {
const bridge = mockBridge();
await inter.sendPoke(bridge as any, false, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(payload).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
});
it('sendLike forwards target + count to 0x7e5_104', async () => {
const bridge = mockBridge();
await inter.sendLike(bridge as any, 10001, 3);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0x7e5_104');
expect(call[4]).toMatchObject({ targetUin: 10001, count: 3 });
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x7e5_104');
expect(call.request.value).toMatchObject({ targetUin: 10001, count: 3 });
});
it('setGroupReaction picks _1 for set and _2 for unset', async () => {
const bridge = mockBridge();
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true);
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
});
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
inner: { userInfo: { uin: 10001 } },
cookie: new Uint8Array([0xCA, 0xFE]),
});
@@ -61,7 +58,7 @@ describe('actions/interaction', () => {
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({});
vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([]);
expect(out.isLast).toBe(true);
+8 -10
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -13,12 +10,13 @@ import { mockBridge } from './_helpers';
describe('actions/misc', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
});
it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
translateResp: { dstWords: ['你好', '世界'] },
});
const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']);
@@ -27,7 +25,7 @@ describe('actions/misc', () => {
it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({});
vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
await expect(misc.translateEn2Zh(bridge as any, ['hello']))
.rejects.toThrow(/empty/);
});
@@ -62,7 +60,7 @@ describe('actions/misc', () => {
it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
result: 1, errMsg: 'ok', promptText: 'hi',
});
const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100);
@@ -72,7 +70,7 @@ describe('actions/misc', () => {
it('sendGroupSign dispatches to 0xEB7_1', async () => {
const bridge = mockBridge();
await misc.sendGroupSign(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xEB7_1');
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
});
});
+96 -20
View File
@@ -1,10 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
vi.mock('../../src/bridge/highway/highway-client', () => ({
@@ -25,9 +22,8 @@ import { mockBridge } from './_helpers';
describe('actions/profile', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
@@ -39,33 +35,81 @@ describe('actions/profile', () => {
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
});
it('setOnlineStatus does NOT include the customExt field 4 (varint 0x22 absent in body)', async () => {
const bridge = mockBridge();
await profile.setOnlineStatus(bridge as any, 11, 0, 100);
const [, body] = bridge.sendRawPacket.mock.calls[0]!;
// proto field 4 length-delimited tag = (4 << 3) | 2 = 0x22. The
// body should not contain that byte; if encoder ever leaks an
// empty customExt it'd appear here.
expect(Buffer.from(body).includes(0x22)).toBe(false);
});
it('setDiyOnlineStatus hardcodes status=10 / extStatus=2000 and packs faceId+wording+faceType into customExt', async () => {
const bridge = mockBridge();
await profile.setDiyOnlineStatus(bridge as any, 1234, '摸鱼中', 2);
const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
// Decode the wire bytes back through the same schema to assert
// every field landed in the right place.
const { protoDecode } = await import('../../src/protobuf/decode');
const { SetStatusReqSchema } = await import('../../src/bridge/proto/oidb-action');
const decoded = protoDecode(body as Uint8Array, SetStatusReqSchema);
expect(decoded).toMatchObject({
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId: 1234, text: '摸鱼中', faceType: 2 },
});
});
it('setDiyOnlineStatus surfaces server errors via the same path as setOnlineStatus', async () => {
const bridge = mockBridge();
// Build a response that decodes to errCode != 0.
const { protoEncode } = await import('../../src/protobuf/decode');
const { SetStatusRespSchema } = await import('../../src/bridge/proto/oidb-action');
const respBuf = Buffer.from(protoEncode({ errCode: 1, errMsg: 'denied' }, SetStatusRespSchema));
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
} as any);
await expect(profile.setDiyOnlineStatus(bridge as any, 1, 't', 1)).rejects.toThrow(/denied/);
});
it('setDiyOnlineStatus rejects when the transport itself fails', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
success: false, gotResponse: false, errorCode: -1, errorMessage: 'pipe closed', responseData: null,
} as any);
await expect(profile.setDiyOnlineStatus(bridge as any, 1, 't', 1)).rejects.toThrow(/pipe closed/);
});
it('setProfile is a no-op when both arguments are undefined', async () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any);
expect(oidb.sendOidbAndCheck).not.toHaveBeenCalled();
expect(oidb.runOidb).not.toHaveBeenCalled();
});
it('setProfile only sends non-undefined fields', async () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any, 'New Nick');
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce();
const body: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(body.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
expect(oidb.runOidb).toHaveBeenCalledOnce();
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect((call.request.value as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
});
it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
const bridge = mockBridge();
await profile.setSelfLongNick(bridge as any, 'hello world');
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect((call[4] as any).profile).toEqual({ tag: 102, value: 'hello world' });
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect((call.request.value as any).profile).toEqual({ tag: 102, value: 'hello world' });
});
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge();
await profile.setInputStatus(bridge as any, 10001, 1);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xcd4_1');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
@@ -73,13 +117,45 @@ describe('actions/profile', () => {
await profile.setAvatar(bridge as any, '/some/avatar.png');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
const [, , cmdId] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
expect(cmdId).toBe(90);
expect((extend as Uint8Array).length).toBe(0); // personal avatar has no extra payload
});
it('setGroupAvatar uses cmdId 3000 and packs the Lagrange GroupAvatarExtra constants', async () => {
const bridge = mockBridge();
await profile.setGroupAvatar(bridge as any, 12345, '/some/group-avatar.png');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
expect(cmdId).toBe(3000);
// Decode the extra blob back through the schema and assert every
// protocol-prescribed constant lands where it should.
const { protoDecode } = await import('../../src/protobuf/decode');
const { GroupAvatarExtraSchema } = await import('../../src/bridge/proto/oidb-action');
const decoded = protoDecode(extend as Uint8Array, GroupAvatarExtraSchema);
expect(decoded).toEqual({
type: 101,
groupUin: 12345,
field3: { field1: 1 },
field5: 3,
field6: 1,
});
});
it('setGroupAvatar rejects an empty file before hitting highway', async () => {
const bridge = mockBridge();
const { loadBinarySource } = await import('../../src/bridge/highway/utils');
vi.mocked(loadBinarySource).mockResolvedValueOnce({
bytes: new Uint8Array(0), fileName: 'empty.png',
} as any);
await expect(profile.setGroupAvatar(bridge as any, 1, 'empty.png')).rejects.toThrow(/empty/);
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
});
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
userLikeInfos: [{
uid: 'u',
time: 1700000000n,
@@ -94,13 +170,13 @@ describe('actions/profile', () => {
it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ userLikeInfos: [] });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ userLikeInfos: [] });
await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/);
});
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
const out = await profile.getUnidirectionalFriendList(bridge as any);
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
import type { GroupMemberJoin, QQEventVariant } from '../src/bridge/events';
import type { PacketInfo } from '../src/protocol/types';
@@ -36,14 +37,14 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
class RefreshingBridge extends Bridge {
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
constructor(qqInfo: QQInfo, private readonly refreshedMembers: GroupMemberInfo[]) {
super(qqInfo);
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
}
override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) {
this.qqInfo.updateGroupMember(groupId, member);
this.identity.updateGroupMember(groupId, member);
}
return this.refreshedMembers;
}
@@ -79,9 +80,9 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
describe('Bridge group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => {
const member = makeGroupMember(22222, 'u_new_member');
const qqInfo = new QQInfo(SELF_UIN);
qqInfo.setGroups([makeGroup()]);
const bridge = new RefreshingBridge(qqInfo, [member]);
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const bridge = new RefreshingBridge(identity, [member]);
const seen: GroupMemberJoin[] = [];
bridge.registerCmd('test.member_join', () => [{
@@ -107,8 +108,7 @@ describe('Bridge group member identity refresh', () => {
});
it('remembers UID mappings from realtime request events', () => {
const qqInfo = new QQInfo(SELF_UIN);
const bridge = new Bridge(qqInfo);
const bridge = new Bridge(IdentityService.memory(SELF_UIN));
const events: QQEventVariant[] = [
{
kind: 'friend_request',
@@ -10,7 +10,7 @@ vi.mock('../src/bridge/element-builder', () => ({
describe('Bridge private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => {
const { Bridge } = await import('../src/bridge/bridge');
const { QQInfo } = await import('../src/bridge/qq-info');
const { IdentityService } = await import('../src/bridge/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
@@ -37,7 +37,7 @@ describe('Bridge private media routing', () => {
}
}
const bridge = new TestBridge(new QQInfo('10000'));
const bridge = new TestBridge(IdentityService.memory('10000'));
await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
@@ -0,0 +1,94 @@
// Regression test for the c2c-vs-group businessType asymmetry that made
// private-chat video / record sends bounce with `send private message
// rejected: result=79`. The receive-side decoder
// (msg-push/rich-body-decoder.ts) explicitly treats the businessType
// pairs as:
//
// image : c2c=10, group=20
// video : c2c=11, group=21
// record : c2c=12, group=22
//
// `makeImageElem` always honoured this split (`isGroup ? 20 : 10`).
// `makeVideoElem` and `makePttElem` used to hardcode the group value
// for both scenes, so any c2c video / private voice send arrived at the
// QQ NT server with a businessType the c2c routing path did not
// recognise and got rejected with result=79.
import { describe, expect, it, vi } from 'vitest';
vi.mock('../src/bridge/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
}));
vi.mock('../src/bridge/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])),
}));
vi.mock('../src/bridge/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
}));
import { buildSendElems } from '../src/bridge/element-builder';
const fakeBridge = {} as any;
function commonElem(elem: any): { serviceType: number; businessType: number; pbElem: Uint8Array } {
return elem.commonElem;
}
describe('element-builder / commonElem.businessType per scene', () => {
describe('image', () => {
it('c2c → businessType 10', async () => {
const [elem] = await buildSendElems(
[{ type: 'image', url: 'file:///tmp/a.png' } as any],
{ bridge: fakeBridge, userUid: 'u_peer' },
);
expect(commonElem(elem).serviceType).toBe(48);
expect(commonElem(elem).businessType).toBe(10);
});
it('group → businessType 20', async () => {
const [elem] = await buildSendElems(
[{ type: 'image', url: 'file:///tmp/a.png' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(commonElem(elem).businessType).toBe(20);
});
});
describe('video', () => {
it('c2c → businessType 11 (regression: was 21, server returned result=79)', async () => {
const [elem] = await buildSendElems(
[{ type: 'video', url: 'file:///tmp/clip.mp4' } as any],
{ bridge: fakeBridge, userUid: 'u_peer' },
);
expect(commonElem(elem).serviceType).toBe(48);
expect(commonElem(elem).businessType).toBe(11);
});
it('group → businessType 21', async () => {
const [elem] = await buildSendElems(
[{ type: 'video', url: 'file:///tmp/clip.mp4' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(commonElem(elem).businessType).toBe(21);
});
});
describe('record', () => {
it('c2c → businessType 12 (regression: was 22)', async () => {
const [elem] = await buildSendElems(
[{ type: 'record', url: 'file:///tmp/voice.amr' } as any],
{ bridge: fakeBridge, userUid: 'u_peer' },
);
expect(commonElem(elem).serviceType).toBe(48);
expect(commonElem(elem).businessType).toBe(12);
});
it('group → businessType 22', async () => {
const [elem] = await buildSendElems(
[{ type: 'record', url: 'file:///tmp/voice.amr' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(commonElem(elem).businessType).toBe(22);
});
});
});
@@ -104,7 +104,6 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
const ctx: OneBotInstanceContext = {
uin: SELF_UIN,
selfId: SELF_ID,
qqInfo: {} as never,
bridge: fakeBridge as never,
messageStore: {} as never,
mediaStore: {} as never,
@@ -0,0 +1,99 @@
// E2E for Docker "QQ never logs in + pipe keeps reconnecting" scenario.
//
// Drives the real PipeWatcher + HookManager through repeated same-PID
// pipe up/down cycles via tickNow() and asserts the BridgeManager mock
// is never touched (no login → no Bridge / OneBotInstance / Identity).
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook/hook-manager';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { ManualMapHandle } from '../src/hook/injector';
import type { BridgeManager } from '../src/bridge/manager';
import type { QqHookClient } from '../src/hook/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
async connectAll(_opts: { recv: boolean }) {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
close() {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
}
describe('HookManager — Docker reconnect-without-login leak guard', () => {
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
const PID = 61;
const liveSet = new Set<number>([PID]);
const clients: FakeClient[] = [];
const pipeWatcher = new PipeWatcher({
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
listLivePipes: async () => new Set(liveSet),
intervalMs: 60_000, // manual ticks only
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManager;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
});
// Initial discovery + first connect.
await pipeWatcher.start();
await flush();
await flush();
// Drive 50 pipe up/down cycles with the QQ process staying alive but
// the pipe (= QQ control socket) bouncing every "tick".
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
liveSet.delete(PID);
await pipeWatcher.tickNow();
await flush();
liveSet.add(PID);
await pipeWatcher.tickNow();
await flush();
}
// The "QQ never logs in" hypothesis: BridgeManager should never have
// been told about a login or a disconnect.
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
// Hook layer should hold at most one live client.
const alive = clients.filter(c => !c.isClosed);
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
// Total clients minted = roughly one per up cycle. Sanity bound:
// we must have actually exercised the reconnect path.
expect(clients.length).toBeGreaterThan(1);
manager.dispose();
});
});
@@ -0,0 +1,123 @@
// Regression test for the Docker "QQ-never-logs-in + pipe keeps reconnecting" leak hypothesis.
//
// User-reported pattern (Docker, idle login screen):
// 02:41:23 [Hook] pipe connected: PID=61
// 04:37:55 [Hook] pipe connected: PID=61 (same PID, ~2h later)
// 04:40:44 [Hook] pipe connected: PID=61
// 04:43:48 [Hook] pipe connected: PID=61 → eventual OOM-kill
//
// Hypothesis (H2): every onPipeDown → onPipeUp cycle leaks the prior
// QqHookClient (listeners or socket-ref keeping it pinned in memory),
// so repeated reconnect drives unbounded growth.
//
// This test drives N up/down cycles against a HookSession with a FakeClient
// factory and asserts:
// - at most one client is alive at any point
// - every prior client's EventEmitter listener count drops to 0 after teardown
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook/hook-session';
import type { ManualMapHandle } from '../src/hook/injector';
import type { QqHookClient } from '../src/hook/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { ...this.loginState }; }
close(): void {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
}
function totalListenerCount(emitter: EventEmitter): number {
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
}
const flush = () => new Promise<void>(r => setImmediate(r));
describe('HookSession — pipe reconnect with QQ never logging in', () => {
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
await session.load();
session.onPipeUp();
await flush();
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
const alive = clients.filter(c => !c.isClosed);
expect.soft(clients.length).toBeGreaterThan(1);
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
.toBeLessThanOrEqual(1);
});
it('drops all listeners from each torn-down client', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
await session.load();
session.onPipeUp();
await flush();
const CYCLES = 20;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
// Every client except the current one should have 0 listeners attached.
// (HookSession.tearDownClient does client.removeAllListeners().)
for (let i = 0; i < clients.length - 1; i++) {
const lc = totalListenerCount(clients[i]);
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
.toBe(0);
}
});
});
+86 -31
View File
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'fs';
import path from 'path';
import { IdentityService } from '../src/bridge/identity-service';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '../src/bridge/qq-info';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
@@ -60,8 +60,7 @@ describe('IdentityService', () => {
const dbPath = tempDbPath('persist');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
@@ -69,12 +68,11 @@ describe('IdentityService', () => {
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
expect(qqInfo.findFriend(22222)?.uid).toBe('u_friend');
expect(qqInfo.findGroup(GROUP_ID)?.groupName).toBe('group');
expect(qqInfo.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(GROUP_ID)?.groupName).toBe('group');
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member');
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
@@ -88,8 +86,7 @@ describe('IdentityService', () => {
const second = makeMember(44444, 'u_second');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [first, second]);
identity.rememberGroupMembers(GROUP_ID, [second]);
@@ -97,11 +94,10 @@ describe('IdentityService', () => {
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
expect(qqInfo.findGroupMember(GROUP_ID, first.uin)).toBeNull();
expect(qqInfo.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
expect(identity.findGroupMember(GROUP_ID, first.uin)).toBeNull();
expect(identity.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
// Historical identity remains available for UID/UIN resolution.
expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid);
@@ -114,8 +110,7 @@ describe('IdentityService', () => {
const member = makeMember(33333, 'u_member');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
@@ -125,11 +120,10 @@ describe('IdentityService', () => {
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
expect(qqInfo.findFriend(22222)).toBeNull();
expect(qqInfo.findGroup(GROUP_ID)).toBeNull();
expect(identity.findFriend(22222)).toBeNull();
expect(identity.findGroup(GROUP_ID)).toBeNull();
// Identity mappings remain useful for historical events/actions.
expect(identity.findUidByUin(22222)).toBe('u_friend');
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
@@ -143,8 +137,7 @@ describe('IdentityService', () => {
const member = makeMember(33333, 'u_member');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
@@ -152,10 +145,9 @@ describe('IdentityService', () => {
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
expect(qqInfo.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
identity.close();
@@ -166,8 +158,7 @@ describe('IdentityService', () => {
const dbPath = tempDbPath('request-events');
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberRequestIdentity({
uid: 'u_friend_request',
uin: 55555,
@@ -183,15 +174,79 @@ describe('IdentityService', () => {
}
{
const qqInfo = new QQInfo(SELF_UIN);
const identity = new IdentityService(qqInfo, dbPath);
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(qqInfo.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
expect(identity.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close();
}
});
});
describe('IdentityService.resolveUid', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '' };
}
it('returns the cached uid without invoking the fetcher', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberRequestIdentity({ uid: 'u_known', uin: 12345 });
const fetchProfile = vi.fn(async (uin: number) => makeProfile(uin, 'should-not-be-used'));
identity.setFetcher({ fetchProfile });
await expect(identity.resolveUid(12345)).resolves.toBe('u_known');
expect(fetchProfile).not.toHaveBeenCalled();
});
it('falls back to fetchProfile on miss and returns the resolved uid', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfile = vi.fn(async (uin: number) => {
// Simulate the bridge writing the result back via rememberUserProfile.
identity.rememberUserProfile(makeProfile(uin, 'u_fetched'));
return makeProfile(uin, 'u_fetched');
});
identity.setFetcher({ fetchProfile });
await expect(identity.resolveUid(99999)).resolves.toBe('u_fetched');
expect(fetchProfile).toHaveBeenCalledWith(99999);
});
it('throws when neither cache nor fetcher can produce a uid', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.setFetcher({ fetchProfile: async (uin) => makeProfile(uin, '') });
await expect(identity.resolveUid(99999)).rejects.toThrow(/failed to resolve UID/);
});
it('tries fetchGroupMemberList before fetchProfile when groupId is provided', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([{
groupId: GROUP_ID, groupName: '', remark: '',
memberCount: 0, memberMax: 0, members: new Map(),
}]);
const fetchProfile = vi.fn(async (uin: number) => makeProfile(uin, 'u_via_profile'));
const fetchGroupMemberList = vi.fn(async (groupId: number) => {
// Roster fetch should populate the cache.
identity.rememberGroupMembers(groupId, [makeMember(77777, 'u_via_roster')]);
return [];
});
identity.setFetcher({ fetchProfile, fetchGroupMemberList });
await expect(identity.resolveUid(77777, GROUP_ID)).resolves.toBe('u_via_roster');
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
expect(fetchProfile).not.toHaveBeenCalled();
});
it('throws on invalid (zero / negative) uin without calling fetcher', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfile = vi.fn();
identity.setFetcher({ fetchProfile });
await expect(identity.resolveUid(0)).rejects.toThrow(/invalid uin/);
expect(fetchProfile).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -258,7 +258,7 @@ describe('parseMessage', () => {
}, respSchema);
const bridge = {
qqInfo: { uin: '10000' },
identity: { uin: '10000' },
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
+13 -8
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push-handler';
import { QQInfo, type GroupMemberInfo, type QQGroupInfo } from '../src/bridge/qq-info';
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push';
import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
import { PushMsgSchema } from '../src/bridge/proto/message';
import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify';
import type { GroupMemberJoin } from '../src/bridge/events';
@@ -36,10 +37,11 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
};
}
function makeQqInfo(members: GroupMemberInfo[] = []): QQInfo {
const qqInfo = new QQInfo(SELF_UIN);
qqInfo.setGroups([makeGroup(members)]);
return qqInfo;
function makeIdentity(members: GroupMemberInfo[] = []): IdentityService {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup(members)]);
if (members.length) identity.rememberGroupMembers(GROUP_ID, members);
return identity;
}
function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo {
@@ -73,7 +75,7 @@ function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin =
describe('parseMsgPush group member increase', () => {
it('does not fall back to the group id when a joining uid is unresolved', () => {
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeQqInfo()) as GroupMemberJoin[];
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeIdentity()) as GroupMemberJoin[];
expect(event.kind).toBe('group_member_join');
expect(event.groupId).toBe(GROUP_ID);
@@ -85,7 +87,10 @@ describe('parseMsgPush group member increase', () => {
it('resolves joining uid and operator uid from the member cache when available', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(makeGroupIncreasePacket(member.uid, operator.uid), makeQqInfo([member, operator])) as GroupMemberJoin[];
const [event] = parseMsgPush(
makeGroupIncreasePacket(member.uid, operator.uid),
makeIdentity([member, operator]),
) as GroupMemberJoin[];
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(operator.uin);
@@ -0,0 +1,297 @@
// First real OneBot unit test that exercises a module purely through
// BridgeInterface — no concrete Bridge, no SQLite, no native packet
// sender, no BridgeManager. This is the testability win that PR4 + PR5
// were supposed to unlock; the file exists to prove it.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo,
} from '../../src/bridge/qq-info';
import {
getFriendList,
getGroupInfo,
getGroupList,
getGroupMemberInfo,
getGroupMemberList,
getLoginInfo,
getStrangerInfo,
} from '../../src/onebot/modules/contact-actions';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
/**
* A typed BridgeInterface where every property is undefined by default;
* accessing an un-stubbed property throws with a clear message so tests
* fail loudly if they exercise a code path the fake hasn't been told
* about. Tests just spread the methods they care about.
*/
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
/** Same Proxy trick for the IdentityService surface that contact-actions touches. */
function fakeIdentity(overrides: Record<string, unknown> = {}): BridgeInterface['identity'] {
return new Proxy(overrides as any, {
get(target, prop) {
if (prop in target) return target[prop];
throw new Error(`fakeIdentity: '${String(prop)}' was not stubbed for this test`);
},
});
}
// ─── Fixture builders ───
function makeFriend(uin: number, nickname: string, remark = ''): FriendInfo {
return { uin, uid: `u_${uin}`, nickname, remark };
}
function makeGroup(groupId: number, groupName: string, members: GroupMemberInfo[] = []): QQGroupInfo {
return {
groupId, groupName, remark: '',
memberCount: members.length, memberMax: 500,
members: new Map(members.map((m) => [m.uin, m])),
};
}
function makeMember(uin: number, nickname: string, card = ''): GroupMemberInfo {
return {
uin, uid: `u_${uin}`, nickname, card,
role: 'member', level: 1, title: '',
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
};
}
function makeProfile(uin: number, nickname: string, sex: 'male' | 'female' | 'unknown' = 'unknown', age = 0): UserProfileInfo {
return {
uin, uid: `u_${uin}`, nickname, remark: '', qid: '', sex, age, sign: '', avatar: '',
};
}
// ─── Tests ───
describe('onebot/contact-actions / getLoginInfo', () => {
it('returns user_id parsed from uin and nickname from identity', () => {
const ref = {
uin: '10001',
bridge: fakeBridge({ identity: fakeIdentity({ nickname: 'self-nick' }) }),
} as unknown as OneBotInstanceContext;
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: 'self-nick' });
});
it('falls back to the uin string when identity nickname is empty', () => {
const ref = {
uin: '10001',
bridge: fakeBridge({ identity: fakeIdentity({ nickname: '' }) }),
} as unknown as OneBotInstanceContext;
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: '10001' });
});
});
describe('onebot/contact-actions / getFriendList', () => {
it('returns the fetched list mapped to OneBot shape', async () => {
const bridge = fakeBridge({
fetchFriendList: vi.fn(async () => [makeFriend(22222, 'alice', 'best-friend')]),
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
expect(bridge.fetchFriendList).toHaveBeenCalledOnce();
});
it('falls back to identity.friends on fetch failure', async () => {
const cached = [makeFriend(33333, 'bob')];
const bridge = fakeBridge({
fetchFriendList: vi.fn(async () => { throw new Error('network down'); }),
identity: fakeIdentity({ friends: cached }),
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 33333, nickname: 'bob', remark: '' }]);
});
});
describe('onebot/contact-actions / getGroupList', () => {
it('triggers fetch when the in-memory roster is empty', async () => {
const fetched = [makeGroup(100, 'Group A')];
// `groups` starts empty; the fetch callback flips it to mimic
// bridge.fetchGroupList writing back through identity.rememberGroups.
let groups: QQGroupInfo[] = [];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }),
identity: fakeIdentity({
get groups() { return groups; },
}),
});
const out = await getGroupList(bridge);
expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
expect(out).toEqual([{
group_id: 100, group_name: 'Group A',
member_count: 0, max_member_count: 500,
}]);
});
it('skips fetch when cache is populated and noCache is omitted', async () => {
const cached = [makeGroup(200, 'Group B')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge);
expect(bridge.fetchGroupList).not.toHaveBeenCalled();
});
it('forces fetch when noCache=true even with a populated cache', async () => {
const cached = [makeGroup(300, 'Group C')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => cached),
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge, true);
expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
});
it('serves the stale cache when the fetch path throws', async () => {
const cached = [makeGroup(400, 'Group D')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { throw new Error('boom'); }),
identity: fakeIdentity({ groups: cached }),
});
const out = await getGroupList(bridge, true);
expect(out[0]).toMatchObject({ group_id: 400, group_name: 'Group D' });
});
});
describe('onebot/contact-actions / getGroupInfo', () => {
it('returns the cached group without refreshing when group is known and noCache is false', async () => {
const cached = makeGroup(500, 'Group E');
const findGroup = vi.fn((groupId: number) => groupId === 500 ? cached : null);
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ findGroup }),
});
const out = await getGroupInfo(bridge, 500);
expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' });
expect(bridge.fetchGroupList).not.toHaveBeenCalled();
});
it('triggers fetch when the group is unknown to the cache', async () => {
const cached = makeGroup(600, 'Group F');
let known = false;
const findGroup = vi.fn((groupId: number) => (known && groupId === 600) ? cached : null);
const fetchGroupList = vi.fn(async () => { known = true; return [cached]; });
const bridge = fakeBridge({
fetchGroupList,
identity: fakeIdentity({ findGroup }),
});
const out = await getGroupInfo(bridge, 600);
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(out).toMatchObject({ group_id: 600, group_name: 'Group F' });
});
it('returns null when the group remains unknown after fetch', async () => {
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ findGroup: () => null }),
});
expect(await getGroupInfo(bridge, 700)).toBeNull();
});
});
describe('onebot/contact-actions / getGroupMemberList', () => {
it('returns the fetched roster mapped to OneBot shape', async () => {
const members = [makeMember(11, 'alice', 'A'), makeMember(22, 'bob', 'B')];
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => members),
});
const out = await getGroupMemberList(bridge, 800);
expect(out).toHaveLength(2);
expect(out[0]).toMatchObject({ group_id: 800, user_id: 11, nickname: 'alice', card: 'A' });
});
it('falls back to the cached roster when fetch fails', async () => {
const cached = makeGroup(900, '', [makeMember(33, 'cached')]);
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({
findGroup: (gid: number) => gid === 900 ? cached : null,
}),
});
const out = await getGroupMemberList(bridge, 900);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({ user_id: 33, nickname: 'cached' });
});
it('returns [] when no roster is known and fetch fails', async () => {
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({ findGroup: () => null }),
});
expect(await getGroupMemberList(bridge, 999)).toEqual([]);
});
});
describe('onebot/contact-actions / getGroupMemberInfo', () => {
it('returns the cached member when present and noCache is false', async () => {
const member = makeMember(44, 'dave', 'D');
const cached = makeGroup(1000, '', [member]);
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => []),
identity: fakeIdentity({
findGroupMember: (gid: number, uin: number) =>
gid === 1000 && uin === 44 ? member : null,
}),
});
const out = await getGroupMemberInfo(bridge, 1000, 44);
expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' });
expect(bridge.fetchGroupMemberList).not.toHaveBeenCalled();
});
it('triggers fetch when member is unknown and re-queries the cache', async () => {
const member = makeMember(55, 'eve');
let known = false;
const findGroupMember = vi.fn((gid: number, uin: number) =>
(known && gid === 1100 && uin === 55) ? member : null,
);
const fetchGroupMemberList = vi.fn(async () => { known = true; return [member]; });
const bridge = fakeBridge({
fetchGroupMemberList,
identity: fakeIdentity({ findGroupMember }),
});
const out = await getGroupMemberInfo(bridge, 1100, 55);
expect(fetchGroupMemberList).toHaveBeenCalledOnce();
expect(out).toMatchObject({ user_id: 55, nickname: 'eve' });
});
});
describe('onebot/contact-actions / getStrangerInfo', () => {
it('returns a fetched profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => makeProfile(55555, 'Eve', 'female', 25)),
});
const out = await getStrangerInfo(bridge, 55555);
expect(out).toMatchObject({ user_id: 55555, nickname: 'Eve', sex: 'female', age: 25 });
});
it('falls back to identity.findUserProfile when fetch fails but the profile is cached', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({
findUserProfile: (uin: number) =>
uin === 66666 ? makeProfile(66666, 'Frank', 'male', 30) : null,
}),
});
const out = await getStrangerInfo(bridge, 66666);
expect(out).toMatchObject({ user_id: 66666, nickname: 'Frank' });
});
it('returns null when neither fetch nor cache produces a profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({ findUserProfile: () => null }),
});
expect(await getStrangerInfo(bridge, 99999)).toBeNull();
});
});
@@ -0,0 +1,533 @@
// End-to-end OneBot action tests for the napcat-parity surface added in
// Tier 1 + Tier 2: send_packet, bot_exit, nc_*, group-todo, AI voice,
// and the rewired ignored-notifies family. We drive everything through
// the public `ApiHandler.handle()` entry point so the wiring (including
// param coercion, retcode shape) is part of what's under test.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ApiHandler, type ApiActionContext } from '../../src/onebot/api-handler';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '../../src/bridge/qq-info';
import type { MessageMeta } from '../../src/onebot/types';
function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
return {
isGroup: true,
targetId: 100,
sequence: 555,
eventName: 'group_message',
clientSequence: 0,
random: 0,
timestamp: 0,
...overrides,
};
}
/**
* Build a BridgeInterface stub that throws on any method we haven't
* pre-stubbed for the test. Same pattern as contact-actions.test.ts —
* keeps tests honest about which surface they actually need.
*/
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
},
});
}
/**
* Build the minimum ApiActionContext needed for the tested actions.
* Anything not stubbed throws on access — keeps the dependency surface
* explicit. Only fields the tested actions read are populated.
*/
function fakeCtx(bridge: BridgeInterface, overrides: Partial<ApiActionContext> = {}): ApiActionContext {
const base = {
bridge,
getMessageMeta: () => null,
getMessage: () => null,
getLoginInfo: () => ({ userId: 1, nickname: '' }),
isOnline: () => true,
canSendImage: () => true,
canSendRecord: () => true,
getDownloadRKeys: async () => [],
...overrides,
};
return new Proxy(base as ApiActionContext, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeCtx: '${String(prop)}' was not stubbed`);
},
});
}
function makeHandler(ctx: ApiActionContext): ApiHandler {
return new ApiHandler(ctx);
}
// ─── Tier 1: send_packet / .send_packet ───
describe('extended-actions / send_packet', () => {
it('hex-decodes data, calls Bridge.sendRawPacket, hex-encodes the response', async () => {
const sendRawPacket: BridgeInterface['sendRawPacket'] = vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from([0xDE, 0xAD, 0xBE, 0xEF]),
}));
const bridge = fakeBridge({ sendRawPacket });
const h = makeHandler(fakeCtx(bridge));
const res = await h.handle('send_packet', { cmd: 'Some.Cmd', data: 'cafebabe', rsp: true });
const spy = vi.mocked(sendRawPacket);
expect(spy).toHaveBeenCalledOnce();
const sentBody = spy.mock.calls[0]![1];
expect(Buffer.from(sentBody).toString('hex')).toBe('cafebabe');
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: 'deadbeef' });
});
it('.send_packet shares the same handler', async () => {
const sendRawPacket = vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0),
}));
const h = makeHandler(fakeCtx(fakeBridge({ sendRawPacket: sendRawPacket as any })));
const res = await h.handle('.send_packet', { cmd: 'C', data: '' });
expect(res.status).toBe('ok');
expect(sendRawPacket).toHaveBeenCalledOnce();
});
it('with rsp=false returns null and ignores responseData', async () => {
const bridge = fakeBridge({
sendRawPacket: (async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from('00ff', 'hex'),
})) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '', rsp: false });
expect(res).toMatchObject({ status: 'ok', data: null });
});
it('rejects missing cmd', async () => {
const bridge = fakeBridge({ sendRawPacket: vi.fn() as any });
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: '', data: '' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
it('rejects malformed hex', async () => {
const sendRawPacket = vi.fn();
const bridge = fakeBridge({ sendRawPacket: sendRawPacket as any });
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'ZZZZ' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
expect(sendRawPacket).not.toHaveBeenCalled();
});
it('rejects odd-length hex', async () => {
const bridge = fakeBridge({ sendRawPacket: vi.fn() as any });
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'abc' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
it('propagates wire-level failure as action_failed', async () => {
const bridge = fakeBridge({
sendRawPacket: (async () => ({
success: false, gotResponse: false, errorCode: -1, errorMessage: 'no sender', responseData: null,
})) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '' });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'no sender' });
});
});
// ─── Tier 1: bot_exit ───
describe('extended-actions / bot_exit', () => {
let exitSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
vi.useFakeTimers();
exitSpy = vi.spyOn(process, 'exit').mockImplementation(((_code?: number) => undefined) as any);
});
afterEach(() => {
vi.useRealTimers();
exitSpy.mockRestore();
});
it('returns ok immediately, then exits on the deferred timer', async () => {
const h = makeHandler(fakeCtx(fakeBridge()));
const res = await h.handle('bot_exit', {});
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
expect(exitSpy).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
expect(exitSpy).toHaveBeenCalledWith(0);
});
});
// ─── Tier 1: nc_get_packet_status / nc_get_rkey ───
describe('extended-actions / nc_get_packet_status', () => {
it('reports healthy with no dependency on bridge', async () => {
const h = makeHandler(fakeCtx(fakeBridge()));
const res = await h.handle('nc_get_packet_status', {});
expect(res).toEqual({ status: 'ok', retcode: 0, data: null });
});
});
describe('extended-actions / nc_get_rkey', () => {
it('reuses the same data the get_rkey handler returns', async () => {
const ctx = fakeCtx(fakeBridge(), {
getDownloadRKeys: async () => [{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }],
});
const h = makeHandler(ctx);
const a = await h.handle('get_rkey', {});
const b = await h.handle('nc_get_rkey', {});
expect(b).toEqual(a);
expect(b.data).toEqual([{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }]);
});
});
// ─── Tier 1: group-request ignored / shut list / ignore-add ───
function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 999,
groupName: 'g',
targetUid: 'u_t',
targetUin: 5555,
targetName: 'target',
invitorUid: 'u_i',
invitorUin: 7777,
invitorName: 'inviter',
operatorUid: 'u_o',
operatorUin: 8888,
operatorName: 'op',
sequence: 42,
state: 1,
eventType: 7,
comment: 'pls',
filtered: true,
...overrides,
};
}
describe('extended-actions / get_group_ignored_notifies', () => {
it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered ? [fakeFilteredRequest()] : []
);
const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any });
const h = makeHandler(fakeCtx(bridge));
const res = await h.handle('get_group_ignored_notifies', {});
expect(fetchGroupRequests).toHaveBeenCalledWith(true);
expect(res.status).toBe('ok');
expect(res.data).toEqual([{
group_id: 999,
group_name: 'g',
request_id: 42,
requester_uin: 5555,
requester_nick: 'target',
message: 'pls',
checked: false, // state == 1 → un-checked
actor: 8888,
invitor_uin: 7777,
invitor_nick: 'inviter',
flag: '7:999:u_t:filtered',
}]);
});
it('returns [] when the fetch throws', async () => {
const bridge = fakeBridge({
fetchGroupRequests: (async () => { throw new Error('boom'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignored_notifies', {});
expect(res).toMatchObject({ status: 'ok', data: [] });
});
});
describe('extended-actions / get_group_ignore_add_request', () => {
it('projects the same filtered list into napcat\'s ignore-add-request shape', async () => {
const bridge = fakeBridge({
fetchGroupRequests: (async () => [fakeFilteredRequest({ state: 2 })]) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignore_add_request', {});
expect(res.status).toBe('ok');
expect(res.data).toEqual([{
request_id: 42,
invitor_uin: 7777,
invitor_nick: 'inviter',
group_id: 999,
message: 'pls',
group_name: 'g',
checked: true, // state == 2 → checked
actor: 8888,
requester_nick: 'target',
}]);
});
});
describe('extended-actions / get_group_shut_list', () => {
it('returns empty list (oidb not yet wrapped)', async () => {
const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {});
expect(res).toEqual({ status: 'ok', retcode: 0, data: [] });
});
});
// ─── Tier 1: delete_group_folder alias ───
describe('extended-actions / delete_group_folder', () => {
it('forwards to bridge.deleteGroupFileFolder', async () => {
const deleteGroupFileFolder = vi.fn(async () => {});
const bridge = fakeBridge({ deleteGroupFileFolder: deleteGroupFileFolder as any });
const res = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', {
group_id: 100, folder_id: 'fid-1',
});
expect(deleteGroupFileFolder).toHaveBeenCalledWith(100, 'fid-1');
expect(res.status).toBe('ok');
});
it('rejects missing fields', async () => {
const bridge = fakeBridge({ deleteGroupFileFolder: vi.fn() as any });
const r1 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { folder_id: 'x' });
const r2 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { group_id: 1 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
// ─── Tier 2: group todo ───
describe('extended-actions / set_/complete_/cancel_group_todo', () => {
it.each([
['set_group_todo', 'setGroupTodo'],
['complete_group_todo', 'completeGroupTodo'],
['cancel_group_todo', 'cancelGroupTodo'],
] as const)('%s resolves message meta then calls bridge.%s with the sequence', async (action, method) => {
const bridgeMethod = vi.fn(async () => {});
const bridge = fakeBridge({ [method]: bridgeMethod } as any);
const ctx = fakeCtx(bridge, {
getMessageMeta: (id: number) => id === 7 ? fakeMeta({ targetId: 100, sequence: 555 }) : null,
});
const res = await makeHandler(ctx).handle(action, { group_id: 100, message_id: 7 });
expect(res.status).toBe('ok');
expect(bridgeMethod).toHaveBeenCalledWith(100, 555n);
});
it('rejects when message meta is missing', async () => {
const ctx = fakeCtx(fakeBridge(), { getMessageMeta: () => null });
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 1, message_id: 9999 });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'message not found' });
});
it('rejects when message belongs to a different chat', async () => {
const ctx = fakeCtx(fakeBridge(), {
getMessageMeta: () => fakeMeta({ targetId: 222 }),
});
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects when message is a private message', async () => {
const ctx = fakeCtx(fakeBridge(), {
getMessageMeta: () => fakeMeta({ isGroup: false }),
});
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects missing params', async () => {
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 });
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { group_id: 1 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
// ─── Tier 2: nc_get_user_status ───
describe('extended-actions / nc_get_user_status', () => {
it('returns whatever bridge.getStrangerStatus reports', async () => {
const getStrangerStatus = vi.fn(async () => ({ status: 10, ext_status: 0x1234 }));
const bridge = fakeBridge({ getStrangerStatus: getStrangerStatus as any });
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 999 });
expect(getStrangerStatus).toHaveBeenCalledWith(999);
expect(res).toMatchObject({ status: 'ok', data: { status: 10, ext_status: 0x1234 } });
});
it('reports action_failed when bridge returns null', async () => {
const bridge = fakeBridge({ getStrangerStatus: (async () => null) as any });
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects missing user_id', async () => {
const bridge = fakeBridge({ getStrangerStatus: vi.fn() as any });
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', {});
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
// ─── Tier 2: AI voice trio ───
describe('extended-actions / get_ai_characters', () => {
it('flattens server categories into {type, characters[]}', async () => {
const fetchAiVoiceList = vi.fn(async () => [{
category: 'cute',
voices: [
{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://a' },
{ voiceId: 'v2', voiceDisplayName: 'V2', voiceExampleUrl: 'http://b' },
],
}]);
const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any });
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', {
group_id: 100, chat_type: 1,
});
expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1);
expect(res.data).toEqual([{
type: 'cute',
characters: [
{ character_id: 'v1', character_name: 'V1', preview_url: 'http://a' },
{ character_id: 'v2', character_name: 'V2', preview_url: 'http://b' },
],
}]);
});
it('defaults chat_type to 1 (Sound) when unspecified', async () => {
const fetchAiVoiceList = vi.fn(async () => []);
const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any });
await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 });
expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1);
});
it('surfaces bridge errors as action_failed', async () => {
const bridge = fakeBridge({
fetchAiVoiceList: (async () => { throw new Error('rate limited'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'rate limited' });
});
});
describe('extended-actions / get_ai_record', () => {
it('feeds IndexNode from fetchAiVoice into fetchGroupPttUrlByNode and returns the URL', async () => {
const node = { fileUuid: 'voice-uuid' };
const fetchAiVoice = vi.fn(async () => node);
const fetchGroupPttUrlByNode = vi.fn(async () => 'http://voice.silk');
const bridge = fakeBridge({
fetchAiVoice: fetchAiVoice as any,
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', {
group_id: 100, character: 'v1', text: 'hello',
});
expect(fetchAiVoice).toHaveBeenCalledWith(100, 'v1', 'hello', 1);
expect(fetchGroupPttUrlByNode).toHaveBeenCalledWith(100, node);
expect(res).toMatchObject({ status: 'ok', data: 'http://voice.silk' });
});
it('rejects missing fields', async () => {
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { character: 'v', text: 't' });
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, text: 't' });
const r3 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, character: 'v' });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r3).toMatchObject({ status: 'failed', retcode: 1400 });
});
it('reports action_failed when synthesis exhausts retries', async () => {
const bridge = fakeBridge({
fetchAiVoice: (async () => { throw new Error('AI voice synthesis did not complete'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', {
group_id: 1, character: 'v', text: 't',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
});
describe('extended-actions / send_group_ai_record', () => {
it('side-effects fetchAiVoice (no URL fetch) and returns message_id=0', async () => {
const fetchAiVoice = vi.fn(async () => ({ fileUuid: 'uuid' }));
const fetchGroupPttUrlByNode = vi.fn();
const bridge = fakeBridge({
fetchAiVoice: fetchAiVoice as any,
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_group_ai_record', {
group_id: 100, character: 'v', text: 'hi',
});
expect(fetchAiVoice).toHaveBeenCalledOnce();
expect(fetchGroupPttUrlByNode).not.toHaveBeenCalled();
expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } });
});
});
// ─── Tier 3: set_diy_online_status ───
describe('extended-actions / set_diy_online_status', () => {
it('coerces face_id / face_type from string-or-number and forwards to bridge.setDiyOnlineStatus', async () => {
const setDiyOnlineStatus = vi.fn(async () => {});
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', {
face_id: '1234',
face_type: '2',
wording: '摸鱼中',
});
expect(res.status).toBe('ok');
expect(setDiyOnlineStatus).toHaveBeenCalledWith(1234, '摸鱼中', 2);
});
it('defaults face_type to 1 when omitted, wording to empty string', async () => {
const setDiyOnlineStatus = vi.fn(async () => {});
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', { face_id: 99 });
expect(setDiyOnlineStatus).toHaveBeenCalledWith(99, '', 1);
});
it('rejects missing face_id', async () => {
const setDiyOnlineStatus = vi.fn();
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', { wording: 'x' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
expect(setDiyOnlineStatus).not.toHaveBeenCalled();
});
it('surfaces bridge errors as action_failed with the original message', async () => {
const bridge = fakeBridge({
setDiyOnlineStatus: (async () => { throw new Error('denied'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', {
face_id: 1, wording: 'x',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'denied' });
});
});
// ─── set_group_portrait (Lagrange-protocol highway upload, cmdId 3000) ───
describe('extended-actions / set_group_portrait', () => {
it('forwards group_id + file to bridge.setGroupAvatar', async () => {
const setGroupAvatar = vi.fn(async () => {});
const bridge = fakeBridge({ setGroupAvatar: setGroupAvatar as any });
const res = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', {
group_id: 12345, file: '/tmp/avatar.png',
});
expect(res.status).toBe('ok');
expect(setGroupAvatar).toHaveBeenCalledWith(12345, '/tmp/avatar.png');
});
it('rejects missing group_id or file', async () => {
const setGroupAvatar = vi.fn();
const bridge = fakeBridge({ setGroupAvatar: setGroupAvatar as any });
const r1 = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', { file: 'x' });
const r2 = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', { group_id: 1 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
expect(setGroupAvatar).not.toHaveBeenCalled();
});
it('surfaces highway / decode errors as action_failed', async () => {
const bridge = fakeBridge({
setGroupAvatar: (async () => { throw new Error('highway 500'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', {
group_id: 1, file: 'x.png',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'highway 500' });
});
});
+19 -22
View File
@@ -3,10 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock the OIDB shim so we can control what `forceFetchClientKey` and
// `getPSkey` see without standing up a Bridge.
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndDecode: vi.fn(async () => ({})),
sendOidbAndCheck: vi.fn(async () => undefined),
resolveUserUid: vi.fn(async () => 'uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
runOidb: vi.fn(async () => ({})),
}));
// Mock the actual HTTP cookie fetch.
@@ -29,13 +26,13 @@ import {
getCredentials,
} from '../../src/bridge/web-actions/cookies';
const bridge = { qqInfo: { uin: '10001' } } as any;
const bridge = { identity: { uin: '10001' } } as any;
describe('cookies — forceFetchClientKey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600,
});
const out = await forceFetchClientKey(bridge);
@@ -43,17 +40,17 @@ describe('cookies — forceFetchClientKey', () => {
});
it('falls back to default keyIndex/expireTime when the response omits them', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck' });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck' });
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' });
});
});
describe('cookies — getPSkey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
it('folds pskeyItems into a domain → pskey Map', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' },
@@ -69,12 +66,12 @@ describe('cookies — getPSkey', () => {
describe('cookies — getCookies', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('builds the ptlogin2 jump URL with the right query params', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({
p_skey: 'psk',
skey: 'sk',
@@ -91,7 +88,7 @@ describe('cookies — getCookies', () => {
});
it('falls back to getPSkey when p_skey is missing in the cookie response', async () => {
vi.mocked(oidb.sendOidbAndDecode)
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey
.mockResolvedValueOnce({ // getPSkey
pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }],
@@ -103,7 +100,7 @@ describe('cookies — getCookies', () => {
});
it('returns whatever cookies it got if getPSkey fallback throws', async () => {
vi.mocked(oidb.sendOidbAndDecode)
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('pskey unavailable'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' });
@@ -115,23 +112,23 @@ describe('cookies — getCookies', () => {
describe('cookies — getSKey', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('returns skey from the qzone-targeted ptlogin2 jump', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' });
expect(await getSKey(bridge)).toBe('the-skey');
});
it('throws when clientKey comes back empty', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: '' });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: '' });
await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/);
});
it('throws when the jump response omits skey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/);
});
@@ -150,21 +147,21 @@ describe('cookies — pure helpers', () => {
});
it('getCookiesStr: joins cookies with "; "', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCookiesStr(bridge, 'qun.qq.com');
expect(out).toBe('p_skey=p; skey=s');
});
it('getCsrfToken: combines getSKey + getBknFromSKey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' });
const csrf = await getCsrfToken(bridge);
expect(csrf).toBe(getBknFromSKey('abc'));
});
it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCredentials(bridge, 'qun.qq.com');
@@ -174,7 +171,7 @@ describe('cookies — pure helpers', () => {
});
it('getCredentials: token is 0 when no skey/p_skey available', async () => {
vi.mocked(oidb.sendOidbAndDecode)
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('no pskey'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/runtime",
"version": "1.7.9",
"version": "1.8.1",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "[email protected]"
},
"version": "1.7.9",
"version": "1.8.1",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+18
View File
@@ -122,6 +122,24 @@ export const SNOWLUMA_ACTIONS = [
'rename_group_file',
'get_file',
'.send_packet',
// napcat-parity extensions (Tier 1 + Tier 2)
'send_packet',
'bot_exit',
'nc_get_packet_status',
'nc_get_rkey',
'nc_get_user_status',
'get_group_ignore_add_request',
'delete_group_folder',
'set_group_todo',
'complete_group_todo',
'cancel_group_todo',
// Tier 3: DIY status
'set_diy_online_status',
// AI voice trio
'get_ai_characters',
'get_ai_record',
'send_group_ai_record',
] as const satisfies readonly (keyof SnowLumaActionMap)[];
export type SnowLumaKnownAction = typeof SNOWLUMA_ACTIONS[number];
+31 -1
View File
@@ -60,6 +60,13 @@ import type {
UploadPrivateFileParams,
UserIdParams,
QuickOperationParams,
SetDiyOnlineStatusParams,
NcGetUserStatusParams,
GroupTodoParams,
GetAiCharactersParams,
AiVoiceParams,
DeleteGroupFolderParams,
SendPacketParams,
} from './params';
import type {
CapabilityInfo,
@@ -84,6 +91,9 @@ import type {
UploadForwardResult,
UrlSafetyInfo,
VersionInfo,
AiCharacterCategory,
UserOnlineStatus,
SendGroupAiRecordResult,
} from './results';
export type ActionData = JsonValue;
@@ -209,7 +219,27 @@ export interface SnowLumaActionMap {
trans_group_file: { params: JsonObject; data: JsonValue };
rename_group_file: { params: JsonObject; data: JsonValue };
get_file: { params: GetMediaParams; data: JsonValue };
'.send_packet': { params: JsonObject; data: JsonValue };
'.send_packet': { params: SendPacketParams; data: string };
// — napcat-parity extensions (Tier 1 + Tier 2) —
send_packet: { params: SendPacketParams; data: string };
bot_exit: { params: JsonObject; data: EmptyData };
nc_get_packet_status: { params: JsonObject; data: JsonValue };
nc_get_rkey: { params: JsonObject; data: JsonObject[] };
nc_get_user_status: { params: NcGetUserStatusParams; data: UserOnlineStatus };
get_group_ignore_add_request: { params: JsonObject; data: JsonArray };
delete_group_folder: { params: DeleteGroupFolderParams; data: EmptyData };
set_group_todo: { params: GroupTodoParams; data: EmptyData };
complete_group_todo: { params: GroupTodoParams; data: EmptyData };
cancel_group_todo: { params: GroupTodoParams; data: EmptyData };
// — Tier 3: DIY status —
set_diy_online_status: { params: SetDiyOnlineStatusParams; data: EmptyData };
// — AI voice trio —
get_ai_characters: { params: GetAiCharactersParams; data: AiCharacterCategory[] };
get_ai_record: { params: AiVoiceParams; data: string };
send_group_ai_record: { params: AiVoiceParams; data: SendGroupAiRecordResult };
}
export type SnowLumaAction = keyof SnowLumaActionMap | (string & {});
+44
View File
@@ -316,3 +316,47 @@ export interface SetOnlineStatusParams extends JsonObject {
ext_status?: number;
battery_status?: number;
}
// DIY online status — status/extStatus are forced to 10/2000 server-side,
// and these three fields land in the customExt sub-message.
export interface SetDiyOnlineStatusParams extends JsonObject {
face_id: number | string;
wording?: string;
face_type?: number | string;
}
// nc_get_user_status — read the QQ-side online/ext-status word for a uin.
export interface NcGetUserStatusParams extends UserIdParams {}
// set_/complete_/cancel_group_todo all share this shape; the action verb
// lives in the route, not the body.
export interface GroupTodoParams extends GroupIdParams {
message_id: number | string;
}
// AI voice — fetch the in-group AI character list.
export interface GetAiCharactersParams extends GroupIdParams {
chat_type?: number | string;
}
// AI voice — `get_ai_record` and `send_group_ai_record` share params.
// The action's verb (read vs send) is the route, not the body.
export interface AiVoiceParams extends GroupIdParams {
character: string;
text: string;
chat_type?: number | string;
}
// delete_group_folder — napcat's alias for delete_group_file_folder.
// Same body, different action name.
export interface DeleteGroupFolderParams extends GroupIdParams {
folder_id: string;
}
// send_packet — debug endpoint, sends a hex-encoded raw packet.
// `rsp=false` skips waiting for a response.
export interface SendPacketParams extends JsonObject {
cmd: string;
data?: string;
rsp?: boolean;
}
+23
View File
@@ -101,3 +101,26 @@ export interface GroupAtAllRemainInfo {
}
export type EmptyData = null;
// — AI 语音角色:get_ai_characters 返回的分类数组 —
export interface AiCharacter {
character_id: string;
character_name: string;
preview_url: string;
}
export interface AiCharacterCategory {
type: string;
characters: AiCharacter[];
}
// — nc_get_user_status 返回的状态字 —
export interface UserOnlineStatus {
status: number;
ext_status: number;
}
// — send_group_ai_record 返回(合成是异步副作用,message_id 总为 0) —
export interface SendGroupAiRecordResult {
message_id: number;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/websocket",
"version": "1.7.9",
"version": "1.8.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+2 -1
View File
@@ -1,7 +1,7 @@
{
"name": "webui",
"private": true,
"version": "1.7.9",
"version": "1.8.1",
"type": "module",
"scripts": {
"dev": "vite",
@@ -18,6 +18,7 @@
"@radix-ui/react-separator": "^1.1.3",
"@radix-ui/react-slot": "^1.1.3",
"@radix-ui/react-tooltip": "^1.1.9",
"@tanstack/react-router": "^1.169.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.469.0",
+80 -393
View File
@@ -1,421 +1,108 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { RouterProvider } from '@tanstack/react-router';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ThemeProvider, useTheme } from '@/contexts/ThemeContext';
import { ThemeProvider } from '@/contexts/ThemeContext';
import { SessionProvider } from '@/contexts/SessionContext';
import { LoginPage } from '@/components/pages/login-page';
import { MainLayout } from '@/components/layout/main-layout';
import { OverviewPage } from '@/components/pages/overview-page';
import { ConfigPage } from '@/components/pages/config-page';
import { LogsPage } from '@/components/pages/logs-page';
import { SettingsPage } from '@/components/pages/settings-page';
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
const TOKEN_KEY = 'snowluma_token';
function readToken() {
return localStorage.getItem(TOKEN_KEY) || '';
}
import { ChangePasswordPage } from '@/components/pages/change-password-page';
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
import { appRouter } from '@/router';
export default function App() {
return (
<ThemeProvider>
<AppInner />
<AuthBoundary />
</ThemeProvider>
);
}
function AppInner() {
const { pollInterval } = useTheme();
function AuthBoundary() {
const [authChecked, setAuthChecked] = useState(false);
const [authed, setAuthed] = useState(false);
const [mustChange, setMustChange] = useState(false);
const [status, setStatus] = useState('未连接');
const [active, setActive] = useState<Page>('overview');
const [qqList, setQqList] = useState<QQInfo[]>([]);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
const [processActionStatus, setProcessActionStatus] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null);
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
// collapse spam-clicks instead of firing a second concurrent request.
const inflightProcessOps = useRef(new Set<number>());
const [selectedUin, setSelectedUin] = useState<string | null>(null);
const [config, setConfig] = useState<OneBotConfig | null>(null);
const [saveStatus, setSaveStatus] = useState('');
const tokenRef = useRef(readToken());
// ---------- API helpers ----------
const fetchApi = useCallback(async (url: string, options: RequestInit = {}) => {
const headers: Record<string, string> = {
...(options.headers as Record<string, string> | undefined),
};
if (tokenRef.current) headers['Authorization'] = `Bearer ${tokenRef.current}`;
if (options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const res = await fetch(url, { ...options, headers });
if (res.status === 401) {
tokenRef.current = '';
localStorage.removeItem(TOKEN_KEY);
setAuthed(false);
setStatus('未授权');
}
return res;
}, []);
// ---------- Polling ----------
const refreshQqList = useCallback(async () => {
try {
const res = await fetchApi('/api/qq-list');
if (!res.ok) return;
const data = await res.json();
setQqList(data.list || []);
} catch (e) {
console.error('qq-list', e);
}
}, [fetchApi]);
const refreshProcesses = useCallback(async () => {
try {
const res = await fetchApi('/api/processes');
if (!res.ok) return;
const data = await res.json();
setProcessList(data.list || []);
} catch (e) {
console.error('processes', e);
}
}, [fetchApi]);
const refreshSystem = useCallback(async () => {
try {
const res = await fetchApi('/api/system');
if (!res.ok) return;
const data = (await res.json()) as SystemInfo;
setSystemInfo(data);
} catch (e) {
console.error('system', e);
}
}, [fetchApi]);
const checkStatus = useCallback(async () => {
try {
const res = await fetchApi('/api/status');
if (res.ok) {
setAuthed(true);
setStatus('已连接');
return true;
}
setStatus('未连接');
return false;
} catch {
setStatus('未连接');
return false;
}
}, [fetchApi]);
const client = useMemo<ApiClient>(
() =>
createApiClient({
onUnauthorized: () => {
setAuthed(false);
setStatus('未授权');
},
}),
[],
);
useEffect(() => {
(async () => {
if (tokenRef.current) {
const ok = await checkStatus();
if (ok) {
// Existing session may still need to change password.
try {
const r = await fetchApi('/api/auth/state');
if (r.ok) {
const d = await r.json();
setMustChange(!!d.mustChangePassword);
}
} catch { /* ignore */ }
}
const ok = await client.status();
if (ok) {
setAuthed(true);
setStatus('已连接');
setMustChange(await client.mustChangePassword());
}
setAuthChecked(true);
})();
}, [checkStatus, fetchApi]);
}, [client]);
useEffect(() => {
if (!authed || mustChange) return;
if (pollInterval <= 0) return;
let cancelled = false;
const tick = async () => {
if (cancelled) return;
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
};
tick();
const interval = setInterval(tick, pollInterval);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [authed, mustChange, pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
// Auto-select first uin when navigating to config
useEffect(() => {
if (active !== 'config') return;
if (!selectedUin && qqList.length > 0) setSelectedUin(qqList[0].uin);
}, [active, qqList, selectedUin]);
// Load config when selectedUin changes
useEffect(() => {
if (!selectedUin) {
setConfig(null);
return;
}
let cancelled = false;
(async () => {
try {
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
if (!res.ok) return;
const data = await res.json();
const loaded = data?.config ?? data;
if (cancelled) return;
const nets = loaded?.networks ?? {};
const legacyFormat = loaded?.messageFormat === 'string' ? 'string' : 'array';
const legacyReport = !!loaded?.reportSelfMessage;
const normalizeNetwork = <T extends Record<string, unknown>>(item: T) => ({
...item,
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
reportSelfMessage:
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
});
setConfig({
networks: {
httpServers: Array.isArray(nets.httpServers) ? nets.httpServers.map(normalizeNetwork) : [],
httpClients: Array.isArray(nets.httpClients) ? nets.httpClients.map(normalizeNetwork) : [],
wsServers: Array.isArray(nets.wsServers) ? nets.wsServers.map(normalizeNetwork) : [],
wsClients: Array.isArray(nets.wsClients) ? nets.wsClients.map(normalizeNetwork) : [],
},
musicSignUrl: loaded?.musicSignUrl,
});
} catch (e) {
console.error('load-config', e);
}
})();
return () => {
cancelled = true;
};
}, [selectedUin, fetchApi]);
// ---------- Actions ----------
const handleLogin = useCallback(async (password: string) => {
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { success: false, error: data.message || data.error || '令牌错误' };
}
const data = await res.json();
const token = data.token as string;
localStorage.setItem(TOKEN_KEY, token);
tokenRef.current = token;
setMustChange(!!data.mustChangePassword);
const ok = await checkStatus();
return ok ? { success: true } : { success: false, error: '校验失败' };
} catch (e) {
return { success: false, error: (e as Error).message || '网络错误' };
}
}, [checkStatus]);
const handleLogout = useCallback(async () => {
try { await fetchApi('/api/logout', { method: 'POST' }); } catch { /* ignore */ }
localStorage.removeItem(TOKEN_KEY);
tokenRef.current = '';
const handleLogoutComplete = useCallback(() => {
// Reset the URL so the next login lands on the overview page, matching
// the pre-router behaviour.
window.history.replaceState({}, '', '/');
setAuthed(false);
setMustChange(false);
setStatus('未连接');
setQqList([]);
setProcessList([]);
setSystemInfo(null);
setSelectedUin(null);
setConfig(null);
}, [fetchApi]);
const handleLoadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessLoadingPid(pid);
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
try {
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '加载失败');
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`加载失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessLoadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleUnloadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessUnloadingPid(pid);
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
try {
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
// Check if unload actually failed (pipe still exists)
if (data.process?.status === 'connecting' && data.process?.error) {
setUnloadFailedAlert({ pid, error: data.process.error });
setProcessActionStatus(`进程 ${pid} 卸载失败`);
} else {
setProcessActionStatus(`已从进程 ${pid} 卸载`);
}
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessUnloadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleRefreshProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessRefreshingPid(pid);
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
try {
const res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '刷新失败');
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`刷新失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessRefreshingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleSaveConfig = useCallback(async () => {
if (!selectedUin || !config) return;
setSaveStatus('保存中...');
try {
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`, {
method: 'POST',
body: JSON.stringify(config),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '保存失败');
setSaveStatus('保存成功');
} catch (e) {
setSaveStatus(`保存失败:${(e as Error).message}`);
} finally {
setTimeout(() => setSaveStatus(''), 3000);
}
}, [selectedUin, config, fetchApi]);
// ---------- Render ----------
if (!authChecked) {
return (
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
初始化中…
</div>
);
}
const checkStrength = async (password: string) => {
const res = await fetchApi('/api/auth/check-strength', {
method: 'POST',
body: JSON.stringify({ password }),
});
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
return { rules: data.rules ?? [], valid: !!data.valid };
};
const submitPwd = async (oldPassword: string, newPassword: string) => {
const res = await fetchApi('/api/auth/change-password', {
method: 'POST',
body: JSON.stringify({ oldPassword, newPassword }),
});
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
return { success: !!data.success, message: data.message };
};
setMustChange(false);
}, []);
return (
<TooltipProvider delayDuration={150}>
{!authed ? (
<LoginPage onLogin={handleLogin} />
) : mustChange ? (
<ChangePasswordPage
forced
checkStrength={checkStrength}
submit={submitPwd}
onSuccess={() => setMustChange(false)}
/>
) : (
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
{active === 'overview' && (
<OverviewPage
qqList={qqList}
status={status}
processList={processList}
processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid}
processRefreshingPid={processRefreshingPid}
processActionStatus={processActionStatus}
systemInfo={systemInfo}
onRefreshProcesses={refreshProcesses}
onRefreshSystem={refreshSystem}
onLoadProcess={handleLoadProcess}
onUnloadProcess={handleUnloadProcess}
onRefreshProcess={handleRefreshProcess}
/>
)}
{active === 'config' && (
<ConfigPage
qqList={qqList}
selectedUin={selectedUin}
config={config}
saveStatus={saveStatus}
onSelectAccount={setSelectedUin}
onSave={handleSaveConfig}
onConfigChange={setConfig}
/>
)}
{active === 'logs' && <LogsPage fetchApi={fetchApi} />}
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
</MainLayout>
)}
<ConfirmDialog
open={!!unloadFailedAlert}
onOpenChange={(open) => !open && setUnloadFailedAlert(null)}
title="卸载失败"
description={
unloadFailedAlert ? (
<>
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
<p className="mt-2 text-sm text-muted-foreground">
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
</p>
</>
) : null
}
confirmText="知道了"
onConfirm={() => setUnloadFailedAlert(null)}
/>
</TooltipProvider>
<ApiProvider client={client}>
<TooltipProvider delayDuration={150}>
{!authChecked ? (
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
初始化中…
</div>
) : !authed ? (
<LoginGate
onAuthed={(needsChange) => {
setAuthed(true);
setStatus('已连接');
setMustChange(needsChange);
}}
/>
) : mustChange ? (
<ForcedChangePasswordGate onSuccess={() => setMustChange(false)} />
) : (
<SessionProvider value={{ status, onLogoutComplete: handleLogoutComplete }}>
<RouterProvider router={appRouter} />
</SessionProvider>
)}
</TooltipProvider>
</ApiProvider>
);
}
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
const api = useApi();
const handleLogin = useCallback(
async (password: string) => {
const result = await api.login(password);
if (!result.ok) return { success: false, error: result.message };
onAuthed(result.mustChangePassword);
return { success: true };
},
[api, onAuthed],
);
return <LoginPage onLogin={handleLogin} />;
}
function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) {
const api = useApi();
return (
<ChangePasswordPage
forced
checkStrength={(p) => api.checkPasswordStrength(p)}
submit={(o, n) => api.changePassword(o, n)}
onSuccess={onSuccess}
/>
);
}
@@ -1,26 +1,26 @@
import { useEffect, useState, type ReactNode } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { useRouterState } from '@tanstack/react-router';
import { Sheet, SheetContent } from '@/components/ui/sheet';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Sidebar, type Page } from '@/components/layout/sidebar';
import { Sidebar } from '@/components/layout/sidebar';
import { TopBar } from '@/components/layout/top-bar';
import { useMediaQuery } from '@/hooks/use-media-query';
import { cn } from '@/lib/utils';
interface MainLayoutProps {
active: Page;
onNavigate: (page: Page) => void;
status: string;
onLogout: () => void;
children: ReactNode;
}
export function MainLayout({ active, onNavigate, status, onLogout, children }: MainLayoutProps) {
export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
const isMobile = !useMediaQuery('(min-width: 768px)');
const [collapsed, setCollapsed] = useState(() => {
return localStorage.getItem('snowluma_sidebar_collapsed') === '1';
});
const [mobileOpen, setMobileOpen] = useState(false);
const pathname = useRouterState({ select: (s) => s.location.pathname });
useEffect(() => {
localStorage.setItem('snowluma_sidebar_collapsed', collapsed ? '1' : '0');
@@ -36,7 +36,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
transition={{ type: 'spring', stiffness: 280, damping: 32 }}
className="relative h-full shrink-0 border-r overflow-hidden"
>
<Sidebar active={active} onNavigate={onNavigate} collapsed={collapsed} />
<Sidebar collapsed={collapsed} />
</motion.aside>
)}
@@ -44,11 +44,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
{isMobile && (
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
<SheetContent side="left" className="w-64 max-w-[80vw] p-0">
<Sidebar
active={active}
onNavigate={onNavigate}
onItemClick={() => setMobileOpen(false)}
/>
<Sidebar onItemClick={() => setMobileOpen(false)} />
</SheetContent>
</Sheet>
)}
@@ -56,7 +52,6 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
{/* Main column */}
<div className="flex min-w-0 flex-1 flex-col">
<TopBar
active={active}
status={status}
collapsed={collapsed}
onToggleCollapse={() => setCollapsed((v) => !v)}
@@ -70,7 +65,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
<AnimatePresence mode="wait">
<motion.div
key={active}
key={pathname}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
@@ -1,27 +1,34 @@
import { LayoutDashboard, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion } from 'motion/react';
import { Link, useRouterState } from '@tanstack/react-router';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
import type { AppPath } from '@/router';
export type Page = 'overview' | 'config' | 'logs' | 'settings';
export interface NavItem {
to: AppPath;
label: string;
icon: typeof LayoutDashboard;
description: string;
}
export const NAV_ITEMS: { page: Page; label: string; icon: typeof LayoutDashboard; description: string }[] = [
{ page: 'overview', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
{ page: 'config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
{ page: 'logs', label: '日志', icon: Terminal, description: '实时事件流' },
{ page: 'settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
export const NAV_ITEMS: NavItem[] = [
{ to: '/', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
{ to: '/config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
{ to: '/logs', label: '日志', icon: Terminal, description: '实时事件流' },
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
];
interface SidebarProps {
active: Page;
onNavigate: (page: Page) => void;
collapsed?: boolean;
onItemClick?: () => void;
}
export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }: SidebarProps) {
export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
return (
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
{/* Brand */}
@@ -43,23 +50,21 @@ export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }:
{/* Nav */}
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{NAV_ITEMS.map(({ page, label, icon: Icon, description }) => {
const isActive = active === page;
{NAV_ITEMS.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
<button
key={page}
type="button"
<Link
key={to}
to={to}
title={collapsed ? label : undefined}
onClick={() => {
onNavigate(page);
onItemClick?.();
}}
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
)}
>
{isActive && (
@@ -76,7 +81,7 @@ export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }:
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
</button>
</Link>
);
})}
</nav>
@@ -1,15 +1,14 @@
import { useState } from 'react';
import { LogOut, Menu, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { useRouterState } from '@tanstack/react-router';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ThemeToggle } from '@/components/theme-toggle';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import { NAV_ITEMS } from '@/components/layout/sidebar';
interface TopBarProps {
active: Page;
status: string;
collapsed: boolean;
onToggleCollapse: () => void;
@@ -19,7 +18,6 @@ interface TopBarProps {
}
export function TopBar({
active,
status,
collapsed,
onToggleCollapse,
@@ -28,7 +26,8 @@ export function TopBar({
isMobile,
}: TopBarProps) {
const [confirmLogout, setConfirmLogout] = useState(false);
const meta = NAV_ITEMS.find((n) => n.page === active);
const pathname = useRouterState({ select: (s) => s.location.pathname });
const meta = NAV_ITEMS.find((n) => n.to === pathname);
const PageIcon = meta?.icon;
const online = status === '已连接';
@@ -56,7 +55,7 @@ export function TopBar({
{/* Page title */}
<AnimatePresence mode="wait">
<motion.div
key={active}
key={pathname}
initial={{ opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 8 }}
@@ -16,19 +16,10 @@ import type {
NetworkKind,
OneBotConfig,
OneBotNetworks,
QQInfo,
WsRole,
} from '@/types';
interface ConfigPageProps {
qqList: QQInfo[];
selectedUin: string | null;
config: OneBotConfig | null;
saveStatus: string;
onSelectAccount: (uin: string) => void;
onSave: () => Promise<void> | void;
onConfigChange: (config: OneBotConfig) => void;
}
import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config';
import { useAppState } from '@/contexts/AppStateContext';
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
@@ -98,18 +89,28 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
);
}
export function ConfigPage({
qqList,
selectedUin,
config,
saveStatus,
onSelectAccount,
onSave,
onConfigChange,
}: ConfigPageProps) {
export function ConfigPage() {
const { qqList, selectedUin, setSelectedUin } = useAppState();
const {
config,
setConfig,
dirty,
requestSwitchUin,
pendingSwitchUin,
confirmSwitch,
cancelSwitch,
save,
saveStatus,
} = useOneBotInstanceConfig(qqList, {
selectedUin,
onSelectedUinChange: setSelectedUin,
});
const [confirmSave, setConfirmSave] = useState(false);
const update = (next: OneBotConfig) => onConfigChange(next);
const update = (next: OneBotConfig) => setConfig(next);
const pendingSwitchAccount = pendingSwitchUin
? qqList.find((q) => q.uin === pendingSwitchUin) ?? null
: null;
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
@@ -132,7 +133,7 @@ export function ConfigPage({
type="button"
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
onClick={() => onSelectAccount(q.uin)}
onClick={() => requestSwitchUin(q.uin)}
className={cn(
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
@@ -193,7 +194,12 @@ export function ConfigPage({
{saveStatus}
</span>
)}
<Button onClick={() => setConfirmSave(true)} size="sm">
{dirty && !saveStatus && (
<span className="rounded-full border border-warning/30 bg-warning/10 px-2.5 py-1 text-[11px] font-medium text-warning">
未保存
</span>
)}
<Button onClick={() => setConfirmSave(true)} size="sm" disabled={!dirty}>
<Save className="size-3.5" /> 保存设定
</Button>
</div>
@@ -421,7 +427,27 @@ export function ConfigPage({
title="保存配置变更?"
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
confirmText="保存"
onConfirm={onSave}
onConfirm={save}
/>
<ConfirmDialog
open={pendingSwitchUin != null}
onOpenChange={(open) => !open && cancelSwitch()}
title="放弃未保存的修改?"
description={
<>
<p>
当前会话 <code className="font-mono">{selectedUin}</code> 还有未保存的修改。
</p>
<p className="mt-2">
切换到 <code className="font-mono">{pendingSwitchAccount?.uin ?? pendingSwitchUin}</code>
{pendingSwitchAccount?.nickname ? `(${pendingSwitchAccount.nickname})` : ''} 会丢弃这些修改。
</p>
</>
}
confirmText="放弃并切换"
destructive
onConfirm={confirmSwitch}
/>
</div>
);
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { motion } from 'motion/react';
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -9,10 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry } from '@/types';
interface LogsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
}
import { useApi } from '@/lib/api';
const levelClass: Record<LogEntry['level'], string> = {
debug: 'text-muted-foreground',
@@ -24,7 +21,8 @@ const levelClass: Record<LogEntry['level'], string> = {
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
export function LogsPage({ fetchApi }: LogsPageProps) {
export function LogsPage() {
const api = useApi();
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
@@ -34,36 +32,30 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
const endRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
async function loadLogs() {
const res = await fetchApi('/api/logs?limit=500');
if (!res.ok) return;
const data = await res.json();
setLogs(data.list || []);
}
const loadLogs = useCallback(async () => {
try {
setLogs(await api.logs.list(500));
} catch (e) {
console.error('logs', e);
}
}, [api]);
useEffect(() => {
loadLogs().catch(console.error);
}, []);
void loadLogs();
}, [loadLogs]);
useEffect(() => {
if (!token) return;
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
const source = new EventSource(url);
source.onopen = () => setStreamStatus('实时');
source.onerror = () => setStreamStatus('重连中');
source.onmessage = (event) => {
try {
const entry = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in entry) return;
return api.logs.stream({
onLine: (entry) => {
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
} catch {
// ignore
}
};
return () => source.close();
}, [token]);
},
onStatus: (s) => {
if (s === 'open') setStreamStatus('实时');
else if (s === 'reconnecting') setStreamStatus('重连中');
else setStreamStatus('已断开');
},
});
}, [api]);
useEffect(() => {
if (paused) return;
@@ -115,7 +107,7 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
{paused ? <Play className="size-3.5" /> : <Pause className="size-3.5" />}
{paused ? '继续' : '暂停'}
</Button>
<Button variant="outline" size="sm" onClick={() => loadLogs().catch(console.error)}>
<Button variant="outline" size="sm" onClick={() => void loadLogs()}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
<Button
@@ -22,23 +22,9 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn, formatBytes, formatUptime } from '@/lib/utils';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
interface OverviewPageProps {
qqList: QQInfo[];
status: string;
processList: HookProcessInfo[];
processLoadingPid: number | null;
processUnloadingPid: number | null;
processRefreshingPid: number | null;
processActionStatus: string;
systemInfo: SystemInfo | null;
onRefreshProcesses: () => void;
onRefreshSystem: () => void;
onLoadProcess: (pid: number) => Promise<void> | void;
onUnloadProcess: (pid: number) => Promise<void> | void;
onRefreshProcess: (pid: number) => Promise<void> | void;
}
import type { HookProcessInfo } from '@/types';
import { useAppState } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载',
@@ -96,21 +82,11 @@ function StatTile({
);
}
export function OverviewPage({
qqList,
status,
processList,
processLoadingPid,
processUnloadingPid,
processRefreshingPid,
processActionStatus,
systemInfo,
onRefreshProcesses,
onRefreshSystem,
onLoadProcess,
onUnloadProcess,
onRefreshProcess,
}: OverviewPageProps) {
export function OverviewPage() {
const { qqList, processList, systemInfo, processOps, refreshProcesses, refreshSystem } =
useAppState();
const { status } = useSession();
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
const [confirm, setConfirm] = useState<
| { kind: 'load' | 'unload'; pid: number; name: string }
| null
@@ -167,7 +143,7 @@ export function OverviewPage({
: '正在采集主机信息…'}
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={onRefreshSystem}>
<Button variant="outline" size="sm" onClick={refreshSystem}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
@@ -270,7 +246,7 @@ export function OverviewPage({
加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={onRefreshProcesses}>
<Button variant="outline" size="sm" onClick={refreshProcesses}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
@@ -292,10 +268,11 @@ export function OverviewPage({
) : (
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
{processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid;
const refreshing = processRefreshingPid === proc.pid;
const busy = loading || unloading || refreshing;
const op = statusOf(proc.pid);
const loading = op === 'load' || proc.status === 'loading';
const unloading = op === 'unload';
const refreshing = op === 'refresh';
const busy = op != null || proc.status === 'loading';
const isOnline = proc.status === 'online';
const canUnload = proc.injected;
// Refresh is meaningful whenever a hook may exist (so the user
@@ -355,7 +332,7 @@ export function OverviewPage({
disabled={busy}
aria-label={`刷新进程 ${proc.pid} 管道状态`}
title="刷新管道状态 / 重连"
onClick={() => onRefreshProcess(proc.pid)}
onClick={() => refresh(proc.pid)}
className="size-8 text-muted-foreground hover:text-foreground"
>
{refreshing ? (
@@ -449,8 +426,8 @@ export function OverviewPage({
destructive={confirm?.kind === 'unload'}
onConfirm={async () => {
if (!confirm) return;
if (confirm.kind === 'unload') await onUnloadProcess(confirm.pid);
else await onLoadProcess(confirm.pid);
if (confirm.kind === 'unload') await unload(confirm.pid);
else await load(confirm.pid);
}}
/>
</div>
@@ -14,18 +14,11 @@ import {
type Density,
type ThemeMode,
} from '@/contexts/ThemeContext';
import {
ChangePasswordPage,
type PasswordRule,
} from '@/components/pages/change-password-page';
import { ChangePasswordPage } from '@/components/pages/change-password-page';
import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext';
import { cn } from '@/lib/utils';
interface SettingsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
/** Called after successful logout (e.g. all-sessions invalidated). */
onLogout: () => void;
}
const MODE_OPTIONS: { value: ThemeMode; label: string; icon: typeof Sun }[] = [
{ value: 'light', label: '浅色', icon: Sun },
{ value: 'dark', label: '深色', icon: Moon },
@@ -37,7 +30,9 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
];
export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
export function SettingsPage() {
const api = useApi();
const { onLogout } = useAppState();
const {
mode, setMode,
accent, setAccent,
@@ -49,30 +44,12 @@ export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
const [showChangePwd, setShowChangePwd] = useState(false);
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
const checkStrength = async (password: string) => {
const res = await fetchApi('/api/auth/check-strength', {
method: 'POST',
body: JSON.stringify({ password }),
});
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
return { rules: data.rules ?? [], valid: !!data.valid };
};
const submitPwd = async (oldPassword: string, newPassword: string) => {
const res = await fetchApi('/api/auth/change-password', {
method: 'POST',
body: JSON.stringify({ oldPassword, newPassword }),
});
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
return { success: !!data.success, message: data.message };
};
if (showChangePwd) {
return (
<ChangePasswordPage
forced={false}
checkStrength={checkStrength}
submit={submitPwd}
checkStrength={(p) => api.checkPasswordStrength(p)}
submit={(o, n) => api.changePassword(o, n)}
onSuccess={() => {
setShowChangePwd(false);
setPwdSavedAt(Date.now());
@@ -0,0 +1,40 @@
import { createContext, useContext, type ReactNode } from 'react';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
/**
* Live mutable state owned by AppLayout and shared with the child route
* components rendered inside its `<Outlet />`. Pages used to receive these
* via prop drilling — now they pull from context so adding a new page does
* not touch AppLayout.
*/
export interface AppStateValue {
qqList: QQInfo[];
processList: HookProcessInfo[];
systemInfo: SystemInfo | null;
selectedUin: string | null;
setSelectedUin: (uin: string | null) => void;
processOps: HookProcessOps;
refreshProcesses: () => void;
refreshSystem: () => void;
/** Triggered from the topbar logout button. */
onLogout: () => void;
}
const AppStateContext = createContext<AppStateValue | null>(null);
export function AppStateProvider({
value,
children,
}: {
value: AppStateValue;
children: ReactNode;
}) {
return <AppStateContext.Provider value={value}>{children}</AppStateContext.Provider>;
}
export function useAppState(): AppStateValue {
const v = useContext(AppStateContext);
if (!v) throw new Error('useAppState must be used inside <AppStateProvider>');
return v;
}
@@ -0,0 +1,30 @@
import { createContext, useContext, type ReactNode } from 'react';
/**
* Auth-level state surfaced into the router subtree. `AuthBoundary` mints
* this and `AppLayout` consumes it — used to drive the status badge and to
* complete logout after page-local state has been cleared.
*/
export interface SessionValue {
status: string;
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */
onLogoutComplete: () => void;
}
const SessionContext = createContext<SessionValue | null>(null);
export function SessionProvider({
value,
children,
}: {
value: SessionValue;
children: ReactNode;
}) {
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
}
export function useSession(): SessionValue {
const v = useContext(SessionContext);
if (!v) throw new Error('useSession must be used inside <SessionProvider>');
return v;
}
@@ -0,0 +1,156 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useApi, type ProcessActionResult } from '@/lib/api';
export type HookProcessOpKind = 'load' | 'unload' | 'refresh';
export interface HookProcessOps {
/** Returns the in-flight op kind for a pid, or null if idle. */
statusOf(pid: number): HookProcessOpKind | null;
/** Latest user-facing status; auto-clears a few seconds after the last update. */
banner: string;
load(pid: number): Promise<void>;
unload(pid: number): Promise<void>;
refresh(pid: number): Promise<void>;
}
export interface UnloadFailedAlert {
pid: number;
error: string;
}
export interface UseHookProcessOpsResult {
ops: HookProcessOps;
unloadFailedAlert: UnloadFailedAlert | null;
dismissUnloadFailedAlert: () => void;
}
interface KindMessages {
start(pid: number): string;
ok(pid: number): string;
fail(message: string): string;
}
const KIND_MESSAGES: Record<HookProcessOpKind, KindMessages> = {
load: {
start: (pid) => `正在向进程 ${pid} 加载 SnowLuma…`,
ok: (pid) => `已向进程 ${pid} 注入 SnowLuma,等待管道连接…`,
fail: (m) => `加载失败:${m}`,
},
unload: {
start: (pid) => `正在从进程 ${pid} 卸载…`,
ok: (pid) => `已从进程 ${pid} 卸载`,
fail: (m) => `卸载失败:${m}`,
},
refresh: {
start: (pid) => `正在刷新进程 ${pid} 的管道状态…`,
ok: (pid) => `已刷新进程 ${pid} 的管道状态`,
fail: (m) => `刷新失败:${m}`,
},
};
const BANNER_CLEAR_MS = 4000;
/**
* Drives load/unload/refresh actions on Hook-target processes. Owns the
* per-pid inflight dedup, the per-kind status indicator, the banner message
* lifecycle, and the "unload silently failed" alert that surfaces when the
* backend reports the named pipe is still alive after an unload attempt.
*/
export function useHookProcessOps(
opts: { onAfterOp?: () => Promise<void> | void } = {},
): UseHookProcessOpsResult {
const api = useApi();
const [byPid, setByPid] = useState<Map<number, HookProcessOpKind>>(() => new Map());
const [banner, setBanner] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<UnloadFailedAlert | null>(null);
// Synchronous inflight guard — protects against rapid double-clicks that
// would race the byPid setter (state updates are batched, refs are not).
const inflightRef = useRef<Set<number>>(new Set());
const bannerTimerRef = useRef<number | null>(null);
const onAfterOpRef = useRef(opts.onAfterOp);
onAfterOpRef.current = opts.onAfterOp;
useEffect(
() => () => {
if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current);
},
[],
);
const scheduleBannerClear = useCallback(() => {
if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current);
bannerTimerRef.current = window.setTimeout(() => {
setBanner('');
bannerTimerRef.current = null;
}, BANNER_CLEAR_MS);
}, []);
const setKind = useCallback((pid: number, kind: HookProcessOpKind | null) => {
setByPid((prev) => {
const next = new Map(prev);
if (kind == null) next.delete(pid);
else next.set(pid, kind);
return next;
});
}, []);
const run = useCallback(
async (
pid: number,
kind: HookProcessOpKind,
action: () => Promise<ProcessActionResult>,
) => {
if (inflightRef.current.has(pid)) return;
inflightRef.current.add(pid);
setKind(pid, kind);
const messages = KIND_MESSAGES[kind];
setBanner(messages.start(pid));
try {
const result = await action();
if (kind === 'unload' && result.process?.status === 'connecting' && result.process.error) {
setUnloadFailedAlert({ pid, error: result.process.error });
setBanner(`进程 ${pid} 卸载失败`);
} else {
setBanner(messages.ok(pid));
}
await onAfterOpRef.current?.();
} catch (e) {
const msg = e instanceof Error ? e.message : '未知错误';
setBanner(messages.fail(msg));
} finally {
inflightRef.current.delete(pid);
setKind(pid, null);
scheduleBannerClear();
}
},
[setKind, scheduleBannerClear],
);
const load = useCallback(
(pid: number) => run(pid, 'load', () => api.processes.load(pid)),
[api, run],
);
const unload = useCallback(
(pid: number) => run(pid, 'unload', () => api.processes.unload(pid)),
[api, run],
);
const refresh = useCallback(
(pid: number) => run(pid, 'refresh', () => api.processes.refresh(pid)),
[api, run],
);
const statusOf = useCallback(
(pid: number): HookProcessOpKind | null => byPid.get(pid) ?? null,
[byPid],
);
const dismissUnloadFailedAlert = useCallback(() => setUnloadFailedAlert(null), []);
const ops = useMemo<HookProcessOps>(
() => ({ statusOf, banner, load, unload, refresh }),
[statusOf, banner, load, unload, refresh],
);
return { ops, unloadFailedAlert, dismissUnloadFailedAlert };
}
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more