Compare commits
181 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3870052fb4 | ||
|
|
b019b00e82 | ||
|
|
50aa9b3595 | ||
|
|
af8d5ab06b | ||
|
|
adf0744f75 | ||
|
|
652bafd75a | ||
|
|
5440cbc37e | ||
|
|
a434da9e85 | ||
|
|
2c565fbd8d | ||
|
|
0d30ee628e | ||
|
|
0f7aa5a600 | ||
|
|
1b07005d91 | ||
|
|
aaed36aa19 | ||
|
|
c3a8a9b6b6 | ||
|
|
868f4a5798 | ||
|
|
93850ec11c | ||
|
|
40c51bcd02 | ||
|
|
bed48bbe46 | ||
|
|
34cc6be8df | ||
|
|
c55042aff4 | ||
|
|
3726913c1f | ||
|
|
5924346823 | ||
|
|
456086599c | ||
|
|
80ee12ecc2 | ||
|
|
acc5084647 | ||
|
|
afbec8ed44 | ||
|
|
a49e507e15 | ||
|
|
a52a9724cb | ||
|
|
245405d294 | ||
|
|
f53df5e313 | ||
|
|
c16064d7e3 | ||
|
|
98296fcec5 | ||
|
|
d8c72c2ebc | ||
|
|
8631453940 | ||
|
|
a4909ec9e5 | ||
|
|
4755a91cb3 | ||
|
|
c8f259ef4a | ||
|
|
cd9403f27a | ||
|
|
5724f490b4 | ||
|
|
99772851a7 | ||
|
|
9b4ff9c5e9 | ||
|
|
521808a6eb | ||
|
|
8d22868777 | ||
|
|
014b87c7ce | ||
|
|
80afa31f5c | ||
|
|
8356121518 | ||
|
|
58e8081420 | ||
|
|
f78431242c | ||
|
|
a38f7ea26e | ||
|
|
ff2b902cbd | ||
|
|
0238bcb280 | ||
|
|
c3675aef7c | ||
|
|
65636953e7 | ||
|
|
7e3e833f84 | ||
|
|
a24272b25a | ||
|
|
2638d13d11 | ||
|
|
ce78a3bbdf | ||
|
|
737b121dfe | ||
|
|
e088167476 | ||
|
|
ee0f159b7e | ||
|
|
607a7b319b | ||
|
|
a13e09131f | ||
|
|
66f8a5eb2f | ||
|
|
d68535e3d1 | ||
|
|
61f40703ca | ||
|
|
5f1d4400dc | ||
|
|
4e51b4bd7d | ||
|
|
4e34f8aeb0 | ||
|
|
26777d0010 | ||
|
|
b69d8ac83c | ||
|
|
998eba2ba8 | ||
|
|
3f2b474120 | ||
|
|
a70f194218 | ||
|
|
0b6541ca36 | ||
|
|
f3f5d27c65 | ||
|
|
070e39090a | ||
|
|
450b551701 | ||
|
|
d983635c8f | ||
|
|
8bf2ff3f36 | ||
|
|
4c4ce60bf2 | ||
|
|
cb698d2435 | ||
|
|
a011b8f033 | ||
|
|
72320121c3 | ||
|
|
9a30df9907 | ||
|
|
f7a03ca05a | ||
|
|
46b302f738 | ||
|
|
e1c9ede9de | ||
|
|
e7afef5d63 | ||
|
|
0479924482 | ||
|
|
e5e85d8d4b | ||
|
|
f4c6838e65 | ||
|
|
22add4ad1c | ||
|
|
e5ac2a61b1 | ||
|
|
d953b9824c | ||
|
|
62c5590fe1 | ||
|
|
2ec72d59f9 | ||
|
|
73f1cd3c80 | ||
|
|
c92daa56df | ||
|
|
dad501ebc0 | ||
|
|
0b91e4db8d | ||
|
|
6bf53890dc | ||
|
|
3e5dca1bd4 | ||
|
|
9a678442e9 | ||
|
|
6c7e56d5a1 | ||
|
|
994633eafa | ||
|
|
fe00774191 | ||
|
|
0464d6439f | ||
|
|
db412ad498 | ||
|
|
b56868878c | ||
|
|
c49ae1c8d9 | ||
|
|
36c3ed031b | ||
|
|
aea2676c31 | ||
|
|
f21740a5d3 | ||
|
|
5ea1c3a961 | ||
|
|
02bab710b8 | ||
|
|
bf4c130641 | ||
|
|
ca0a888003 | ||
|
|
3cd3155d1a | ||
|
|
4b217eb4b8 | ||
|
|
2de1ff4f0d | ||
|
|
5d83aedd83 | ||
|
|
d1aade6f87 | ||
|
|
cc574632f1 | ||
|
|
c83c333e73 | ||
|
|
6de2e071be | ||
|
|
312df29b5f | ||
|
|
1db287d8cc | ||
|
|
f65fe959bb | ||
|
|
cec38b4c1b | ||
|
|
0b8dc1f7af | ||
|
|
8f839f4f30 | ||
|
|
04a905460b | ||
|
|
3c65df668c | ||
|
|
87ac6ffedb | ||
|
|
1daf6f6218 | ||
|
|
898898a507 | ||
|
|
604dbc3f64 | ||
|
|
ff5fc651d0 | ||
|
|
c758eb6569 | ||
|
|
10154cfbff | ||
|
|
e637647877 | ||
|
|
a50e038272 | ||
|
|
ecb8064ca9 | ||
|
|
70715763bd | ||
|
|
d821336943 | ||
|
|
76b87f6b27 | ||
|
|
5802812392 | ||
|
|
6f3646e956 | ||
|
|
c543ce9227 | ||
|
|
7526622917 | ||
|
|
ccc31a760c | ||
|
|
9f32dbd60c | ||
|
|
b7d8952163 | ||
|
|
d323318a7e | ||
|
|
31079673c6 | ||
|
|
3d739c255a | ||
|
|
194165f49d | ||
|
|
02d1848d39 | ||
|
|
0d40a03f28 | ||
|
|
64530cc287 | ||
|
|
df691c4e8f | ||
|
|
9f9db8d16f | ||
|
|
4d7302a13f | ||
|
|
f316073431 | ||
|
|
692a1b7665 | ||
|
|
941e60dea5 | ||
|
|
b99f5c0bf1 | ||
|
|
562fd4f7f9 | ||
|
|
ba899782fe | ||
|
|
6a7c9a5de1 | ||
|
|
7a2de230bf | ||
|
|
a460433175 | ||
|
|
24056c3de0 | ||
|
|
a07521d9de | ||
|
|
c62f51750a | ||
|
|
b441647df4 | ||
|
|
e2ee528939 | ||
|
|
c58f4d4085 | ||
|
|
16bdf1be1e | ||
|
|
0401ac4afb | ||
|
|
b176e929b9 |
15
.editorconfig
Normal file
15
.editorconfig
Normal file
@@ -0,0 +1,15 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = crlf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.{json,yml,yaml,md}]
|
||||
indent_size = 2
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
119
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
119
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
name: Bug 反馈
|
||||
description: 报告一个可复现的问题
|
||||
title: "[Bug] "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。
|
||||
在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。
|
||||
|
||||
- type: checkboxes
|
||||
id: preflight
|
||||
attributes:
|
||||
label: 提交前检查
|
||||
options:
|
||||
- label: 我已搜索过 Issues,确认没有重复的反馈
|
||||
required: true
|
||||
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: snowluma-version
|
||||
attributes:
|
||||
label: SnowLuma 版本
|
||||
description: 启动日志首行或 `package.json` 里的版本号
|
||||
placeholder: "例如 1.8.5"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: adapter
|
||||
attributes:
|
||||
label: 出问题的适配器
|
||||
description: 可多选
|
||||
multiple: true
|
||||
options:
|
||||
- WebSocket Server
|
||||
- WebSocket Client
|
||||
- HTTP Server
|
||||
- HTTP Post
|
||||
- WebUI
|
||||
- Bridge / Core(协议层)
|
||||
- 其他 / 不确定
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: 操作系统
|
||||
placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: node-version
|
||||
attributes:
|
||||
label: Node.js 版本
|
||||
description: '`node -v` 的输出。如果使用预构建包可填"预构建包"'
|
||||
placeholder: "例如 v20.11.0 或 预构建包"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: qq-version
|
||||
attributes:
|
||||
label: QQ 客户端版本
|
||||
description: QQ NT 客户端的版本号
|
||||
placeholder: "例如 9.9.15-29722"
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: 简要说明发生了什么
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: reproduce
|
||||
attributes:
|
||||
label: 复现步骤
|
||||
description: 详细列出如何触发这个问题
|
||||
placeholder: |
|
||||
1. 启动 SnowLuma 并登录账号 ...
|
||||
2. 通过 HTTP Server 调用 `send_group_msg` ...
|
||||
3. 观察到 ...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 期望行为
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: 实际行为
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志 / 错误堆栈
|
||||
description: |
|
||||
粘贴控制台日志、SSE 实时日志或错误堆栈。
|
||||
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
render: shell
|
||||
|
||||
- type: textarea
|
||||
id: extra
|
||||
attributes:
|
||||
label: 补充信息
|
||||
description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等
|
||||
11
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
11
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: QQ 群
|
||||
url: https://qm.qq.com/q/g3UMLpWALe
|
||||
about: 日常使用问题、快速交流可以先来 QQ 群
|
||||
- name: Telegram
|
||||
url: https://t.me/napcatqq
|
||||
about: 海外用户交流频道
|
||||
- name: Releases
|
||||
url: https://github.com/SnowLuma/SnowLuma/releases
|
||||
about: 在反馈 Bug 前,请先确认已使用最新发布版本
|
||||
76
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
76
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
name: 功能请求
|
||||
description: 提议一个新功能或对现有功能的增强
|
||||
title: "[Feature] "
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。
|
||||
|
||||
- type: checkboxes
|
||||
id: preflight
|
||||
attributes:
|
||||
label: 提交前检查
|
||||
options:
|
||||
- label: 我已搜索过 Issues,确认没有重复的提案
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: scope
|
||||
attributes:
|
||||
label: 涉及范围
|
||||
multiple: true
|
||||
options:
|
||||
- OneBot 协议 / 消息段
|
||||
- WebSocket Server / Client 适配器
|
||||
- HTTP Server / Post 适配器
|
||||
- WebUI 管理面板
|
||||
- SDK (`@snowluma/sdk`)
|
||||
- UI 组件 (`@snowluma/ui`)
|
||||
- Bridge / Core(协议层)
|
||||
- 构建 / 发布流程
|
||||
- 文档
|
||||
- 其他
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: 需求场景 / 当前痛点
|
||||
description: 这个功能要解决什么问题?目前是如何变通处理的?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: 期望方案
|
||||
description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 已考虑的替代方案
|
||||
description: 还想过哪些其他实现路径,为什么放弃
|
||||
|
||||
- type: textarea
|
||||
id: references
|
||||
attributes:
|
||||
label: 参考链接
|
||||
description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR
|
||||
placeholder: |
|
||||
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
|
||||
- 相关讨论: #xxx
|
||||
|
||||
- type: checkboxes
|
||||
id: willingness
|
||||
attributes:
|
||||
label: 您是否愿意提交 PR 来实现这个功能?
|
||||
options:
|
||||
- label: 愿意,且需要维护者讨论方案后再动手
|
||||
- label: 愿意,已有大致实现思路
|
||||
- label: 暂时只提建议
|
||||
4
.github/workflows/dev-build.yml
vendored
4
.github/workflows/dev-build.yml
vendored
@@ -110,10 +110,6 @@ jobs:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -11,6 +11,7 @@ dist/
|
||||
|
||||
/config/
|
||||
/data/
|
||||
logs/
|
||||
|
||||
# macOS metadata
|
||||
.DS_Store
|
||||
|
||||
@@ -68,6 +68,7 @@ WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial cr
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
|
||||
|
||||
494
RoadMap.md
494
RoadMap.md
@@ -1,3 +1,491 @@
|
||||
# V2.0.0 前计划
|
||||
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
|
||||
# SnowLuma v3 — 目标架构
|
||||
|
||||
> v2 已完成:UID/UIN Service(SQLite 持久化)、tsx+map Debug、包拆分、proto-defs 剥离、消息 hot-path 优化(17.5μs → 4.7μs)、NapCat 风格 Api 层、Bridge/Account 分层(v2 发布在 `@snowluma/bridge`,v3 重命名为 `@snowluma/channel`)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 数据流总览(一图概览所有权)
|
||||
|
||||
```
|
||||
┌─ @snowluma/channel-hook ─────────┐ ┌─ @snowluma/channel-socket ──────┐
|
||||
│ HookManager + HookChannel │ │ SocketChannel (future) │
|
||||
│ — 仅 send/recv + pid/hook state — │ │ — 仅 send/recv + socket state — │
|
||||
└────────────┬─────────────────────┘ └─────────────┬───────────────────┘
|
||||
│ Channel 实例 │
|
||||
└───────────┬──────────────────────────┘
|
||||
│ 通过 ChannelAdapter 注册
|
||||
▼
|
||||
┌─ @snowluma/core ──── Hub(主入口 / 持有一切)──────────────┐
|
||||
│ │
|
||||
│ 内部:Map<uin, Core> │
|
||||
│ │
|
||||
│ channel available ──► ctx = capability(channel) │
|
||||
│ ──► core = new Core(ctx) │
|
||||
│ ──► emit 'core-online' { uin, apis, events, ... } │
|
||||
│ │
|
||||
│ channel gone ──► core.dispose() + emit 'core-offline' { uin } │
|
||||
└─────────────────────────────────────┬─────────────────────────────────┘
|
||||
│ 顶层 lifecycle 事件(仅 2 个)
|
||||
▼
|
||||
┌─ @snowluma/onebot ──────────────────────────────────────────────────────┐
|
||||
│ hub.events.on('core-online', ctx => { │
|
||||
│ this.byUin.set(ctx.uin, ctx); │
|
||||
│ ctx.events.on('group_message', e => …); // 每账号 bus │
|
||||
│ }); │
|
||||
│ // 处理 OneBot action: │
|
||||
│ this.byUin.get(uin)?.apis.message.sendGroup(...) │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**核心约定**:
|
||||
- `Channel` / adapter 包 **只**做 send/recv + 自己的内部状态(pid set / hook session / socket fd)。完全无业务。
|
||||
- `Hub` 是**主入口**,独占持有 Channels + Cores。`Core` 实例由它构造,外部拿不到 Core 类本身。
|
||||
- `Core` 通过 **ctx**(capability,一个 POJO)拿到 send/recv,从不直接持有 Channel。
|
||||
- 外部消费者(OneBot / WebUI)只拿 `CoreCtx`(Core 的对外投影:`{ uin, apis, events, identity }`),不知道 Core 类的存在。
|
||||
- 每个账号一个 `events`(在 Core 上),不做全局 bus;Hub 只 emit 两个顶层生命周期事件。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标包结构
|
||||
|
||||
```
|
||||
SnowLuma/
|
||||
├── packages/
|
||||
│ │
|
||||
│ │ ── Infrastructure(无业务) ──
|
||||
│ ├── common/ logger / packet-sender / protocol-types / async-context
|
||||
│ ├── proto-defs/ protobuf TS 接口定义
|
||||
│ ├── proton/ protobuf codec 编译时生成器
|
||||
│ ├── runtime/ native .node 产物清单
|
||||
│ ├── ui/ Tailwind v4 + shadcn 组件(前端)
|
||||
│ │
|
||||
│ │ ── Protocol(解析层,纯函数) ──
|
||||
│ ├── protocol/ events / identity-service / msg-push / oidb / highway /
|
||||
│ │ element-builder / packet-pipeline / event-bus
|
||||
│ │
|
||||
│ │ ── Channel & adapters(transport 端口与实现) ──
|
||||
│ ├── channel/ ⭐ Channel 接口 + 抽象类 + ChannelAdapter 端口
|
||||
│ │ —— 只定义接口和最小抽象,**不**含 Hub
|
||||
│ ├── channel-hook/ ⭐ HookManager + HookChannel + HookAdapter
|
||||
│ │ —— 现 @snowluma/channel 大部分内容搬来
|
||||
│ ├── channel-socket/ ⭐ 未来:SocketChannel + SocketAdapter
|
||||
│ │
|
||||
│ │ ── Core(主入口 + 业务封装) ──
|
||||
│ ├── core/ ⭐ Core + Hub + CoreCtx + ApiHub + 协议封装
|
||||
│ │ —— Hub 在这里(避免 channel↔core 循环)
|
||||
│ │
|
||||
│ │ ── Inbound(外部协议消费 CoreCtx) ──
|
||||
│ ├── onebot/ OneBot v11 (HTTP + WS)
|
||||
│ ├── websocket/ 底层 WS server(被 onebot / webui-backend 共用)
|
||||
│ ├── webui-backend/ ⭐ Hono server + REST/WS(拆自 webui)
|
||||
│ ├── webui-frontend/ ⭐ Vite SPA(拆自 webui)
|
||||
│ └── sdk/ TS SDK
|
||||
│
|
||||
├── package.json
|
||||
└── pnpm-workspace.yaml
|
||||
```
|
||||
|
||||
⭐ 标记的是 v3 改动。
|
||||
|
||||
### 1.1 关键变动
|
||||
|
||||
| 当前 | 目标 | 备注 |
|
||||
|---|---|---|
|
||||
| `@snowluma/bridge`(hook + transport + adapter + manager) | `@snowluma/channel`(仅接口 + abstract Channel)+ `@snowluma/channel-hook`(hook 实现) | 包名 v2 叫 bridge,v3 重命名;hook 全套迁出独立包 |
|
||||
| `@snowluma/core`(含 Account + AccountManager) | `core`:Core + Hub | Account → Core;AccountManager 折进 Hub |
|
||||
| —— | `channel-socket` | 新建 stub |
|
||||
| `@snowluma/webui` | `webui-backend` + `webui-frontend` | 前后端拆分 |
|
||||
|
||||
### 1.2 依赖 DAG(无环)
|
||||
|
||||
```
|
||||
common ◄── proton, proto-defs, protocol, runtime, ui, channel
|
||||
proto-defs ◄── protocol
|
||||
proton ◄── protocol
|
||||
protocol ◄── core
|
||||
channel ◄── channel-hook, channel-socket, core
|
||||
channel-hook ◄── core
|
||||
channel-socket ◄── core
|
||||
core ◄── onebot, webui-backend
|
||||
websocket ◄── onebot, webui-backend
|
||||
ui ◄── webui-frontend
|
||||
```
|
||||
|
||||
**核心要点**:`core` 是唯一一处同时知道 `channel` 端口 + 业务实现的地方。Channel 包不反向依赖 core,因此 Hub **住在 core**,而不是 channel —— 名字保留 `Hub` 是因为它语义上仍是「channel 集群的指挥官」。
|
||||
|
||||
---
|
||||
|
||||
## 2. 三个关键类型 / 接口(设计核心)
|
||||
|
||||
整个系统由 **3 个类型** 串起来。每个职责单一、边界清晰。
|
||||
|
||||
### 2.1 `Channel`(在 `@snowluma/channel`)—— 纯 transport
|
||||
|
||||
```ts
|
||||
// packages/channel/src/channel.ts
|
||||
export type ChannelKind = 'inject' | 'socket';
|
||||
|
||||
export interface Channel {
|
||||
readonly kind: ChannelKind;
|
||||
readonly uin: string;
|
||||
readonly id: string; // adapter:uin 形式
|
||||
|
||||
sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult>;
|
||||
setPacketHandler(h: ((pkt: PacketInfo) => void) | null): void;
|
||||
deliverPacket(pkt: PacketInfo): void; // adapter 内部用
|
||||
dispose(): void;
|
||||
}
|
||||
```
|
||||
|
||||
Adapter 包(`channel-hook` / `channel-socket`)的具体类(`HookChannel` / `SocketChannel`)实现 `Channel`。它们的内部状态(PID set、hook session、socket fd)对外不可见。
|
||||
|
||||
### 2.2 `ChannelCtx`(在 `@snowluma/channel`)—— channel → core 的能力 POJO
|
||||
|
||||
```ts
|
||||
// packages/channel/src/channel-ctx.ts
|
||||
export interface ChannelCtx {
|
||||
readonly uin: string;
|
||||
readonly kind: ChannelKind;
|
||||
readonly sendRawPacket: (cmd: string, body: Uint8Array) => Promise<SendPacketResult>;
|
||||
readonly onPacket: (h: (pkt: PacketInfo) => void) => void;
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
// Hub 用 makeCtx(channel) 把 Channel 投影成 ChannelCtx:
|
||||
export function makeChannelCtx(b: Channel): ChannelCtx {
|
||||
return {
|
||||
uin: b.uin, kind: b.kind,
|
||||
sendRawPacket: (c, x) => b.sendRawPacket(c, x),
|
||||
onPacket: (h) => b.setPacketHandler(h),
|
||||
dispose: () => b.dispose(),
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**关键设计**:`Core` 只接收 `ChannelCtx`(capability POJO),**不**持有 `Channel` 类引用。这样 `core` 包不依赖任何 adapter 实现细节,连 Channel 抽象类都不用 import。
|
||||
|
||||
### 2.3 `CoreCtx`(在 `@snowluma/core`)—— core → onebot 的能力 POJO
|
||||
|
||||
```ts
|
||||
// packages/core/src/core-ctx.ts
|
||||
export interface CoreCtx {
|
||||
readonly uin: string;
|
||||
readonly kind: ChannelKind;
|
||||
readonly apis: ApiHub; // 所有 typed api(message/contacts/...)
|
||||
readonly events: EventBus; // 该账号的事件(per-uin)
|
||||
readonly identity: IdentityService; // UID/UIN/group roster
|
||||
}
|
||||
```
|
||||
|
||||
**关键设计**:OneBot 拿到的就是这个 POJO 投影,**不**持有 `Core` 类引用。Hub 在 `core-online` 事件里把 `CoreCtx` 透出去;OneBot 按 uin 存起来用。
|
||||
|
||||
---
|
||||
|
||||
## 3. `Hub` —— 主入口完整实现
|
||||
|
||||
所有所有权、生命周期、装配都在这里。**外部 main.ts 只跟它打交道。**
|
||||
|
||||
```ts
|
||||
// packages/core/src/hub.ts
|
||||
import { Channel, ChannelAdapter, ChannelAdapterHost, makeChannelCtx } from '@snowluma/channel';
|
||||
import { Core } from './core';
|
||||
import type { CoreCtx } from './core-ctx';
|
||||
import { TypedEmitter } from '@snowluma/common/typed-emitter';
|
||||
|
||||
type Lifecycle = {
|
||||
'core-online': CoreCtx;
|
||||
'core-offline': { uin: string };
|
||||
};
|
||||
|
||||
export class Hub {
|
||||
private readonly cores = new Map<string, Core>();
|
||||
private readonly adapters: ChannelAdapter[] = [];
|
||||
readonly events = new TypedEmitter<Lifecycle>();
|
||||
|
||||
registerAdapter(a: ChannelAdapter): void {
|
||||
this.adapters.push(a);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const host: ChannelAdapterHost = {
|
||||
onChannelReady: (b) => this.onChannelReady(b),
|
||||
onChannelGone: (uin) => this.onChannelGone(uin),
|
||||
};
|
||||
await Promise.all(this.adapters.map((a) => a.start(host)));
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await Promise.all(this.adapters.map((a) => a.stop()));
|
||||
for (const c of this.cores.values()) c.dispose();
|
||||
this.cores.clear();
|
||||
}
|
||||
|
||||
// ─── private ───────────────────────────────
|
||||
|
||||
private onChannelReady(channel: Channel): void {
|
||||
const stale = this.cores.get(channel.uin);
|
||||
if (stale) {
|
||||
stale.dispose();
|
||||
this.events.emit('core-offline', { uin: channel.uin });
|
||||
}
|
||||
const core = new Core(makeChannelCtx(channel));
|
||||
this.cores.set(channel.uin, core);
|
||||
this.events.emit('core-online', core.publicCtx);
|
||||
}
|
||||
|
||||
private onChannelGone(uin: string): void {
|
||||
const core = this.cores.get(uin);
|
||||
if (!core) return;
|
||||
core.dispose();
|
||||
this.cores.delete(uin);
|
||||
this.events.emit('core-offline', { uin });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4. `Core` 实现要点
|
||||
|
||||
```ts
|
||||
// packages/core/src/core.ts
|
||||
import type { ChannelCtx } from '@snowluma/channel';
|
||||
import { EventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import type { CoreCtx } from './core-ctx';
|
||||
|
||||
export class Core {
|
||||
readonly events = new EventBus(); // ← 每账号一个 bus
|
||||
readonly identity: IdentityService;
|
||||
readonly apis: ApiHub;
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
|
||||
constructor(private readonly channelCtx: ChannelCtx) {
|
||||
this.identity = IdentityService.openForUin(channelCtx.uin);
|
||||
this.pipeline = new IncomingPacketPipeline(this.events, this.identity);
|
||||
this.apis = buildApiHub(this); // apis 内部持 Core 引用,调 sendRawPacket
|
||||
channelCtx.onPacket((pkt) => this.pipeline.process(pkt));
|
||||
}
|
||||
|
||||
// 给外部消费者的投影(只读 POJO,不暴露 Core 实例)
|
||||
get publicCtx(): CoreCtx {
|
||||
return {
|
||||
uin: this.channelCtx.uin,
|
||||
kind: this.channelCtx.kind,
|
||||
apis: this.apis,
|
||||
events: this.events,
|
||||
identity: this.identity,
|
||||
};
|
||||
}
|
||||
|
||||
// apis 内部通过 core 调发包
|
||||
sendRawPacket(cmd: string, body: Uint8Array) {
|
||||
return this.channelCtx.sendRawPacket(cmd, body);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.channelCtx.dispose();
|
||||
this.identity.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 5. OneBot 消费 `CoreCtx`
|
||||
|
||||
```ts
|
||||
// packages/onebot/src/manager.ts
|
||||
import type { Hub, CoreCtx } from '@snowluma/core';
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly byUin = new Map<string, CoreCtx>();
|
||||
|
||||
bind(hub: Hub): void {
|
||||
hub.events.on('core-online', (ctx) => this.attach(ctx));
|
||||
hub.events.on('core-offline', ({ uin }) => this.detach(uin));
|
||||
}
|
||||
|
||||
private attach(ctx: CoreCtx): void {
|
||||
this.byUin.set(ctx.uin, ctx);
|
||||
ctx.events.on('group_message', (e) => this.dispatchGroupMessage(ctx, e));
|
||||
ctx.events.on('private_message',(e) => this.dispatchPrivateMessage(ctx, e));
|
||||
// ... 其它 kind
|
||||
}
|
||||
|
||||
private detach(uin: string): void {
|
||||
this.byUin.delete(uin);
|
||||
// ctx.events 随 Core dispose 一起释放
|
||||
}
|
||||
|
||||
// 处理 OneBot HTTP/WS action:用 uin 查到 ctx,直接调 apis
|
||||
async handleSendGroupMsg(uin: string, groupId: number, msg: OneBotMsg) {
|
||||
const ctx = this.byUin.get(uin);
|
||||
if (!ctx) throw new Error(`unknown uin: ${uin}`);
|
||||
return ctx.apis.message.sendGroup(groupId, msg); // ← 直接调封装好的 api
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 主入口(`packages/core/src/index.ts`)
|
||||
|
||||
```ts
|
||||
import { HookAdapter } from '@snowluma/channel-hook';
|
||||
import { OneBotManager } from '@snowluma/onebot';
|
||||
import { Hub } from './hub';
|
||||
|
||||
const hub = new Hub();
|
||||
hub.registerAdapter(new HookAdapter({ autoLoadOnDiscovery: true }));
|
||||
// hub.registerAdapter(new SocketAdapter()); // 未来
|
||||
|
||||
const onebot = new OneBotManager();
|
||||
onebot.bind(hub);
|
||||
|
||||
await hub.start();
|
||||
await initWebUI(port, onebot, /* hookManager from adapter */);
|
||||
```
|
||||
|
||||
9 行装配,每行都是有意义的所有权声明。
|
||||
|
||||
---
|
||||
|
||||
## 7. 为什么这样设计优雅
|
||||
|
||||
### 7.1 单向数据流
|
||||
|
||||
```
|
||||
adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot
|
||||
transport capability capability
|
||||
```
|
||||
|
||||
**没有反向引用**:Core 不知道 Channel 类,OneBot 不知道 Core 类。每层只看到「下一层的能力 POJO」。
|
||||
|
||||
### 7.2 单一所有者
|
||||
|
||||
`Hub.cores: Map<uin, Core>` 是 **唯一** 持有 Core 的地方。OneBot 只持 `CoreCtx`(投影,不算所有权)。Core 销毁 = 从这个 Map 里删 = 所有 ctx 同时失效。无需引用计数、无需 GC 协调。
|
||||
|
||||
### 7.3 每账号独立 EventBus
|
||||
|
||||
Core 自带 `events: EventBus`,互不干扰。OneBot 通过 `core-online` 拿到 ctx 后立即 subscribe,`core-offline` 时 Core 已 dispose,bus 自然失效,不会泄漏。**没有全局 bus**,没有「哪个账号的事件」问题。
|
||||
|
||||
### 7.4 完全可测
|
||||
|
||||
- 测 Channel:mock `setPacketHandler` 回调(已在 `account-private-routing.test.ts` 用 `FakeChannel` 验证)
|
||||
- 测 Core:传 `ChannelCtx` POJO 即可,无需真 Channel
|
||||
- 测 OneBot:emit 一个 `core-online` + 假 `CoreCtx`
|
||||
- 测 Hub:用 fake `ChannelAdapter`
|
||||
|
||||
每层都能独立测试。
|
||||
|
||||
### 7.5 内部还要避免 ctx 漫天的两个小招
|
||||
|
||||
**(a) Api 类捕获 deps(已做)**
|
||||
|
||||
```ts
|
||||
class MessageApi {
|
||||
constructor(private readonly core: Core) {}
|
||||
// 方法签名只有业务参数:
|
||||
async sendGroup(groupId: number, msg: Msg) { this.core.sendRawPacket(...) }
|
||||
}
|
||||
```
|
||||
|
||||
**(b) AsyncLocalStorage 处理日志 / trace(建议引入)**
|
||||
|
||||
```ts
|
||||
// packages/common/src/async-context.ts
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
const als = new AsyncLocalStorage<{ uin?: string; trace?: string }>();
|
||||
|
||||
export const runInContext = <T>(c: { uin?: string; trace?: string }, fn: () => T) =>
|
||||
als.run(c, fn);
|
||||
export const ctx = () => als.getStore() ?? {};
|
||||
|
||||
// logger 自动 prefix [uin],业务代码不用接 log 参数
|
||||
```
|
||||
|
||||
在 `Core.constructor` 给 `onPacket` 包一层:
|
||||
```ts
|
||||
channelCtx.onPacket((pkt) => {
|
||||
runInContext({ uin: channelCtx.uin, trace: `pkt:${pkt.seqId}` }, () => {
|
||||
this.pipeline.process(pkt);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
所有下游 `log.info()` 自动带 `[10001]` 前缀,不污染业务签名。开销 ~50ns/call。
|
||||
|
||||
---
|
||||
|
||||
## 8. 不要的设计(保持简单)
|
||||
|
||||
| 方案 | 不做的原因 |
|
||||
|---|---|
|
||||
| **`CoreFactory` 抽象** | Core 只一种,多此一举。直接 `new Core(ctx)` |
|
||||
| **全局 EventBus** | 每账号自己的 bus 更清晰,OneBot 按 uin 订阅,不混杂 |
|
||||
| **`AccountManager` 独立层** | 多余的中间层,折进 `Hub` |
|
||||
| **`InboundAdapter` 抽象** | OneBot / WebUI 数量有限且固定,直接 `bm.events.on(...)` 即可,不抽插件层 |
|
||||
| **DI 容器(tsyringe 等)** | 9 行手动装配已经清晰,DI 引入反射/装饰器元数据反而难调 |
|
||||
| **Effect monad / Reader monad** | TS 缺 do-notation,类型噪音 > 收益 |
|
||||
| **CQRS / Event-sourced state** | 当前状态量级(10 账号 × 100 群)远未到 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 迁移路线(每步独立可 ship)
|
||||
|
||||
> typecheck + 全测试通过才进下一步。
|
||||
|
||||
**Step 1** —— ⭐ 重命名 + 拆现有的 `@snowluma/bridge`
|
||||
- `packages/bridge/` 重命名为 `packages/channel/`;package.json name 改为 `@snowluma/channel`
|
||||
- 新建 `packages/channel-hook/`,从 `@snowluma/channel` 搬:`hook-manager.ts` / `hook-session.ts` / `hook-packet-client.ts` / `injector.ts` / `pipe-watcher.ts` / `qq-hook-client.ts` / `qq-port-probe.ts` / `hook-channel.ts`(原 inject-bridge.ts)/ `hook-adapter.ts`(原 inject-adapter.ts)
|
||||
- `@snowluma/channel` 留:`channel.ts`(abstract,原 bridge.ts)/ `channel-interface.ts` / `channel-ctx.ts`(新)/ `adapter.ts`(端口)+ `makeChannelCtx` 工具
|
||||
- 删除:`manager.ts`(原 BridgeManager)(搬到 core/hub.ts)/ `socket-channel.ts` + `socket-adapter.ts`(搬到 `channel-socket` stub)
|
||||
|
||||
**Step 2** —— ⭐ 重塑 `@snowluma/core`
|
||||
- 删除:`account/account.ts` / `account-interface.ts` / `account-context.ts` / `account-manager.ts`
|
||||
- 新建:`core.ts`(吸收 Account 业务,构造接 `ChannelCtx`)/ `core-ctx.ts` / `hub.ts`
|
||||
- `apis/` 内部 `AccountContext` → `Core`(直接拿 Core 类型)
|
||||
- `index.ts` 9 行装配(见 §6)
|
||||
|
||||
**Step 3** —— OneBot 适配 CoreCtx
|
||||
- 全局 `AccountInterface` → `CoreCtx`
|
||||
- `OneBotManager.bind(hub)` 订阅 `'core-online'` / `'core-offline'`
|
||||
- 内部 `byUin.get(uin).apis.<area>.method()` 调 api
|
||||
|
||||
**Step 4** —— 引入 `AsyncLocalStorage`
|
||||
- `packages/common/src/async-context.ts`
|
||||
- `logger.ts` 自动读 ALS,加 `[uin]` 前缀
|
||||
- `Core.constructor` 在 `onPacket` 回调外包 `runInContext`
|
||||
|
||||
**Step 5** —— `channel-socket` stub 包(占位)
|
||||
- 把 `socket-channel.ts` / `socket-adapter.ts` 搬过来
|
||||
- 实现 placeholder,让 `ChannelAdapter` 端口齐
|
||||
|
||||
**Step 6** —— ⭐ 拆 `webui` 为 `webui-backend` + `webui-frontend`
|
||||
- Hono server + REST/WS → `webui-backend`,依赖 `@snowluma/core`(消费 `CoreCtx`)
|
||||
- Vite SPA + UI → `webui-frontend`,依赖 `@snowluma/ui`
|
||||
|
||||
---
|
||||
|
||||
## 10. 设计原则速查
|
||||
|
||||
- **单向数据流**:`adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot`,无反向引用
|
||||
- **能力 POJO 跨层传递**:层间用 `{ uin, sendRawPacket, ... }` / `{ uin, apis, events, ... }` 这种纯数据,不传类实例
|
||||
- **单一所有者**:`Hub.cores` 是 Core 唯一容器,消费者只持投影
|
||||
- **每账号自带 EventBus**:避免全局 bus 混杂,订阅生命周期与 Core 绑定
|
||||
- **Class 封装 deps**:构造时捕获,方法签名只剩业务参数
|
||||
- **AsyncLocalStorage 跨切面**:日志 / trace 不进显式参数
|
||||
- **不引入过度抽象**:no factory / no DI / no Effect monad / no global bus
|
||||
- **可测**:每层接 POJO,fake 一下就能测
|
||||
|
||||
---
|
||||
|
||||
## 11. v2.0.0 已完成
|
||||
|
||||
- ✅ UID/UIN Service + SQLite 持久化
|
||||
- ✅ tsx 免打包 Debug
|
||||
- ✅ Common / OneBot / Core / Bridge / Protocol / proto-defs 拆包
|
||||
- ✅ 消息 hot-path 优化(17.5μs → 4.7μs,better-sqlite3 + prepared-statement cache)
|
||||
- ✅ NapCat 风格 Api 层(13 Api 类)
|
||||
- ✅ Bridge / Account 严格分层(v2 中间形态;v3 重命名为 Channel + Core,并用 ctx 替代直接引用)
|
||||
- ✅ `@snowluma/bridge` 完整 transport 包(v3 重命名为 `@snowluma/channel`)
|
||||
|
||||
|
||||
|
||||
|
||||
105
eslint.config.ts
Normal file
105
eslint.config.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import js from '@eslint/js';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/coverage/**',
|
||||
'**/.turbo/**',
|
||||
'**/.vite/**',
|
||||
'**/*.tsbuildinfo',
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
// OIDB service layer is namespace-per-cmd by design — the
|
||||
// structural-typing contract (namespace IS the OidbCallSpec) and
|
||||
// the file:cmd 1:1 mapping are the whole point. Disable the
|
||||
// module-syntax preference here only.
|
||||
files: [
|
||||
'packages/protocol/src/oidb-services/**/*.ts',
|
||||
'packages/protocol/tests/oidb-services/**/*.ts',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
21
package.json
21
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.8.4",
|
||||
"version": "1.9.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -15,21 +15,34 @@
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "pnpm -r --if-present lint",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"start": "node dist/index.mjs",
|
||||
"bump": "node tools/bump-version.mjs",
|
||||
"release": "node tools/release.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@vitest/coverage-istanbul": "4.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"cross-env": "^10.1.0",
|
||||
"typescript": "catalog:"
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
"allowedVersions": {
|
||||
"eslint-plugin-react-hooks>eslint": "10"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"better-sqlite3"
|
||||
]
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"engines": {
|
||||
|
||||
69
packages/channel-hook/package.json
Normal file
69
packages/channel-hook/package.json
Normal file
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"name": "@snowluma/channel-hook",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma `inject` channel implementation — in-process NTQQ hook runtime. Bundles HookManager / HookSession / pipe-watcher / injector / qq-hook-client plus the `HookChannel` and `HookAdapter` that `Hub` (in @snowluma/core) registers as the primary transport on Windows. Depends on `@snowluma/channel` for the abstract `Channel` + `ChannelAdapter` contracts.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./hook-channel": {
|
||||
"types": "./src/hook-channel.ts",
|
||||
"default": "./src/hook-channel.ts"
|
||||
},
|
||||
"./hook-adapter": {
|
||||
"types": "./src/hook-adapter.ts",
|
||||
"default": "./src/hook-adapter.ts"
|
||||
},
|
||||
"./hook-manager": {
|
||||
"types": "./src/hook-manager.ts",
|
||||
"default": "./src/hook-manager.ts"
|
||||
},
|
||||
"./hook-session": {
|
||||
"types": "./src/hook-session.ts",
|
||||
"default": "./src/hook-session.ts"
|
||||
},
|
||||
"./hook-packet-client": {
|
||||
"types": "./src/hook-packet-client.ts",
|
||||
"default": "./src/hook-packet-client.ts"
|
||||
},
|
||||
"./injector": {
|
||||
"types": "./src/injector.ts",
|
||||
"default": "./src/injector.ts"
|
||||
},
|
||||
"./pipe-watcher": {
|
||||
"types": "./src/pipe-watcher.ts",
|
||||
"default": "./src/pipe-watcher.ts"
|
||||
},
|
||||
"./qq-hook-client": {
|
||||
"types": "./src/qq-hook-client.ts",
|
||||
"default": "./src/qq-hook-client.ts"
|
||||
},
|
||||
"./qq-port-probe": {
|
||||
"types": "./src/qq-port-probe.ts",
|
||||
"default": "./src/qq-port-probe.ts"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./src/types.ts",
|
||||
"default": "./src/types.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
174
packages/channel-hook/src/hook-adapter.ts
Normal file
174
packages/channel-hook/src/hook-adapter.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { HookChannel } from './hook-channel';
|
||||
import { HookManager, type HookManagerDeps, type HookSink } from './hook-manager';
|
||||
|
||||
/** Subset of `HookManagerDeps` the operator is allowed to forward
|
||||
* through the adapter. The `sink` is owned by the adapter itself and
|
||||
* intentionally not exposed. */
|
||||
export type HookAdapterOptions = Omit<HookManagerDeps, 'sink'>;
|
||||
|
||||
/**
|
||||
* `HookAdapter` — the `ChannelAdapter` for the NTQQ hook runtime. It
|
||||
* owns the `HookManager` and translates its three sink callbacks
|
||||
* (`onHookLogin` / `onPacket` / `onPidDisconnected`) into lifecycle
|
||||
* events on a per-UIN `HookChannel`.
|
||||
*
|
||||
* Why an adapter rather than letting the `Hub` keep the hook sink:
|
||||
* this is the only place in the codebase that legitimately needs to
|
||||
* know about PIDs. Quarantining that knowledge here keeps the `Hub`
|
||||
* (and everything above it) free of `pid`, leaving the door open for
|
||||
* a future `SocketAdapter` that doesn't have the concept at all.
|
||||
*
|
||||
* Internal bookkeeping:
|
||||
*
|
||||
* - `pidToUin` — quick "which UIN does this PID feed?" lookup,
|
||||
* populated on login (and lazily during defensive
|
||||
* packet routing for PIDs that arrived ahead of
|
||||
* their login notification).
|
||||
* - `pidToSender` — the live `PacketSender` per PID, so a re-login
|
||||
* from the same PID rotates the outbound sender
|
||||
* without dropping the channel.
|
||||
* - `uinToPids` — reverse index for fast "did this UIN lose its
|
||||
* last PID?" checks on disconnect.
|
||||
* - `channelsByUin` — one `HookChannel` per UIN; the hub only sees
|
||||
* `Channel` instances, never the PID set living
|
||||
* inside them.
|
||||
*/
|
||||
export class HookAdapter implements ChannelAdapter, HookSink {
|
||||
readonly kind = 'inject' as const;
|
||||
|
||||
private readonly hookManager_: HookManager;
|
||||
|
||||
private readonly pidToUin = new Map<number, string>();
|
||||
private readonly pidToSender = new Map<number, PacketSender>();
|
||||
private readonly uinToPids = new Map<string, Set<number>>();
|
||||
private readonly channelsByUin = new Map<string, HookChannel>();
|
||||
|
||||
private host_: ChannelAdapterHost | null = null;
|
||||
private disposed_ = false;
|
||||
|
||||
constructor(opts: HookAdapterOptions = {}) {
|
||||
// `sink: this` wires HookManager → adapter sink. The HookManager
|
||||
// doesn't know about the broader ChannelAdapter contract; it only
|
||||
// sees the three sink methods we implement below.
|
||||
this.hookManager_ = new HookManager({ ...opts, sink: this });
|
||||
}
|
||||
|
||||
/** The underlying `HookManager`, exposed so WebUI can keep its
|
||||
* `/api/processes/*` endpoints pointing at the hook process table.
|
||||
* Higher-level code (OneBot, channel consumers) MUST NOT reach into
|
||||
* this — that's the whole point of the adapter layer. */
|
||||
get hookManager(): HookManager { return this.hookManager_; }
|
||||
|
||||
// ─── ChannelAdapter contract ─────────────────────────────────────
|
||||
|
||||
start(host: ChannelAdapterHost): void {
|
||||
this.host_ = host;
|
||||
host.log.debug('hook adapter started');
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed_) return;
|
||||
this.disposed_ = true;
|
||||
// Tear down hook sessions first so no more sink callbacks fire.
|
||||
this.hookManager_.dispose();
|
||||
// Then proactively remove every channel we published; the hub
|
||||
// will call `channel.dispose()` on its way out.
|
||||
for (const id of [...this.channelsByUin.values()].map(c => c.id)) {
|
||||
this.host_?.removeChannel(id);
|
||||
}
|
||||
this.pidToUin.clear();
|
||||
this.pidToSender.clear();
|
||||
this.uinToPids.clear();
|
||||
this.channelsByUin.clear();
|
||||
this.host_ = null;
|
||||
}
|
||||
|
||||
// ─── HookSink contract (called by HookManager) ──────────────────
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (this.disposed_ || !isRealUin(uin)) return;
|
||||
|
||||
this.recordPidMapping(pid, uin, packetClient);
|
||||
const channel = this.ensureChannel(uin);
|
||||
channel.attachPid(pid, packetClient);
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (this.disposed_ || !pkt.uin || !isRealUin(pkt.uin)) return;
|
||||
|
||||
const uin = pkt.uin;
|
||||
const channel = this.ensureChannel(uin);
|
||||
|
||||
// Defensive: a packet may arrive before its login notification
|
||||
// when the channel is being re-adopted (SnowLuma restarted while
|
||||
// the hook stayed resident in QQ.exe). If we have a sender for
|
||||
// this PID, weave it in so subsequent sends through this channel
|
||||
// succeed.
|
||||
if (pkt.pid) {
|
||||
const sender = this.pidToSender.get(pkt.pid);
|
||||
if (sender && !this.pidToUin.has(pkt.pid)) {
|
||||
this.recordPidMapping(pkt.pid, uin, sender);
|
||||
channel.attachPid(pkt.pid, sender);
|
||||
}
|
||||
}
|
||||
|
||||
channel.deliverPacket(pkt);
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
if (this.disposed_) return;
|
||||
this.pidToSender.delete(pid);
|
||||
|
||||
const uin = this.pidToUin.get(pid);
|
||||
if (!uin) return;
|
||||
this.pidToUin.delete(pid);
|
||||
|
||||
const pids = this.uinToPids.get(uin);
|
||||
if (pids) {
|
||||
pids.delete(pid);
|
||||
if (pids.size === 0) this.uinToPids.delete(uin);
|
||||
}
|
||||
|
||||
const channel = this.channelsByUin.get(uin);
|
||||
if (!channel) return;
|
||||
channel.detachPid(pid);
|
||||
|
||||
if (channel.isEmpty) {
|
||||
this.channelsByUin.delete(uin);
|
||||
this.host_?.removeChannel(channel.id);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── internal ────────────────────────────────────────────────────
|
||||
|
||||
private recordPidMapping(pid: number, uin: string, sender: PacketSender): void {
|
||||
this.pidToUin.set(pid, uin);
|
||||
this.pidToSender.set(pid, sender);
|
||||
let pids = this.uinToPids.get(uin);
|
||||
if (!pids) {
|
||||
pids = new Set();
|
||||
this.uinToPids.set(uin, pids);
|
||||
}
|
||||
pids.add(pid);
|
||||
}
|
||||
|
||||
private ensureChannel(uin: string): HookChannel {
|
||||
let channel = this.channelsByUin.get(uin);
|
||||
if (channel) return channel;
|
||||
channel = new HookChannel(uin);
|
||||
this.channelsByUin.set(uin, channel);
|
||||
this.host_?.addChannel(channel);
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
// QQ uins are 5-12 decimal digits; "0" is the hook's "no login yet"
|
||||
// sentinel. Anything else (empty, alpha, too short) is a sign the hook
|
||||
// callback fired before login info was probed — we ignore those.
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
82
packages/channel-hook/src/hook-channel.ts
Normal file
82
packages/channel-hook/src/hook-channel.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Channel } from '@snowluma/channel';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
/**
|
||||
* `HookChannel` — concrete transport backed by the in-process NTQQ
|
||||
* hook. One UIN may be served simultaneously by several injected
|
||||
* processes; the channel therefore tracks an unordered set of PIDs and
|
||||
* keeps a single live `PacketSender` (the most recently logged-in
|
||||
* pipe) for outbound traffic.
|
||||
*
|
||||
* PID bookkeeping is scoped to this transport because the socket-only
|
||||
* runtime never has the concept; quarantining it here keeps the
|
||||
* abstract `Channel` and the `Hub` free of pid awareness.
|
||||
*
|
||||
* The owning `HookAdapter` is responsible for calling
|
||||
* `attachPid(pid, sender)` on every successful hook login,
|
||||
* `detachPid(pid)` when the watcher reports a pipe drop, and tearing
|
||||
* the channel down once `isEmpty` returns true.
|
||||
*/
|
||||
export class HookChannel extends Channel {
|
||||
readonly kind = 'inject' as const;
|
||||
readonly uin: string;
|
||||
|
||||
private readonly pids_ = new Set<number>();
|
||||
private packetClient_: PacketSender | null = null;
|
||||
|
||||
constructor(uin: string) {
|
||||
super();
|
||||
this.uin = uin;
|
||||
}
|
||||
|
||||
get id(): string { return `inject:${this.uin}`; }
|
||||
|
||||
/** PIDs currently routing packets into this channel. Read-only view
|
||||
* for diagnostics — mutate only via `attachPid` / `detachPid`. */
|
||||
get pids(): ReadonlySet<number> { return this.pids_; }
|
||||
|
||||
/** True iff no PID is currently bound; the adapter uses this to
|
||||
* decide when to remove the channel from the `Hub`. */
|
||||
get isEmpty(): boolean { return this.pids_.size === 0; }
|
||||
|
||||
/** Bind a freshly-logged-in PID (and its outbound `PacketSender`)
|
||||
* to this channel. Idempotent — re-binding the same PID just rotates
|
||||
* the active sender. */
|
||||
attachPid(pid: number, sender: PacketSender): void {
|
||||
this.pids_.add(pid);
|
||||
this.packetClient_ = sender;
|
||||
}
|
||||
|
||||
/** Forget a PID. If it owned the active sender we drop it; the next
|
||||
* `attachPid` (or pipe-up) will install a fresh one. */
|
||||
detachPid(pid: number): void {
|
||||
this.pids_.delete(pid);
|
||||
if (this.pids_.size === 0) {
|
||||
this.packetClient_ = null;
|
||||
}
|
||||
}
|
||||
|
||||
override async sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs = 15000,
|
||||
): Promise<SendPacketResult> {
|
||||
const client = this.packetClient_;
|
||||
if (!client) {
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'hook channel has no live packet sender',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
}
|
||||
|
||||
override dispose(): void {
|
||||
super.dispose();
|
||||
this.packetClient_ = null;
|
||||
this.pids_.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,40 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
|
||||
import fs from 'fs';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import type { PacketSink } from '../protocol/types';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
|
||||
/**
|
||||
* Sink that the hook layer calls back into when it observes a new login,
|
||||
* a parsed packet, or a PID disconnect. The concrete implementation is
|
||||
* `HookAdapter`, which sits between this hook runtime and the `Hub` in
|
||||
* `@snowluma/core`. Declaring it here keeps `@snowluma/channel` (and
|
||||
* future `@snowluma/channel-hook`) free of any dependency on
|
||||
* `@snowluma/core` — the hook package is self-contained.
|
||||
*/
|
||||
export interface HookSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
bridgeManager: BridgeManager;
|
||||
sink: HookSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `bridgeManager.onPacket` — every packet flows straight into the
|
||||
* per-UIN bridge dispatcher with no intermediate event emitter. */
|
||||
* `sink.onPacket` — every packet flows straight into the per-UIN
|
||||
* channel dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
@@ -46,7 +60,7 @@ export type HookManagerDeps = {
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected') to BridgeManager.
|
||||
* - Forward session events ('login' / 'disconnected') to the `HookSink`.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
*
|
||||
@@ -55,7 +69,7 @@ export type HookManagerDeps = {
|
||||
* real QQ.exe or a native addon.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly bridgeManager: BridgeManager;
|
||||
private readonly sink: HookSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
@@ -70,8 +84,8 @@ export class HookManager {
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: HookManagerDeps) {
|
||||
this.bridgeManager = deps.bridgeManager;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
||||
this.sink = deps.sink;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.sink.onPacket(pkt));
|
||||
this.log = deps.log ?? createLogger('Hook');
|
||||
|
||||
this.injector = deps.injector ?? {
|
||||
@@ -147,6 +161,11 @@ export class HookManager {
|
||||
return session.refresh();
|
||||
}
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
@@ -191,14 +210,25 @@ export class HookManager {
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeDown();
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting'
|
||||
// while the pipe is up. Mirrors the original tickWatcher's per-tick
|
||||
// reconcileConnect pass; onPipeUp is idempotent so calling it for an
|
||||
// already-connected session is harmless.
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
|
||||
// so calling it for an already-connected session is harmless.
|
||||
//
|
||||
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
|
||||
// the named pipe stays alive but the SnowLuma-side socket dies (read
|
||||
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
|
||||
// sees the pipe as still-live (the OS-level pipe is still listed by
|
||||
// `listLivePipes`) so it never fires another `pipe-up`. Without
|
||||
// retrying 'disconnected' sessions here the session is stranded
|
||||
// forever — a real-world symptom users reported as "Windows running
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
if (this.disposed) return;
|
||||
for (const session of this.sessions.values()) {
|
||||
if (session.status === 'connecting' && this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
if ((session.status === 'connecting' || session.status === 'disconnected')
|
||||
&& this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
@@ -219,10 +249,10 @@ export class HookManager {
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
this.sink.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
if (wasLoggedIn) this.sink.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
@@ -280,3 +310,7 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
export type { QqPortLoginInfo } from './qq-port-probe';
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
constructor(private readonly client: QqHookClient) {}
|
||||
constructor(private readonly client: QqHookClient) { }
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
import { EventEmitter } from 'events';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
import type { PacketSink } from '../protocol/types';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import type { HookInjectResult } from './injector';
|
||||
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
|
||||
@@ -21,8 +20,8 @@ export type HookSessionDeps = {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the BridgeManager-shaped
|
||||
* PacketInfo for every packet received while logged in. If omitted,
|
||||
/** Sink for parsed packets. Called with the canonical PacketInfo
|
||||
* shape for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
onPacket?: PacketSink;
|
||||
log?: Logger;
|
||||
@@ -36,7 +35,7 @@ export type HookSessionDeps = {
|
||||
* promise chain so user clicks (load/unload/refresh) and watcher-driven
|
||||
* events (onPipeUp/onPipeDown) never interleave.
|
||||
*
|
||||
* Communication: emits high-level events instead of calling BridgeManager
|
||||
* Communication: emits high-level events instead of calling the sink
|
||||
* directly, so HookManager forwards them and tests can attach spies.
|
||||
*
|
||||
* Emitted events:
|
||||
@@ -407,7 +406,7 @@ export class HookSession extends EventEmitter {
|
||||
const uin = packet.uin || this._uin;
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
// Re-shape the hook-client wire packet into the canonical PacketInfo
|
||||
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
|
||||
// renaming was that module's entire purpose, so it lives at the source
|
||||
// now (no need for a single-listener event-emitter in between).
|
||||
15
packages/channel-hook/src/index.ts
Normal file
15
packages/channel-hook/src/index.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
// `@snowluma/channel-hook` — the `inject` channel implementation
|
||||
// (NTQQ in-process hook). Registered with `Hub` from `@snowluma/core`
|
||||
// as a `ChannelAdapter` of kind `'inject'`. Everything pid-related is
|
||||
// scoped to this package — neither `@snowluma/channel` nor anything
|
||||
// downstream knows about it.
|
||||
|
||||
// ─── Hook runtime ──────────────────────────────────────────────────
|
||||
export {
|
||||
HookManager, type HookSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
} from './hook-manager';
|
||||
|
||||
// ─── Concrete Channel + Adapter ────────────────────────────────────
|
||||
export { HookChannel } from './hook-channel';
|
||||
export { HookAdapter, type HookAdapterOptions } from './hook-adapter';
|
||||
@@ -55,12 +55,13 @@ function defaultProcessName(): string {
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
|
||||
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
|
||||
// 2. Dev via tsx (packages/channel/src/injector.ts): __dirname=<root>/packages/channel/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/channel/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', '..', 'runtime', 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { EventEmitter } from 'events';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 1500;
|
||||
@@ -1,8 +1,8 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export const PIPE_MAGIC = 0x31504851;
|
||||
export const PIPE_VERSION = 1;
|
||||
@@ -235,7 +235,7 @@ function encodeFrame({
|
||||
class FrameReader {
|
||||
private buffer = Buffer.alloc(0);
|
||||
|
||||
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
|
||||
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
|
||||
|
||||
push(chunk: Buffer): void {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||
@@ -513,7 +513,7 @@ export class QqHookClient extends EventEmitter {
|
||||
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
|
||||
|
||||
const worker = async () => {
|
||||
for (;;) {
|
||||
for (; ;) {
|
||||
const index = nextIndex;
|
||||
nextIndex += 1;
|
||||
if (index >= items.length) return;
|
||||
@@ -624,7 +624,7 @@ export class QqHookClient extends EventEmitter {
|
||||
else resolve();
|
||||
});
|
||||
}));
|
||||
this.controlWriteChain = writePromise.catch(() => {});
|
||||
this.controlWriteChain = writePromise.catch(() => { });
|
||||
return writePromise;
|
||||
}
|
||||
|
||||
168
packages/channel-hook/src/qq-port-probe.ts
Normal file
168
packages/channel-hook/src/qq-port-probe.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
loggedIn: boolean;
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
errCode: number;
|
||||
errMsg: string;
|
||||
port: number;
|
||||
uin?: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
data?: {
|
||||
uin?: string;
|
||||
url?: string;
|
||||
};
|
||||
iat: number;
|
||||
}
|
||||
|
||||
function decodeJwt(token: string): JwtPayload | null {
|
||||
try {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
|
||||
return JSON.parse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
const link = 'tencent://';
|
||||
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
|
||||
|
||||
let responseData = '';
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
|
||||
client.setTimeout(CONNECTION_TIMEOUT_MS);
|
||||
|
||||
client.connect(port, '127.0.0.1', () => {
|
||||
client.write(payload);
|
||||
});
|
||||
|
||||
client.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
cleanup();
|
||||
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
|
||||
if (!jwtMatch) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = decodeJwt(jwtMatch[0]);
|
||||
if (!decoded || decoded.errCode !== 0) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = decoded.uin || decoded.data?.uin || '';
|
||||
resolve({
|
||||
port,
|
||||
uin,
|
||||
uid: decoded.uid,
|
||||
nickName: decoded.nickName,
|
||||
loggedIn: uin.length > 0,
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
client.on('timeout', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
const port = Number(portMatch[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
const port = Number(match[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const port of ports) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,11 +1,5 @@
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
/**
|
||||
* Lifecycle status of a single per-PID HookSession.
|
||||
*
|
||||
* Transitions live inside HookSession; this union only enumerates the
|
||||
* states visible to API callers (WebUI, manager.listProcesses()).
|
||||
*/
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
@@ -3,12 +3,12 @@ import { EventEmitter } from 'events';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { HookManager, shouldAutoLoadPid } 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';
|
||||
import { createLogger } from '../src/utils/logger';
|
||||
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { HookSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
@@ -37,13 +37,13 @@ function makeManager(opts: {
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
const sink = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManager;
|
||||
} as unknown as HookSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
sink,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
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';
|
||||
import { HookManager } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { HookSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
@@ -41,14 +41,14 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
const sink = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManager;
|
||||
} as unknown as HookSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
sink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
@@ -82,9 +82,9 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
|
||||
// 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();
|
||||
expect(sink.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(sink.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(sink.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
@@ -17,9 +17,9 @@
|
||||
|
||||
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';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
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, QqHookPacket } from '../src/hook/qq-hook-client';
|
||||
import type { PacketSink } from '../src/protocol/types';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { PipeWatcher } from '../src/hook/pipe-watcher';
|
||||
import type { HookProcessBaseInfo } from '../src/hook/injector';
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
|
||||
let processes = initial.processes;
|
||||
@@ -2,7 +2,7 @@ import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids } from '../src/hook/qq-hook-client';
|
||||
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
16
packages/channel-hook/tsconfig.json
Normal file
16
packages/channel-hook/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
8
packages/channel-hook/vitest.config.ts
Normal file
8
packages/channel-hook/vitest.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
34
packages/channel-socket/package.json
Normal file
34
packages/channel-socket/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@snowluma/channel-socket",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma `socket` channel implementation — placeholder for the future pure-socket runtime (no QQ.exe, no hook). Today registers as a no-op `ChannelAdapter` so the Hub-adapter architecture is exercised end-to-end. Will gain a `SocketClient` long-lived TCP login session when the protocol runtime lands.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./socket-channel": {
|
||||
"types": "./src/socket-channel.ts",
|
||||
"default": "./src/socket-channel.ts"
|
||||
},
|
||||
"./socket-adapter": {
|
||||
"types": "./src/socket-adapter.ts",
|
||||
"default": "./src/socket-adapter.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
8
packages/channel-socket/src/index.ts
Normal file
8
packages/channel-socket/src/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// `@snowluma/channel-socket` — future pure-socket transport (no
|
||||
// QQ.exe, no hook). Today an empty stub so `Hub` can register it as a
|
||||
// `ChannelAdapter` of kind `'socket'` and exercise the adapter pool
|
||||
// end-to-end. Will materialise a real `SocketChannel` once the
|
||||
// pure-socket login client lands.
|
||||
|
||||
export { SocketChannel } from './socket-channel';
|
||||
export { SocketAdapter } from './socket-adapter';
|
||||
30
packages/channel-socket/src/socket-adapter.ts
Normal file
30
packages/channel-socket/src/socket-adapter.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
|
||||
|
||||
/**
|
||||
* `SocketAdapter` — placeholder for the future pure-socket runtime.
|
||||
* Once a `SocketClient` (long-lived TCP login session, heartbeat,
|
||||
* reconnect loop, …) lands, this adapter will:
|
||||
*
|
||||
* 1. Read its account list from runtime config.
|
||||
* 2. Spin up one `SocketClient` per configured account.
|
||||
* 3. On successful login, materialise a `SocketChannel` and call
|
||||
* `host.addChannel(channel)`.
|
||||
* 4. On logout / fatal error, call `host.removeChannel(channel.id)`.
|
||||
*
|
||||
* Until that lands the adapter is registered as a no-op so the wider
|
||||
* architecture (Hub → ChannelAdapter[] → Channel → Core) is already in
|
||||
* place and exercised in production. Registering it is harmless:
|
||||
* `start()` does nothing, `dispose()` does nothing, no channels are
|
||||
* ever produced.
|
||||
*/
|
||||
export class SocketAdapter implements ChannelAdapter {
|
||||
readonly kind = 'socket' as const;
|
||||
|
||||
start(host: ChannelAdapterHost): void {
|
||||
host.log.debug('socket adapter is a stub; no socket clients will be opened');
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
// Nothing to tear down yet.
|
||||
}
|
||||
}
|
||||
41
packages/channel-socket/src/socket-channel.ts
Normal file
41
packages/channel-socket/src/socket-channel.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Channel } from '@snowluma/channel';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
/**
|
||||
* `SocketChannel` — placeholder transport for the future pure-socket
|
||||
* runtime (no QQ.exe, no hook). It already participates in the `Hub`
|
||||
* (in `@snowluma/core`) so the wider architecture (ChannelAdapter pool
|
||||
* → Hub → Core → OneBot) is exercised end-to-end today; once a real
|
||||
* `SocketClient` lands the transport will gain a constructor argument
|
||||
* and `sendRawPacket` will route through it.
|
||||
*
|
||||
* Until then `sendRawPacket` returns a structured "not implemented"
|
||||
* failure rather than throwing, so the surrounding code treats it as
|
||||
* a regular transport-down result.
|
||||
*/
|
||||
export class SocketChannel extends Channel {
|
||||
readonly kind = 'socket' as const;
|
||||
readonly uin: string;
|
||||
|
||||
constructor(uin: string) {
|
||||
super();
|
||||
this.uin = uin;
|
||||
}
|
||||
|
||||
get id(): string { return `socket:${this.uin}`; }
|
||||
|
||||
override async sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult> {
|
||||
void serviceCmd; void body; void timeoutMs;
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'socket channel transport is not yet implemented',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
15
packages/channel-socket/tsconfig.json
Normal file
15
packages/channel-socket/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
44
packages/channel/package.json
Normal file
44
packages/channel/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@snowluma/channel",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma transport abstract layer. Defines the `Channel` abstract base + `ChannelCtx` capability POJO + `ChannelAdapter` port that `Hub` (in @snowluma/core) consumes. Concrete transports live in `@snowluma/channel-hook` (in-process NTQQ hook) and `@snowluma/channel-socket` (future pure-socket).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./channel": {
|
||||
"types": "./src/channel.ts",
|
||||
"default": "./src/channel.ts"
|
||||
},
|
||||
"./channel-interface": {
|
||||
"types": "./src/channel-interface.ts",
|
||||
"default": "./src/channel-interface.ts"
|
||||
},
|
||||
"./channel-ctx": {
|
||||
"types": "./src/channel-ctx.ts",
|
||||
"default": "./src/channel-ctx.ts"
|
||||
},
|
||||
"./adapter": {
|
||||
"types": "./src/adapter.ts",
|
||||
"default": "./src/adapter.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
15
packages/channel/src/adapter.ts
Normal file
15
packages/channel/src/adapter.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { Logger } from '@snowluma/common/logger';
|
||||
import type { Channel } from './channel';
|
||||
import type { ChannelKind } from './channel-interface';
|
||||
|
||||
export interface ChannelAdapterHost {
|
||||
addChannel(channel: Channel): void;
|
||||
removeChannel(channelId: string): void;
|
||||
readonly log: Logger;
|
||||
}
|
||||
|
||||
export interface ChannelAdapter {
|
||||
readonly kind: ChannelKind;
|
||||
start(host: ChannelAdapterHost): Promise<void> | void;
|
||||
dispose(): Promise<void> | void;
|
||||
}
|
||||
26
packages/channel/src/channel-ctx.ts
Normal file
26
packages/channel/src/channel-ctx.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { Channel } from './channel';
|
||||
import type { ChannelKind } from './channel-interface';
|
||||
|
||||
export interface ChannelCtx {
|
||||
readonly uin: string;
|
||||
readonly kind: ChannelKind;
|
||||
readonly sendRawPacket: (
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
) => Promise<SendPacketResult>;
|
||||
readonly onPacket: (handler: ((pkt: PacketInfo) => void) | null) => void;
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
export function makeChannelCtx(channel: Channel): ChannelCtx {
|
||||
return {
|
||||
uin: channel.uin,
|
||||
kind: channel.kind,
|
||||
sendRawPacket: (cmd, body, timeoutMs) => channel.sendRawPacket(cmd, body, timeoutMs),
|
||||
onPacket: (handler) => channel.setPacketHandler(handler),
|
||||
dispose: () => channel.dispose(),
|
||||
};
|
||||
}
|
||||
73
packages/channel/src/channel-interface.ts
Normal file
73
packages/channel/src/channel-interface.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
|
||||
/**
|
||||
* Discriminator for the two channel transport implementations:
|
||||
*
|
||||
* - `'inject'` — backed by an in-process NTQQ hook (one or more
|
||||
* QQ.exe processes injected with the SnowLuma DLL,
|
||||
* talking over named pipes). Implemented by
|
||||
* `HookChannel` in `@snowluma/channel-hook`.
|
||||
* - `'socket'` — backed by a direct protocol client (no QQ.exe, no
|
||||
* hook). Reserved for the future pure-protocol
|
||||
* runtime; `SocketChannel` is a stub until then.
|
||||
*
|
||||
* Mirrored on `CoreCtx.kind` so account-level consumers can branch on
|
||||
* transport without `instanceof` checks against a concrete subclass
|
||||
* (diagnostics, kind-specific WebUI panels, …).
|
||||
*/
|
||||
export type ChannelKind = 'inject' | 'socket';
|
||||
|
||||
/**
|
||||
* `ChannelInterface` — **strictly transport**. A channel owns one
|
||||
* wire-level connection to QQ for a given UIN: it sends opaque packets
|
||||
* out and surfaces received packets to whoever subscribed via
|
||||
* `setPacketHandler`.
|
||||
*
|
||||
* It deliberately knows nothing about identity caches, the event bus,
|
||||
* the api hub, or the cmd-dispatch pipeline — that machinery lives on
|
||||
* the `Core` layer (`@snowluma/core`) which wraps a `Channel` (via a
|
||||
* `ChannelCtx` capability POJO) to expose a business-level API to
|
||||
* OneBot and friends.
|
||||
*
|
||||
* Direct consumers are limited to:
|
||||
* - `ChannelAdapter` implementations (they create / dispose channels
|
||||
* and pump received packets through `deliverPacket`),
|
||||
* - `Hub` in `@snowluma/core` (the only place that turns a `Channel`
|
||||
* into a `ChannelCtx` and hands the ctx to `Core`),
|
||||
* - `Core` (only via the `ChannelCtx` projection; never holds a
|
||||
* Channel reference directly).
|
||||
*
|
||||
* OneBot and api modules NEVER import `ChannelInterface`; they consume
|
||||
* `CoreCtx` from `@snowluma/core`.
|
||||
*/
|
||||
export interface ChannelInterface {
|
||||
/** Transport family backing this channel. */
|
||||
readonly kind: ChannelKind;
|
||||
/** Stable, unique-per-live-channel id inside the `Hub`
|
||||
* (e.g. `'inject:3161592748'`). */
|
||||
readonly id: string;
|
||||
/** QQ number this transport carries. */
|
||||
readonly uin: string;
|
||||
|
||||
/** Wire-level send. The only escape hatch the apis layer eventually
|
||||
* routes through (via `Core.sendRawPacket` → `ChannelCtx.sendRawPacket`). */
|
||||
sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult>;
|
||||
|
||||
/** Subscribe to inbound packets. Called once by `Hub` (via
|
||||
* `ChannelCtx.onPacket`) when a `Core` is constructed on top of this
|
||||
* channel. Passing `null` detaches. */
|
||||
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void;
|
||||
|
||||
/** Adapter-side hook: feed a freshly-received packet into the
|
||||
* current subscriber (if any). Called by `ChannelAdapter`s when
|
||||
* their underlying runtime delivers a frame. */
|
||||
deliverPacket(pkt: PacketInfo): void;
|
||||
|
||||
/** Release transport-side resources. Idempotent. */
|
||||
dispose(): void;
|
||||
}
|
||||
34
packages/channel/src/channel.ts
Normal file
34
packages/channel/src/channel.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { ChannelInterface, ChannelKind } from './channel-interface';
|
||||
|
||||
export abstract class Channel implements ChannelInterface {
|
||||
abstract readonly kind: ChannelKind;
|
||||
abstract readonly id: string;
|
||||
abstract readonly uin: string;
|
||||
|
||||
abstract sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult>;
|
||||
|
||||
private packetHandler_: ((pkt: PacketInfo) => void) | null = null;
|
||||
private disposed_ = false;
|
||||
|
||||
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void {
|
||||
this.packetHandler_ = handler;
|
||||
}
|
||||
|
||||
deliverPacket(pkt: PacketInfo): void {
|
||||
this.packetHandler_?.(pkt);
|
||||
}
|
||||
|
||||
get isDisposed(): boolean { return this.disposed_; }
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed_) return;
|
||||
this.disposed_ = true;
|
||||
this.packetHandler_ = null;
|
||||
}
|
||||
}
|
||||
0
packages/channel/src/hub-events.ts
Normal file
0
packages/channel/src/hub-events.ts
Normal file
5
packages/channel/src/index.ts
Normal file
5
packages/channel/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { type ChannelAdapter, type ChannelAdapterHost } from './adapter';
|
||||
export { Channel } from './channel';
|
||||
export { makeChannelCtx, type ChannelCtx } from './channel-ctx';
|
||||
export { type ChannelInterface, type ChannelKind } from './channel-interface';
|
||||
|
||||
16
packages/channel/tsconfig.json
Normal file
16
packages/channel/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
8
packages/channel/vitest.config.ts
Normal file
8
packages/channel/vitest.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
54
packages/common/package.json
Normal file
54
packages/common/package.json
Normal file
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./logger": {
|
||||
"types": "./src/logger.ts",
|
||||
"default": "./src/logger.ts"
|
||||
},
|
||||
"./hex": {
|
||||
"types": "./src/hex.ts",
|
||||
"default": "./src/hex.ts"
|
||||
},
|
||||
"./json": {
|
||||
"types": "./src/json.ts",
|
||||
"default": "./src/json.ts"
|
||||
},
|
||||
"./log-file-transport": {
|
||||
"types": "./src/log-file-transport.ts",
|
||||
"default": "./src/log-file-transport.ts"
|
||||
},
|
||||
"./log-summary": {
|
||||
"types": "./src/log-summary.ts",
|
||||
"default": "./src/log-summary.ts"
|
||||
},
|
||||
"./packet-sender": {
|
||||
"types": "./src/packet-sender.ts",
|
||||
"default": "./src/packet-sender.ts"
|
||||
},
|
||||
"./protocol-types": {
|
||||
"types": "./src/protocol-types.ts",
|
||||
"default": "./src/protocol-types.ts"
|
||||
},
|
||||
"./runtime": {
|
||||
"types": "./src/runtime.ts",
|
||||
"default": "./src/runtime.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
6
packages/common/src/json.ts
Normal file
6
packages/common/src/json.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
export type JsonArray = JsonValue[];
|
||||
@@ -1,21 +1,3 @@
|
||||
// File transport for the SnowLuma logger.
|
||||
//
|
||||
// Writes plain text (ANSI stripped) to:
|
||||
// <SNOWLUMA_LOG_DIR>/snowluma-YYYY-MM-DD.log (shared, all UINs)
|
||||
// <SNOWLUMA_LOG_DIR>/<uin>/snowluma-YYYY-MM-DD.log (per-account)
|
||||
//
|
||||
// Both pathways use the same daily rotation + per-file size cap. When the
|
||||
// cap is hit the in-flight file is closed and writes continue in
|
||||
// snowluma-YYYY-MM-DD.1.log, .2.log, ...
|
||||
// at the same date. Files older than the retain window are unlinked on
|
||||
// startup and on each day rollover.
|
||||
//
|
||||
// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally
|
||||
// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O
|
||||
// failure during init or write degrades silently to console-only — we
|
||||
// deliberately do NOT use the logger from inside this module to avoid
|
||||
// recursion.
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
@@ -81,7 +63,6 @@ class FileWriter {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
@@ -170,12 +151,10 @@ class FileWriter {
|
||||
}
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`[logger] file write error on ${p}: ${err.message}`);
|
||||
});
|
||||
return { stream, bytes, date, splitIndex, path: p };
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
@@ -1,12 +1,3 @@
|
||||
// Compact one-line param summary for log output.
|
||||
//
|
||||
// OneBot action params can include large message arrays / nested
|
||||
// payloads that would blow the line width to multiple kilobytes if we
|
||||
// JSON.stringify them naively. This helper produces a flat
|
||||
// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard
|
||||
// total cap, designed to be grep-friendly without flooding the log
|
||||
// file.
|
||||
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
|
||||
@@ -23,9 +23,6 @@ interface LogOptions {
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Fixed-width slot for the UIN tag in rendered output so the [Scope]
|
||||
// column stays vertically aligned across lines with and without a UIN.
|
||||
// Width covers `[1234567890]` (12 chars); anything longer just won't pad.
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
@@ -205,7 +202,7 @@ export interface Logger {
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
|
||||
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
@@ -8,9 +8,4 @@ export interface PacketInfo {
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Packet sink injected into HookSession / HookManager. The default
|
||||
* wiring forwards to BridgeManager.onPacket, but tests inject spies.
|
||||
*/
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
13
packages/common/tsconfig.json
Normal file
13
packages/common/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -1,10 +1,36 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.8.4",
|
||||
"version": "1.9.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "../../dist/index.mjs",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "../../dist/index.mjs"
|
||||
},
|
||||
"./core": {
|
||||
"types": "./src/core.ts",
|
||||
"default": "./src/core.ts"
|
||||
},
|
||||
"./core-context": {
|
||||
"types": "./src/core-context.ts",
|
||||
"default": "./src/core-context.ts"
|
||||
},
|
||||
"./core-ctx": {
|
||||
"types": "./src/core-ctx.ts",
|
||||
"default": "./src/core-ctx.ts"
|
||||
},
|
||||
"./hub": {
|
||||
"types": "./src/hub.ts",
|
||||
"default": "./src/hub.ts"
|
||||
},
|
||||
"./apis": {
|
||||
"types": "./src/apis/index.ts",
|
||||
"default": "./src/apis/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"build:all": "cross-env BUILD_WEBUI=true vite build",
|
||||
@@ -14,6 +40,14 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/channel-hook": "workspace:*",
|
||||
"@snowluma/channel-socket": "workspace:*",
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -21,7 +55,7 @@
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.14",
|
||||
"hono": "^4.12.18",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
233
packages/core/src/apis/contacts.ts
Normal file
233
packages/core/src/apis/contacts.ts
Normal file
@@ -0,0 +1,233 @@
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
/**
|
||||
* One row of an `OidbSvcTrpcTcp.0x9067_202` (download rkey) response.
|
||||
* Cached for the duration of `ttlSeconds` and consumed by the OneBot
|
||||
* media-URL resolver / message converter when a download URL must be
|
||||
* minted on the fly. Lives at the apis layer (not on `Bridge`) because
|
||||
* only `apis.contacts.fetchDownloadRKeys` materialises these rows.
|
||||
*/
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
storeId: number;
|
||||
createTime: number;
|
||||
type: number;
|
||||
}
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
type FriendPropertySource = {
|
||||
additional?: Array<{
|
||||
type?: number;
|
||||
layer1?: {
|
||||
properties?: Array<{
|
||||
code?: number;
|
||||
value?: string;
|
||||
}>;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
|
||||
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
for (const additional of raw.additional ?? []) {
|
||||
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
|
||||
for (const property of additional.layer1.properties ?? []) {
|
||||
props.set(property.code ?? 0, property.value ?? '');
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
export function permissionToRole(permission: number): string {
|
||||
switch (permission) {
|
||||
case 1: return 'owner';
|
||||
case 2: return 'admin';
|
||||
default: return 'member';
|
||||
}
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
|
||||
* Keyed by groupId, lives for the lifetime of the Bridge.
|
||||
*
|
||||
* Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
* `get_group_member_info` once per inbound message) triggers one
|
||||
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
|
||||
* Tencent risk-control and gets the account banned for 7 days.
|
||||
*/
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
do {
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
|
||||
for (const raw of resp.friends ?? []) {
|
||||
const props = buildFriendProperties(raw);
|
||||
friends.push({
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
});
|
||||
}
|
||||
nextUin = resp.next?.uin ?? null;
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const resp = await FetchGroupList.invoke(this.ctx);
|
||||
const groups: QQGroupInfo[] = [];
|
||||
for (const raw of resp.groups ?? []) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
async fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch.get(groupId);
|
||||
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight.get(groupId);
|
||||
if (inflight) return inflight;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const data = await this.fetchGroupMemberListUncached(groupId);
|
||||
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
|
||||
return data;
|
||||
} finally {
|
||||
this.memberListInflight.delete(groupId);
|
||||
}
|
||||
})();
|
||||
this.memberListInflight.set(groupId, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
do {
|
||||
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
for (const raw of resp.members ?? []) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
});
|
||||
}
|
||||
token = resp.token ?? '';
|
||||
} while (token);
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfile.invoke(this.ctx, { uin });
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Look up a user profile by UID (string form). Used for strangers
|
||||
* whose UIN we don't have yet — typically the requester on a
|
||||
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
|
||||
* .Create(targetUid)` path. */
|
||||
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
|
||||
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
for (const raw of resp.requests ?? []) {
|
||||
requests.push({
|
||||
groupId: raw.group?.groupUin ?? 0,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid: raw.target?.uid ?? '',
|
||||
targetUin: 0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid: raw.invitor?.uid ?? '',
|
||||
invitorUin: 0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid: raw.operatorUser?.uid ?? '',
|
||||
operatorUin: 0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence: Number(raw.sequence ?? 0),
|
||||
state: raw.state ?? 0,
|
||||
eventType: raw.eventType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
for (const entry of resp.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
if (rkey && type) {
|
||||
result.push({
|
||||
rkey,
|
||||
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
|
||||
storeId: entry.storeId ?? 0,
|
||||
createTime: entry.rkeyCreateTime ?? 0,
|
||||
type,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
91
packages/core/src/apis/extras.ts
Normal file
91
packages/core/src/apis/extras.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
|
||||
import {
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import type { CoreContext } from '../core-context';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
|
||||
export const AiVoiceChatType = {
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
} as const;
|
||||
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
|
||||
|
||||
export type AiVoiceCategory = NamespaceAiVoiceCategory;
|
||||
export interface AiVoiceItem {
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
export class ExtrasApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
}
|
||||
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
|
||||
}
|
||||
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Returns `null` on transport / decode failure rather than throwing,
|
||||
* so the OneBot action can produce a clean retcode without try/catch
|
||||
* gymnastics. Namespace throws on transport failure → swallow here.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
return await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
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 node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
|
||||
if (node) return node as MediaIndexNode;
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
}
|
||||
560
packages/core/src/apis/forward.ts
Normal file
560
packages/core/src/apis/forward.ts
Normal file
@@ -0,0 +1,560 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type {
|
||||
LongMsgResult,
|
||||
RecvLongMsgReq,
|
||||
RecvLongMsgResp,
|
||||
SendLongMsgReq,
|
||||
SendLongMsgResp,
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
|
||||
import { parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { gunzipSync, gzipSync } from 'zlib';
|
||||
import type { CoreContext } from '../core-context';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
|
||||
// of the process — that's enough because OneBot clients typically
|
||||
// resolve a forward immediately after receiving the parent message.
|
||||
const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
|
||||
// Per-layer piggyback entry. Each level of a nested forward attaches
|
||||
// its own msgBody under a uuid `actionCommand`, so when the receiver
|
||||
// fetches the outermost res_id it gets every layer in one shot
|
||||
// (modelled on NapCat's `uploadForwardedNodesPacket` — see
|
||||
// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2
|
||||
// both ship a single-action model and silently break when the
|
||||
// recipient is a NapCat instance trying to walk the tree.
|
||||
interface ForwardInnerAction {
|
||||
uuid: string;
|
||||
msgBody: PushMsgBody[];
|
||||
}
|
||||
|
||||
interface ForwardUploadResult {
|
||||
resId: string;
|
||||
// The current level's msgBody + uuid — what an outer caller would
|
||||
// piggyback to expose this layer through the tree.
|
||||
msgBody: PushMsgBody[];
|
||||
uuid: string;
|
||||
// All accumulated piggyback entries from deeper levels. Outer
|
||||
// callers concatenate these to their own actions list so the
|
||||
// outermost upload carries the full tree.
|
||||
innerActions: ForwardInnerAction[];
|
||||
}
|
||||
|
||||
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
|
||||
// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`.
|
||||
function hexToBytesLocal(hex: string): Uint8Array {
|
||||
const s = hex.trim();
|
||||
if (!s) return new Uint8Array(0);
|
||||
const len = s.length >> 1;
|
||||
const out = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
out[i] = parseInt(s.substr(i * 2, 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function buildForwardPushBody(
|
||||
bridge: BridgeContext,
|
||||
node: ForwardNodePayload,
|
||||
groupId?: number,
|
||||
userUid?: string,
|
||||
): Promise<PushMsgBody> {
|
||||
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);
|
||||
// image/record/video upload inside a forward node must be scoped to the
|
||||
// forward's recipient: group → groupId, private → recipient uid.
|
||||
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
|
||||
// element builder throws "private image target uid is missing".
|
||||
//
|
||||
// `forwardFake: true` keeps `{type:'file'}` segments in the
|
||||
// long-msg payload: group → emitted as transElem(24) in elems[],
|
||||
// c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }).
|
||||
// The QQ-NT live-send pipeline would reject these (transElem(24) →
|
||||
// result=79; notOnlineFile via PbSendMsg doesn't render), but the
|
||||
// long-msg upload service stores the bytes verbatim and the
|
||||
// receiver decodes them through the normal msg-push path.
|
||||
const sendCtx = groupId !== undefined
|
||||
? { bridge, groupId, forwardFake: true }
|
||||
: userUid
|
||||
? { bridge, userUid, forwardFake: true }
|
||||
: { bridge, forwardFake: true };
|
||||
const elems = await buildSendElems(node.elements, sendCtx);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
|
||||
const seq = Math.floor(Math.random() * 9000000) + 1000000;
|
||||
|
||||
// c2c-file in a forward node — element-builder intentionally skips
|
||||
// it (RichText.notOnlineFile + msgContent live outside elems[]). For
|
||||
// forward fake-send we mirror what an inbound c2c file message looks
|
||||
// like on the wire: serialise the FileExtra blob and ride it on
|
||||
// `body.msgContent`. The receiver's rich-body-decoder reads from
|
||||
// `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so
|
||||
// the bubble renders with the right file name + size when the
|
||||
// forward is expanded. Only the FIRST c2c file in a node ships —
|
||||
// QQ NT's bubble can only carry one msgContent payload, same as
|
||||
// a live c2c send. Group nodes ignore this branch entirely (the
|
||||
// transElem(24) elems[] entry above covers them).
|
||||
let msgContent: Uint8Array | undefined;
|
||||
if (groupId === undefined) {
|
||||
const fileEl = node.elements.find(e => e.type === 'file' && e.fileId);
|
||||
if (fileEl) {
|
||||
// Honour inline segment fields first; fall back to the upload
|
||||
// metadata cache (populated by upload_private_file). Without
|
||||
// size/md5 the receiver would render "0 B" so prefer recovering
|
||||
// them — see same logic in modules/message-actions.ts.
|
||||
const cached = bridge.recallUploadedFile(fileEl.fileId ?? '');
|
||||
const fileMd5 = fileEl.md5Hex
|
||||
? hexToBytesLocal(fileEl.md5Hex)
|
||||
: (cached?.fileMd5 ?? new Uint8Array(0));
|
||||
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
|
||||
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
|
||||
const fileHash = fileEl.fileHash ?? cached?.fileHash ?? '';
|
||||
const sevenDays = 7 * 24 * 60 * 60;
|
||||
msgContent = protobuf_encode<FileExtra>({
|
||||
file: {
|
||||
fileType: 0,
|
||||
fileUuid: fileEl.fileId!,
|
||||
fileMd5,
|
||||
fileName,
|
||||
fileSize: BigInt(fileSize),
|
||||
subcmd: 1,
|
||||
dangerEvel: 0,
|
||||
expireTime: now + sevenDays,
|
||||
fileHash,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin,
|
||||
toUid: bridge.identity.selfUid ?? '',
|
||||
forward: {
|
||||
friendName: nickname,
|
||||
},
|
||||
},
|
||||
contentHead: {
|
||||
msgType: 9,
|
||||
subType: 4,
|
||||
msgId: random,
|
||||
sequence: seq,
|
||||
timestamp: now,
|
||||
divSeq: 0,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
elems,
|
||||
},
|
||||
...(msgContent ? { msgContent } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Inner forward preview metadata — kept minimal here (the OneBot
|
||||
// `parseForwardNodes` caller can override these on the top-level
|
||||
// node by passing custom forwardSource/forwardSummary on the
|
||||
// non-nested send path; nested levels just get sensible defaults
|
||||
// since they're synthesised by us and never reach OneBot input).
|
||||
function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string {
|
||||
const nicks: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const node of innerNodes) {
|
||||
const name = (node.nickname ?? '').trim();
|
||||
if (name && !seen.has(name)) {
|
||||
seen.add(name);
|
||||
nicks.push(name);
|
||||
}
|
||||
if (nicks.length >= 4) break;
|
||||
}
|
||||
if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
|
||||
return `${nicks.join('和')}的聊天记录`;
|
||||
}
|
||||
|
||||
function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
|
||||
return innerNodes.slice(0, 4).map(node => {
|
||||
const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户');
|
||||
const previewText = previewFromElements(node.elements);
|
||||
return { text: previewText ? `${name}: ${previewText}` : name };
|
||||
});
|
||||
}
|
||||
|
||||
function previewFromElements(elements: MessageElement[]): string {
|
||||
for (const elem of elements) {
|
||||
if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30);
|
||||
if (elem.type === 'image') return '[图片]';
|
||||
if (elem.type === 'record') return '[语音]';
|
||||
if (elem.type === 'video') return '[视频]';
|
||||
if (elem.type === 'file') return '[文件]';
|
||||
if (elem.type === 'forward') return '[聊天记录]';
|
||||
if (elem.type === 'face') return '[表情]';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
return resId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive upload with NapCat-style piggyback. Each invocation:
|
||||
* 1. Walks `nodes`. For any node whose `innerForward` is set,
|
||||
* recursively uploads that inner chain first (which itself runs
|
||||
* this same recursion).
|
||||
* 2. Replaces the node's `elements` with an ARK preview pointing at
|
||||
* the inner res_id (and inner uuid for receiver-side walking).
|
||||
* 3. Accumulates the inner level's `{uuid, msgBody}` plus all of
|
||||
* ITS accumulated `innerActions` into this level's piggyback list.
|
||||
* 4. Encodes this level's long-msg payload as
|
||||
* `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it,
|
||||
* returns `{resId, msgBody, uuid, innerActions}` so an outer
|
||||
* caller can keep piggybacking up the tree.
|
||||
*/
|
||||
private async uploadRecursive(
|
||||
nodes: ForwardNodePayload[],
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<ForwardUploadResult> {
|
||||
if (!Array.isArray(nodes) || nodes.length === 0) {
|
||||
throw new Error('forward nodes are required');
|
||||
}
|
||||
|
||||
const bridge = this.ctx;
|
||||
|
||||
// For a private forward to `userId`, any image/record/video inside a node
|
||||
// needs the recipient's uid as upload scene. Resolve it once up-front,
|
||||
// and only when at least one node actually contains media (saves an RPC
|
||||
// for text-only forwards). Also need it when a node is itself a nested
|
||||
// forward — the inner upload uses the same scene.
|
||||
let userUid: string | undefined;
|
||||
if (groupId === undefined && userId !== undefined && userId > 0) {
|
||||
const needsUid = nodes.some(node => !!node.innerForward
|
||||
|| node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'));
|
||||
if (needsUid) {
|
||||
const resolved = await this.ctx.resolveUserUid(userId);
|
||||
if (resolved) userUid = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
// Walk nodes and resolve nested forwards first (so we know their
|
||||
// res_id / uuid before encoding the outer ARK previews). Build
|
||||
// `processedNodes` with elements rewritten for nested layers,
|
||||
// and collect every inner level's piggyback in `myInnerActions`.
|
||||
//
|
||||
// CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the
|
||||
// outer's preview element as `forwardUuid` AND used as the
|
||||
// `actionCommand` for the outer's piggyback entry. That's the
|
||||
// alignment the QQ-NT receiver uses to find the inner layer
|
||||
// inside the outer's LongMsgResult without a second server fetch
|
||||
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
|
||||
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
|
||||
const myInnerActions: ForwardInnerAction[] = [];
|
||||
const processedNodes: ForwardNodePayload[] = [];
|
||||
const isGroup = groupId !== undefined;
|
||||
for (const node of nodes) {
|
||||
if (node.innerForward && node.innerForward.length > 0) {
|
||||
const inner = await this.uploadRecursive(node.innerForward, groupId, userId);
|
||||
// NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}`
|
||||
// + the entire `inner.innerPacketMsg` array up to its caller. We
|
||||
// mirror that — `inner.uuid` indexes the inner level itself,
|
||||
// and `inner.innerActions` already contains deeper layers.
|
||||
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
|
||||
myInnerActions.push(...inner.innerActions);
|
||||
// Replace the inner placeholder element with a forward preview
|
||||
// pointing at the inner res_id. `forwardUuid: inner.uuid`
|
||||
// baked into the LightApp JSON's `meta.detail.uniseq` is what
|
||||
// closes the loop with our piggyback action above.
|
||||
const previewElement: MessageElement = {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
forwardUuid: inner.uuid,
|
||||
forwardSource: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: '[聊天记录]',
|
||||
forwardNews: previewLinesFromNodes(node.innerForward),
|
||||
forwardTSum: node.innerForward.length,
|
||||
};
|
||||
processedNodes.push({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [previewElement],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
});
|
||||
} else {
|
||||
processedNodes.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
// Encode this level's msgBody.
|
||||
const msgBody = await Promise.all(processedNodes.map(
|
||||
node => buildForwardPushBody(bridge, node, groupId, userUid),
|
||||
));
|
||||
|
||||
// Compose the action list: own MultiMsg + piggybacked inner actions.
|
||||
const longMsgResult = protobuf_encode<LongMsgResult>({
|
||||
action: [
|
||||
{ actionCommand: 'MultiMsg', actionData: { msgBody } },
|
||||
...myInnerActions.map(a => ({
|
||||
actionCommand: a.uuid,
|
||||
actionData: { msgBody: a.msgBody },
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const info: SendLongMsgReq['info'] = {
|
||||
type: groupId ? 3 : 1,
|
||||
uid: { uid: groupId ? String(groupId) : selfUid },
|
||||
payload: gzipSync(Buffer.from(longMsgResult)),
|
||||
};
|
||||
if (groupId) info.groupUin = groupId;
|
||||
|
||||
const request = protobuf_encode<SendLongMsgReq>({
|
||||
info,
|
||||
settings: {
|
||||
field1: 4,
|
||||
field2: 1,
|
||||
field3: 7,
|
||||
field4: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'upload forward message failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<SendLongMsgResp>(result.responseData);
|
||||
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
|
||||
if (!resId) {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, processedNodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId ?? groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
|
||||
})));
|
||||
|
||||
return {
|
||||
resId,
|
||||
msgBody,
|
||||
// UUID generated here so the OUTER caller can use it as both
|
||||
// (1) the `actionCommand` for its piggyback entry carrying our
|
||||
// msgBody, and
|
||||
// (2) the `forwardUuid` baked into its forward-preview element
|
||||
// pointing at our resId.
|
||||
// Receivers walking the outer's LongMsgResult find the inner
|
||||
// layer by matching `uniseq` from (2) against `actionCommand`
|
||||
// from (1) — no separate fetch needed.
|
||||
uuid: randomUUID(),
|
||||
innerActions: myInnerActions,
|
||||
};
|
||||
}
|
||||
|
||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||
const bridge = this.ctx;
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
return cached.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
}
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const request = protobuf_encode<RecvLongMsgReq>({
|
||||
info: {
|
||||
uid: { uid: selfUid },
|
||||
resId,
|
||||
acquire: true,
|
||||
},
|
||||
settings: {
|
||||
field1: 2,
|
||||
field2: 0,
|
||||
field3: 0,
|
||||
field4: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'download forward message failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<RecvLongMsgResp>(result.responseData);
|
||||
const payload = resp?.result?.payload;
|
||||
if (!(payload instanceof Uint8Array) || payload.length === 0) {
|
||||
throw new Error('download forward message payload is empty');
|
||||
}
|
||||
|
||||
const inflate = gunzipSync(Buffer.from(payload));
|
||||
const longMsg = protobuf_decode<LongMsgResult>(inflate);
|
||||
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
|
||||
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
|
||||
|
||||
// Piggyback index: any non-`MultiMsg` action carries an inner
|
||||
// layer keyed by the uuid the sender baked into its forward
|
||||
// preview's `uniseq`. Build a lookup so we can resolve inner
|
||||
// forwards (via their uniseq → inner msgBody) without a second
|
||||
// server roundtrip — matches the sender-side piggyback emitted in
|
||||
// `uploadRecursive` above.
|
||||
const piggybackByUuid = new Map<string, PushMsgBody[]>();
|
||||
for (const action of actions) {
|
||||
const cmd = action?.actionCommand;
|
||||
if (!cmd || cmd === 'MultiMsg') continue;
|
||||
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
piggybackByUuid.set(cmd, body);
|
||||
}
|
||||
|
||||
const nodes = this.decodeMsgBodiesToNodes(msgBodyList);
|
||||
|
||||
// Walk the decoded outer nodes for inner-forward previews
|
||||
// (`type: 'forward', forwardUuid: <uniseq>`). For each, pull the
|
||||
// matching piggyback body, decode it into inner nodes, and seed
|
||||
// the cache by the inner resId so a follow-up `fetch(innerResId)`
|
||||
// hits the cache instead of the wire.
|
||||
if (piggybackByUuid.size > 0) {
|
||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
||||
}
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** Walk a list of PushMsgBody, run each through the regular msg-push
|
||||
* pipeline, and shape the result into ForwardNodePayloads. Extracted
|
||||
* so both the outer + piggyback decode paths share one implementation. */
|
||||
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
|
||||
const out: ForwardNodePayload[] = [];
|
||||
for (const msgBody of msgBodyList) {
|
||||
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
|
||||
const pkt: PacketInfo = {
|
||||
pid: 0,
|
||||
uin: this.ctx.identity.uin,
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 0,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: wrapped,
|
||||
};
|
||||
const events = parseMsgPush(pkt, this.ctx.identity);
|
||||
const event = events.find(e =>
|
||||
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
|
||||
if (!event) continue;
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderCard || event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgId: event.msgId,
|
||||
msgSeq: event.msgSeq,
|
||||
groupId: event.groupId,
|
||||
senderCard: event.senderCard,
|
||||
messageType: 'group',
|
||||
});
|
||||
} else if (event.kind === 'friend_message') {
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgId: event.msgId,
|
||||
msgSeq: event.msgSeq,
|
||||
messageType: 'private',
|
||||
});
|
||||
} else {
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgSeq: event.msgSeq,
|
||||
groupId: event.groupId,
|
||||
messageType: 'private',
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Recursively resolve forward previews against the piggyback table.
|
||||
* For every `{type: 'forward', resId, forwardUuid}` element we find,
|
||||
* look up the uniseq in the piggyback map; if hit, decode the
|
||||
* inner msgBody and cache it by inner resId, then descend into that
|
||||
* inner layer to resolve deeper nestings carried in the SAME
|
||||
* piggyback set (NapCat hoists the entire tree's piggybacks onto
|
||||
* the outermost action list). */
|
||||
private consumePiggybacks(
|
||||
nodes: ForwardNodePayload[],
|
||||
piggybackByUuid: Map<string, PushMsgBody[]>,
|
||||
): void {
|
||||
const seen = new Set<string>();
|
||||
const visit = (chain: ForwardNodePayload[]): void => {
|
||||
for (const node of chain) {
|
||||
for (const elem of node.elements) {
|
||||
if (elem.type !== 'forward') continue;
|
||||
const uuid = elem.forwardUuid;
|
||||
const innerResId = elem.resId;
|
||||
if (!uuid || !innerResId || seen.has(uuid)) continue;
|
||||
const body = piggybackByUuid.get(uuid);
|
||||
if (!body) continue;
|
||||
seen.add(uuid);
|
||||
const innerNodes = this.decodeMsgBodiesToNodes(body);
|
||||
forwardResCache.set(innerResId, cloneNodes(innerNodes));
|
||||
visit(innerNodes);
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(nodes);
|
||||
}
|
||||
}
|
||||
|
||||
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
|
||||
return nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
}
|
||||
29
packages/core/src/apis/friend.ts
Normal file
29
packages/core/src/apis/friend.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
|
||||
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
* pre-resolved UID string or a numeric uin (then resolved on the fly).
|
||||
*/
|
||||
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
|
||||
}
|
||||
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
// Refresh friend cache after deletion so subsequent reads don't
|
||||
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
|
||||
// shouldn't make the delete itself look failed.
|
||||
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
setRemark(userId: number, remark: string): Promise<void> {
|
||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
}
|
||||
87
packages/core/src/apis/group-admin.ts
Normal file
87
packages/core/src/apis/group-admin.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
|
||||
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
|
||||
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
|
||||
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
|
||||
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
|
||||
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
|
||||
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
|
||||
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
|
||||
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
|
||||
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
|
||||
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
|
||||
muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
|
||||
setAddOption(groupId: number, addType: number): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType });
|
||||
}
|
||||
|
||||
setSearch(groupId: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
|
||||
}
|
||||
|
||||
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
leave(groupId: number): Promise<void> {
|
||||
return LeaveGroup.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
|
||||
setName(groupId: number, name: string): Promise<void> {
|
||||
return SetGroupName.invoke(this.ctx, { groupId, name });
|
||||
}
|
||||
|
||||
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot's local-only label for a group. Lives here rather than
|
||||
* `FriendApi` because the semantic is "operate on a group" rather
|
||||
* than "operate on a contact list".
|
||||
*/
|
||||
setRemark(groupId: number, remark: string): Promise<void> {
|
||||
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
|
||||
}
|
||||
|
||||
getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
return GetAtAllRemain.invoke(this.ctx, { groupId });
|
||||
}
|
||||
}
|
||||
279
packages/core/src/apis/group-album.ts
Normal file
279
packages/core/src/apis/group-album.ts
Normal file
@@ -0,0 +1,279 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import type {
|
||||
DeleteMediasRequest,
|
||||
DeleteMediasResponse,
|
||||
DoQunCommentRequest,
|
||||
DoQunCommentResponse,
|
||||
DoQunLikeRequest,
|
||||
DoQunLikeResponse,
|
||||
GetMediaListRequest,
|
||||
GetMediaListResponse,
|
||||
MediaInfo,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
|
||||
function convertBigIntToString(obj: unknown): JsonValue {
|
||||
if (obj === null || obj === undefined) return null;
|
||||
if (typeof obj === 'bigint') return obj.toString();
|
||||
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
|
||||
if (typeof obj === 'object') {
|
||||
const result: JsonObject = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = convertBigIntToString(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj;
|
||||
return null;
|
||||
}
|
||||
|
||||
export class GroupAlbumApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
|
||||
async list(groupId: number): Promise<GroupAlbumList> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
|
||||
return albumData?.album || [];
|
||||
}
|
||||
|
||||
// 上传图片到现有相册(HTTP 分片上传)。
|
||||
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
|
||||
}
|
||||
|
||||
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const body = protobuf_encode<GetMediaListRequest>({
|
||||
field1: 0,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
reqInfo: {
|
||||
groupId: groupId.toString(),
|
||||
albumId,
|
||||
field3: 0,
|
||||
attachInfo,
|
||||
field5: '',
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to get album media list');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
|
||||
|
||||
if (resp.field1 !== 0) {
|
||||
throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
const data = resp.data ?? {};
|
||||
const mediaList = data.mediaList ?? [];
|
||||
const nextAttachInfo = data.nextAttachInfo ?? '';
|
||||
|
||||
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
|
||||
}
|
||||
|
||||
async comment(groupId: number, albumId: string, lloc: string, content: string): Promise<GroupAlbumCommentResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const clientKey = Date.now().toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
|
||||
const body = protobuf_encode<DoQunCommentRequest>({
|
||||
field1: 8527,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
body: {
|
||||
groupId: groupId.toString(),
|
||||
field3: 2,
|
||||
reqBody: {
|
||||
field1: { field3: 0, field4: '' },
|
||||
field2: {
|
||||
field1: { uin },
|
||||
},
|
||||
field5: {
|
||||
field1: {
|
||||
field2: {
|
||||
field1: 0, field2: '',
|
||||
lloc,
|
||||
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
|
||||
},
|
||||
},
|
||||
albumId,
|
||||
field5: 0,
|
||||
},
|
||||
},
|
||||
field5: {
|
||||
field2: { uin },
|
||||
field3: {
|
||||
field1: 0,
|
||||
field2: content,
|
||||
field3: '', field4: '', field5: 0, field6: '',
|
||||
},
|
||||
clientKey,
|
||||
},
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to comment on album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
|
||||
|
||||
const resCode = resp.field1;
|
||||
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
|
||||
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
const commentData = resp.comment?.data ?? {};
|
||||
|
||||
return convertBigIntToString({
|
||||
id: commentData.id ?? '',
|
||||
user: { uin: commentData.user?.uin ?? '' },
|
||||
content: commentData.content ?? [],
|
||||
time: commentData.time ?? '0',
|
||||
clientKey: commentData.clientKey ?? '',
|
||||
}) as unknown as GroupAlbumCommentResult;
|
||||
}
|
||||
|
||||
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<JsonValue> {
|
||||
const uin = this.ctx.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const type = isLike ? 2 : 1;
|
||||
const status = isLike ? 0 : 1;
|
||||
|
||||
let id = '';
|
||||
if (lloc) {
|
||||
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
|
||||
} else {
|
||||
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
|
||||
}
|
||||
|
||||
const body = protobuf_encode<DoQunLikeRequest>({
|
||||
field1: 5495,
|
||||
field2: 'h5_test',
|
||||
field3: 'h5_test',
|
||||
body: {
|
||||
type,
|
||||
like: { id, status },
|
||||
publish: {
|
||||
cellCommon: {
|
||||
time: BigInt(Date.now()),
|
||||
feedId: `422_0_${batchId}`,
|
||||
},
|
||||
cellUserInfo: {
|
||||
user: { uin },
|
||||
},
|
||||
cellMedia: {
|
||||
albumId,
|
||||
batchId: BigInt(batchId),
|
||||
},
|
||||
cellQunInfo: {
|
||||
qunId: groupId.toString(),
|
||||
},
|
||||
},
|
||||
clientKey,
|
||||
},
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to like album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DoQunLikeResponse>(result.responseData);
|
||||
const resCode = resp.field1;
|
||||
|
||||
if (resCode !== 5495) {
|
||||
throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
return convertBigIntToString(resp.body?.like ?? {});
|
||||
}
|
||||
|
||||
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
|
||||
const uin = this.ctx.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const body = protobuf_encode<DeleteMediasRequest>({
|
||||
field1: 8694,
|
||||
field2: 'h5_test',
|
||||
field3: 'h5_test',
|
||||
body: {
|
||||
groupId: groupId.toString(),
|
||||
albumId,
|
||||
lloc,
|
||||
},
|
||||
traceId: clientKey,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to delete album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DeleteMediasResponse>(result.responseData);
|
||||
const resCode = resp.field1;
|
||||
const errCode = resp.field2;
|
||||
const errMsg = resp.field3;
|
||||
|
||||
if (resCode !== 8694 || errCode) {
|
||||
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
export interface GroupAlbumMediaResult {
|
||||
mediaList: Array<JsonValue & Partial<MediaInfo>>;
|
||||
nextAttachInfo: string;
|
||||
}
|
||||
|
||||
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
|
||||
|
||||
export interface GroupAlbumCommentResult {
|
||||
id: string;
|
||||
user: { uin: string };
|
||||
content: Array<{ type: number; content: string }>;
|
||||
time: string;
|
||||
clientKey: string;
|
||||
}
|
||||
641
packages/core/src/apis/group-file.ts
Normal file
641
packages/core/src/apis/group-file.ts
Normal file
@@ -0,0 +1,641 @@
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { CoreContext } from '../core-context';
|
||||
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
|
||||
|
||||
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
|
||||
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
|
||||
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
|
||||
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
|
||||
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
|
||||
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
|
||||
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
|
||||
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
|
||||
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
|
||||
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
|
||||
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
|
||||
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
|
||||
|
||||
const log = createLogger('GroupFile');
|
||||
|
||||
// ─────────────── public result types ───────────────
|
||||
|
||||
export interface GroupFileInfo {
|
||||
fileId: string;
|
||||
fileName: string;
|
||||
busId: number;
|
||||
fileSize: number;
|
||||
uploadTime: number;
|
||||
deadTime: number;
|
||||
modifyTime: number;
|
||||
downloadTimes: number;
|
||||
uploader: number;
|
||||
uploaderName: string;
|
||||
}
|
||||
|
||||
export interface GroupFolderInfo {
|
||||
folderId: string;
|
||||
folderName: string;
|
||||
createTime: number;
|
||||
creator: number;
|
||||
creatorName: string;
|
||||
totalFileCount: number;
|
||||
}
|
||||
|
||||
export interface GroupFilesResult {
|
||||
files: GroupFileInfo[];
|
||||
folders: GroupFolderInfo[];
|
||||
}
|
||||
|
||||
export interface UploadFileResult {
|
||||
fileId: string | null;
|
||||
fileHash?: string | null;
|
||||
}
|
||||
|
||||
// Re-export so callers don't have to dig into apis/shared.
|
||||
export type { MediaIndexNode } from './shared';
|
||||
|
||||
// ─────────────── file-specific helpers ───────────────
|
||||
|
||||
function normalizeDirectory(dir?: string): string {
|
||||
if (!dir || !dir.trim()) return '/';
|
||||
return dir;
|
||||
}
|
||||
|
||||
function bytesToHexUpper(data: unknown): string {
|
||||
if (!(data instanceof Uint8Array) || data.length === 0) return '';
|
||||
return toHexUpper(data);
|
||||
}
|
||||
|
||||
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
|
||||
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
|
||||
// same way. Force-unsigned the shift to keep negative ints (high bit set)
|
||||
// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
|
||||
// into a negative number.
|
||||
function int32ToIpv4Dotted(value: number): string {
|
||||
const b1 = value & 0xFF;
|
||||
const b2 = (value >>> 8) & 0xFF;
|
||||
const b3 = (value >>> 16) & 0xFF;
|
||||
const b4 = (value >>> 24) & 0xFF;
|
||||
return `${b1}.${b2}.${b3}.${b4}`;
|
||||
}
|
||||
|
||||
function normalizeUploadFileName(name: string, fallback: string): string {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed) return trimmed;
|
||||
const safeFallback = fallback.trim();
|
||||
return safeFallback || 'file.bin';
|
||||
}
|
||||
|
||||
function md5First10MB(bytes: Uint8Array): Uint8Array {
|
||||
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
|
||||
return computeMd5(bytes.subarray(0, limit));
|
||||
}
|
||||
|
||||
function buildGroupFileUploadExt(
|
||||
senderUin: number,
|
||||
groupId: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
fileId: string,
|
||||
uploadKey: Uint8Array,
|
||||
checkKey: Uint8Array,
|
||||
uploadHost: string,
|
||||
uploadPort: number,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<FileUploadExt>({
|
||||
unknown1: 100,
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: BigInt(groupId),
|
||||
groupCode: BigInt(groupId),
|
||||
},
|
||||
fileEntry: {
|
||||
fileSize: BigInt(Math.max(0, fileSize)),
|
||||
md5,
|
||||
md5S2: md5,
|
||||
checkKey,
|
||||
fileId,
|
||||
uploadKey,
|
||||
},
|
||||
clientInfo: {
|
||||
clientType: 3,
|
||||
appId: '100',
|
||||
terminalType: 3,
|
||||
clientVer: '1.1.1',
|
||||
unknown: 4,
|
||||
},
|
||||
fileNameInfo: {
|
||||
fileName,
|
||||
},
|
||||
host: {
|
||||
hosts: [
|
||||
{
|
||||
url: {
|
||||
host: uploadHost,
|
||||
unknown: 1,
|
||||
},
|
||||
port: uploadPort,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
unknown200: 0,
|
||||
});
|
||||
}
|
||||
|
||||
function buildPrivateFileUploadExt(
|
||||
senderUin: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
sha1: Uint8Array,
|
||||
fileId: string,
|
||||
uploadKey: Uint8Array,
|
||||
uploadHost: string,
|
||||
uploadPort: number,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<FileUploadExt>({
|
||||
unknown1: 100,
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: 0n,
|
||||
groupCode: 0n,
|
||||
},
|
||||
fileEntry: {
|
||||
fileSize: BigInt(Math.max(0, fileSize)),
|
||||
md5,
|
||||
md5S2: md5,
|
||||
checkKey: sha1,
|
||||
fileId,
|
||||
uploadKey,
|
||||
},
|
||||
clientInfo: {
|
||||
clientType: 3,
|
||||
appId: '100',
|
||||
terminalType: 3,
|
||||
clientVer: '1.1.1',
|
||||
unknown: 4,
|
||||
},
|
||||
fileNameInfo: {
|
||||
fileName,
|
||||
},
|
||||
host: {
|
||||
hosts: [
|
||||
{
|
||||
url: {
|
||||
host: uploadHost,
|
||||
unknown: 1,
|
||||
},
|
||||
port: uploadPort,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
unknown3: 0,
|
||||
unknown200: 1,
|
||||
});
|
||||
}
|
||||
|
||||
export class GroupFileApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── publish (group file → chat) ───────────────
|
||||
|
||||
publish(groupId: number, fileId: string): Promise<void> {
|
||||
if (!fileId) throw new Error('publish requires fileId');
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
// ─────────────── count ───────────────
|
||||
|
||||
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
|
||||
return GetGroupFileCount.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
|
||||
|
||||
async upload(
|
||||
groupId: number,
|
||||
source: string,
|
||||
name = '',
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = this.ctx;
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileName,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
|
||||
// caller opts out via `uploadFile=false` (treat that as "I only
|
||||
// wanted the slot allocated, hold the chat post"). Routes through
|
||||
// `this.publish` so tests can mock at the same Api boundary.
|
||||
if (uploadFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
}
|
||||
|
||||
async uploadPrivate(
|
||||
userId: number,
|
||||
source: string,
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = this.ctx;
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
let selfUid = this.ctx.identity.selfUid;
|
||||
if (!selfUid) {
|
||||
const selfUin = toInt(this.ctx.identity.uin);
|
||||
if (selfUin > 0) {
|
||||
selfUid = await this.ctx.resolveUserUid(selfUin);
|
||||
}
|
||||
}
|
||||
if (!selfUid) throw new Error('self uid is unavailable');
|
||||
|
||||
const senderUin = toInt(this.ctx.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 upload = await UploadPrivateFileRequest.invoke(this.ctx, {
|
||||
senderUid: selfUid,
|
||||
receiverUid: targetUid,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
md510MCheckSum: md5First10MB(loaded.bytes),
|
||||
});
|
||||
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
|
||||
|
||||
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
|
||||
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
|
||||
if (!fileId) throw new Error('private file upload response missing file_id');
|
||||
|
||||
// Cache the metadata so a later `send_private_msg` carrying just
|
||||
// `{type:'file', file_id}` can resurrect the full c2c-file packet
|
||||
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
|
||||
// this the recipient sees a 0-byte file because the OneBot send path
|
||||
// has no way to recover those fields from the file_id alone.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'private',
|
||||
userId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
fileHash: fileHash ?? '',
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
// Host selection.
|
||||
//
|
||||
// Current QQ-NT server rollout has stopped populating the legacy
|
||||
// `uploadIp` (field 60) entirely. The host now arrives as the first
|
||||
// entry of `rtpMediaPlatformUploadAddress` (field 210, repeated
|
||||
// IPv4 message) — same place acidify reads it from since their
|
||||
// 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort`
|
||||
// (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN);
|
||||
// acidify uses `inIP`/`inPort` exclusively and so do we, because
|
||||
// that's the address the highway PUT actually needs to reach.
|
||||
//
|
||||
// The 32-bit IPs are little-endian-packed (byte0 = first octet)
|
||||
// per acidify's `Int.toIpString()`. Cross-checked the byte order
|
||||
// by inspecting their highway flow — there's no separate htonl
|
||||
// step, so the integer is already in network-octet-first order.
|
||||
//
|
||||
// Older server versions still populate the legacy string fields
|
||||
// (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain /
|
||||
// uploadDns), so we fall through to those after rtpMediaPlatform.
|
||||
// Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
|
||||
// what we picked.
|
||||
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
|
||||
&& upload.rtpMediaPlatformUploadAddress[0])
|
||||
? upload.rtpMediaPlatformUploadAddress[0] : null;
|
||||
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
|
||||
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
|
||||
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
|
||||
? rtpFirst.inPort : 0;
|
||||
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
|
||||
? upload.uploadIpList[0] : '';
|
||||
const uploadHost = (rtpInIP)
|
||||
|| (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
|
||||
|| (ipListFirst)
|
||||
|| (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
|
||||
|| (typeof upload.uploadDns === 'string' && upload.uploadDns)
|
||||
|| '';
|
||||
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
|
||||
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
|
||||
const uploadPort = rtpInIP && rtpInPort > 0
|
||||
? rtpInPort
|
||||
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
|
||||
? toInt(upload.uploadHttpsPort)
|
||||
: toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
|
||||
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
|
||||
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
|
||||
iPType: e.iPType,
|
||||
})))
|
||||
: '[]';
|
||||
log.warn(
|
||||
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
|
||||
rtpDump,
|
||||
upload.uploadIp ?? '', upload.uploadDomain ?? '',
|
||||
JSON.stringify(upload.uploadIpList ?? []),
|
||||
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
|
||||
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
|
||||
upload.uploadHttpsPort ?? 0,
|
||||
);
|
||||
throw new Error('private file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildPrivateFileUploadExt(
|
||||
senderUin,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
hashes.sha1,
|
||||
fileId,
|
||||
upload.mediaPlatformUploadKey instanceof Uint8Array
|
||||
? upload.mediaPlatformUploadKey
|
||||
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: publish the file as a c2c chat message. C2C files use
|
||||
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
|
||||
// the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate`
|
||||
// which only knows about elems[]. NapCat does the same atomic
|
||||
// upload+send dance — without it the file sits on the server and
|
||||
// the recipient sees nothing.
|
||||
if (uploadFile) {
|
||||
try {
|
||||
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
|
||||
fileId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileHash: fileHash ?? '',
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId, fileHash };
|
||||
}
|
||||
|
||||
// ─────────────── list (paginated loop) ───────────────
|
||||
|
||||
async list(groupId: number, folderId = '/'): Promise<GroupFilesResult> {
|
||||
const targetDirectory = normalizeDirectory(folderId);
|
||||
const files: GroupFileInfo[] = [];
|
||||
const folders: GroupFolderInfo[] = [];
|
||||
|
||||
const pageSize = 20;
|
||||
let startIndex = 0;
|
||||
for (let page = 0; page < 200; page++) {
|
||||
const list = await ListGroupFilesPage.invoke(this.ctx, {
|
||||
groupId, targetDirectory, startIndex, pageSize,
|
||||
});
|
||||
if (!list) break;
|
||||
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
|
||||
|
||||
for (const item of list.items ?? []) {
|
||||
const type = toInt(item?.type);
|
||||
if (type === 1 && item?.fileInfo) {
|
||||
const file = item.fileInfo;
|
||||
const uploader = toInt(file.uploaderUin);
|
||||
const cached = this.ctx.identity.findGroupMember(groupId, uploader);
|
||||
files.push({
|
||||
fileId: typeof file.fileId === 'string' ? file.fileId : '',
|
||||
fileName: typeof file.fileName === 'string' ? file.fileName : '',
|
||||
busId: toInt(file.busId),
|
||||
fileSize: toInt(file.fileSize),
|
||||
uploadTime: toInt(file.uploadedTime),
|
||||
deadTime: toInt(file.expireTime),
|
||||
modifyTime: toInt(file.modifiedTime),
|
||||
downloadTimes: toInt(file.downloadedTimes),
|
||||
uploader,
|
||||
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
});
|
||||
} else if (type === 2 && item?.folderInfo) {
|
||||
const folder = item.folderInfo;
|
||||
const creator = toInt(folder.creatorUin);
|
||||
const cached = this.ctx.identity.findGroupMember(groupId, creator);
|
||||
folders.push({
|
||||
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
|
||||
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
|
||||
createTime: toInt(folder.createTime),
|
||||
creator,
|
||||
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
totalFileCount: toInt(folder.totalFileCount),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (list.isEnd) break;
|
||||
startIndex += pageSize;
|
||||
}
|
||||
|
||||
return { files, folders };
|
||||
}
|
||||
|
||||
// ─────────────── url fetch (group / private files) ───────────────
|
||||
|
||||
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
|
||||
const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
|
||||
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
|
||||
|
||||
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|
||||
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|
||||
|| '';
|
||||
const hexUrl = bytesToHexUpper(download.downloadUrl);
|
||||
if (!dns || !hexUrl) {
|
||||
throw new Error('group file url response invalid');
|
||||
}
|
||||
|
||||
// Keep the same behavior as Lagrange: append file_id after ?fname=
|
||||
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
|
||||
}
|
||||
|
||||
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
const bridge = this.ctx;
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
void userId;
|
||||
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
|
||||
|
||||
const server = typeof result?.server === 'string' ? result.server : '';
|
||||
const port = toInt(result?.port);
|
||||
const url = typeof result?.url === 'string' ? result.url : '';
|
||||
if (!server || !port || !url) {
|
||||
throw new Error('private file url response invalid');
|
||||
}
|
||||
return `http://${server}:${port}${url}&isthumb=0`;
|
||||
}
|
||||
|
||||
// ─────────────── delete / move ───────────────
|
||||
|
||||
delete(groupId: number, fileId: string): Promise<void> {
|
||||
return DeleteGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> {
|
||||
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
|
||||
}
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
return CreateGroupFolder.invoke(this.ctx, {
|
||||
groupId, parentId: normalizeDirectory(parentId), folderName: name,
|
||||
});
|
||||
}
|
||||
|
||||
deleteFolder(groupId: number, folderId: string): Promise<void> {
|
||||
return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId });
|
||||
}
|
||||
|
||||
renameFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> {
|
||||
return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName });
|
||||
}
|
||||
|
||||
// ─────────────── rich-media URL by node ───────────────
|
||||
|
||||
getPttUrl(groupId: number, node: MediaIndexNode): Promise<string> {
|
||||
return GetGroupPttUrl.invoke(this.ctx, { groupId, node });
|
||||
}
|
||||
|
||||
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
|
||||
const bridge = this.ctx;
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
|
||||
}
|
||||
|
||||
getVideoUrl(groupId: number, node: MediaIndexNode): Promise<string> {
|
||||
return GetGroupVideoUrl.invoke(this.ctx, { groupId, node });
|
||||
}
|
||||
|
||||
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
|
||||
const bridge = this.ctx;
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
|
||||
}
|
||||
}
|
||||
87
packages/core/src/apis/index.ts
Normal file
87
packages/core/src/apis/index.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import type { CoreContext } from '../core-context';
|
||||
import { ContactsApi } from './contacts';
|
||||
import { ExtrasApi } from './extras';
|
||||
import { ForwardApi } from './forward';
|
||||
import { FriendApi } from './friend';
|
||||
import { GroupAdminApi } from './group-admin';
|
||||
import { GroupAlbumApi } from './group-album';
|
||||
import { GroupFileApi } from './group-file';
|
||||
import { InteractionApi } from './interaction';
|
||||
import { MessageApi } from './message';
|
||||
import { MiscApi } from './misc';
|
||||
import { ProfileApi } from './profile';
|
||||
import { WebApi } from './web';
|
||||
|
||||
export interface ApiHub {
|
||||
/** Send/recall/markRead operations across c2c + group + c2c-file. */
|
||||
readonly message: MessageApi;
|
||||
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
|
||||
readonly contacts: ContactsApi;
|
||||
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
|
||||
readonly groupAdmin: GroupAdminApi;
|
||||
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
|
||||
readonly groupFile: GroupFileApi;
|
||||
/** Group photo album: list/upload/comment/like/delete + media listing. */
|
||||
readonly groupAlbum: GroupAlbumApi;
|
||||
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
|
||||
readonly interaction: InteractionApi;
|
||||
/** Friend roster mutations: handleRequest / delete / setRemark. */
|
||||
readonly friend: FriendApi;
|
||||
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
|
||||
readonly profile: ProfileApi;
|
||||
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
|
||||
readonly forward: ForwardApi;
|
||||
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
|
||||
readonly misc: MiscApi;
|
||||
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
|
||||
readonly extras: ExtrasApi;
|
||||
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
|
||||
readonly web: WebApi;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct the ApiHub for a Bridge. Called once from the Bridge
|
||||
* constructor. Eager construction means every Bridge instance pays
|
||||
* the cost up-front (a few object allocations) — there's no lazy
|
||||
* path because that would require either a thunk-based wrapper or
|
||||
* runtime-mutated `apis.xxx` slots, neither of which is worth the
|
||||
* complexity for ~13 small classes.
|
||||
*/
|
||||
export function buildApiHub(ctx: CoreContext): ApiHub {
|
||||
return {
|
||||
message: new MessageApi(ctx),
|
||||
contacts: new ContactsApi(ctx),
|
||||
groupAdmin: new GroupAdminApi(ctx),
|
||||
groupFile: new GroupFileApi(ctx),
|
||||
groupAlbum: new GroupAlbumApi(ctx),
|
||||
interaction: new InteractionApi(ctx),
|
||||
friend: new FriendApi(ctx),
|
||||
profile: new ProfileApi(ctx),
|
||||
forward: new ForwardApi(ctx),
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
web: new WebApi(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export the Api classes themselves so callers can write
|
||||
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
|
||||
// signature use. Concrete instances always come from `bridge.apis.*`.
|
||||
export { ContactsApi, type DownloadRKeyInfo } from './contacts';
|
||||
export {
|
||||
AiVoiceChatType, ExtrasApi, type AiVoiceCategory,
|
||||
type AiVoiceItem,
|
||||
type StrangerStatus
|
||||
} from './extras';
|
||||
export { ForwardApi } from './forward';
|
||||
export { FriendApi } from './friend';
|
||||
export { GroupAdminApi } from './group-admin';
|
||||
export { GroupAlbumApi } from './group-album';
|
||||
export { GroupFileApi } from './group-file';
|
||||
export { InteractionApi } from './interaction';
|
||||
export { MessageApi, type SendMessageReceipt } from './message';
|
||||
export { MiscApi } from './misc';
|
||||
export { ProfileApi } from './profile';
|
||||
export { type MediaIndexNode } from './shared';
|
||||
export { WebApi, type ClientKeyInfo, type WebHonorInfo, type WebNoticeInfo } from './web';
|
||||
|
||||
68
packages/core/src/apis/interaction.ts
Normal file
68
packages/core/src/apis/interaction.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
// InteractionApi — facade over interactive-engagement OIDB cmds
|
||||
// (poke / like / reaction / essence / emoji-like-list). Every method
|
||||
// is a one-line forwarder to a self-contained namespace under
|
||||
// @snowluma/protocol/oidb-services. The facade exists purely to keep
|
||||
// the `bridge.apis.interaction.X(...)` ergonomic call style; all wire
|
||||
// work (envelope build / encode / send / decode) lives in the
|
||||
// namespace files.
|
||||
|
||||
import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like';
|
||||
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
|
||||
import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence';
|
||||
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
|
||||
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
|
||||
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class InteractionApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
|
||||
}
|
||||
|
||||
sendLike(userId: number, count: number): Promise<void> {
|
||||
return SendLike.invoke(this.ctx, { userId, count });
|
||||
}
|
||||
|
||||
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
|
||||
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
|
||||
}
|
||||
|
||||
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
|
||||
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy stub: see `GetEmojiLikes` namespace comment for why this
|
||||
* SSO path can never surface the user list. Real data lives in
|
||||
* ReactionStore on the OneBot side.
|
||||
*/
|
||||
async getEmojiLikes(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType = 1,
|
||||
count = 10,
|
||||
cookie = '',
|
||||
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
|
||||
try {
|
||||
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
|
||||
} catch {
|
||||
return { users: [], cookie: '', isLast: true };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the per-emoji reaction summary on a group message via
|
||||
* 0x9084_1 — emoji_id + reactor count + last-reaction timestamp.
|
||||
* Cross-checked against the local ReactionStore cache for callers
|
||||
* that need to detect cache gaps.
|
||||
*/
|
||||
fetchReactionSummary(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
|
||||
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
|
||||
}
|
||||
}
|
||||
337
packages/core/src/apis/message.ts
Normal file
337
packages/core/src/apis/message.ts
Normal file
@@ -0,0 +1,337 @@
|
||||
import type {
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import type {
|
||||
C2CRecallRequest,
|
||||
GroupRecallRequest,
|
||||
SsoReadedReportReq,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
/**
|
||||
* Receipt returned by every typed `send*Message` call. The OneBot
|
||||
* adapter feeds these into its `MessageStore` so later `recall_msg`
|
||||
* actions can resolve the wire-level coordinates (sequence + random)
|
||||
* from the `message_id` it previously emitted.
|
||||
*/
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
sequence: number;
|
||||
clientSequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
export class MessageApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
/**
|
||||
* Send a message to a QQ group.
|
||||
*
|
||||
* Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`.
|
||||
* Media elements (image / record / video) trigger highway uploads
|
||||
* inside `buildSendElems` — see `element-builder.ts`.
|
||||
*
|
||||
* Returns a `SendMessageReceipt` carrying the assigned messageId,
|
||||
* group sequence, and timestamps; callers cache this for later
|
||||
* `recall` / reply lookups.
|
||||
*/
|
||||
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx, groupId });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
grp: { groupCode: BigInt(groupId) },
|
||||
},
|
||||
contentHead: {
|
||||
type: 1,
|
||||
},
|
||||
messageBody: {
|
||||
richText: {
|
||||
elems: protoElems,
|
||||
},
|
||||
},
|
||||
clientSequence: 0,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
multiSendSeq: 0,
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
|
||||
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||
if (response.result != null && response.result !== 0) {
|
||||
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const seq = response.groupSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a c2c (private) message.
|
||||
*
|
||||
* Resolves the recipient's UID only when the message carries media
|
||||
* — text-only messages skip the lookup. Routes through `c2c.uin`
|
||||
* (and optionally `c2c.uid` for the media case).
|
||||
*/
|
||||
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
let userUid = '';
|
||||
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
||||
if (hasMedia) {
|
||||
userUid = await this.ctx.resolveUserUid(userUin);
|
||||
}
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx, userUid });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
c2c: {
|
||||
uin: userUin,
|
||||
...(userUid ? { uid: userUid } : {}),
|
||||
},
|
||||
},
|
||||
contentHead: {
|
||||
type: 1,
|
||||
subType: 0,
|
||||
c2cCmd: 11,
|
||||
},
|
||||
messageBody: {
|
||||
richText: {
|
||||
elems: protoElems,
|
||||
},
|
||||
},
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
ctrl: {
|
||||
msgFlag: Math.floor(Date.now() / 1000),
|
||||
},
|
||||
multiSendSeq: 0,
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
|
||||
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||
if (response.result != null && response.result !== 0) {
|
||||
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const seq = response.privateSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a c2c file as a chat message.
|
||||
*
|
||||
* The wire shape isn't the same as a regular c2c message — the c2c
|
||||
* file path uses three slots that differ from a normal text/image
|
||||
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
|
||||
* BuildPacketBase` + `FileEntity.PackMessageContent`):
|
||||
*
|
||||
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
|
||||
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
|
||||
* messages routed through the regular c2c slot.
|
||||
* 2. `messageBody.msgContent` carries the serialised
|
||||
* `FileExtra { file: NotOnlineFile }` bytes. NOT
|
||||
* `richText.notOnlineFile` — the receiver doesn't read that
|
||||
* slot for file metadata.
|
||||
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
|
||||
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
|
||||
* server doesn't recognise.
|
||||
*
|
||||
* NotOnlineFile carries three required-on-send fields the receiver
|
||||
* itself ignores but the server's intake validator checks:
|
||||
* - `subcmd: 1` — c2c file send command code
|
||||
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
|
||||
* - `expireTime` — 7 days from now (Lagrange convention)
|
||||
*/
|
||||
async sendC2cFile(
|
||||
userUin: number,
|
||||
userUid: string,
|
||||
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
|
||||
): Promise<SendMessageReceipt> {
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const sevenDaysSec = 7 * 24 * 60 * 60;
|
||||
const fileExtraBytes = protobuf_encode<FileExtra>({
|
||||
file: {
|
||||
fileType: 0,
|
||||
fileUuid: info.fileId,
|
||||
fileMd5: info.fileMd5,
|
||||
fileName: info.fileName,
|
||||
fileSize: BigInt(info.fileSize),
|
||||
subcmd: 1,
|
||||
dangerEvel: 0,
|
||||
expireTime: nowSec + sevenDaysSec,
|
||||
fileHash: info.fileHash ?? '',
|
||||
},
|
||||
});
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
trans0x211: { ccCmd: 4, uid: userUid },
|
||||
},
|
||||
contentHead: {
|
||||
type: 1,
|
||||
subType: 0,
|
||||
},
|
||||
messageBody: {
|
||||
msgContent: fileExtraBytes,
|
||||
},
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
ctrl: { msgFlag: nowSec },
|
||||
multiSendSeq: 0,
|
||||
});
|
||||
|
||||
// `userUin` is part of the public contract (the OneBot layer
|
||||
// threads it through for symmetry with `sendPrivate`) but the
|
||||
// wire shape only needs the uid. Silence the unused-parameter
|
||||
// lint without changing the signature.
|
||||
void userUin;
|
||||
|
||||
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||
if (response.result != null && response.result !== 0) {
|
||||
throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
const seq = response.privateSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Recall (revoke) a group message by sequence number. Server-side
|
||||
* the message ages out after the standard 2-minute window unless
|
||||
* the user is an admin/owner.
|
||||
*/
|
||||
async recallGroup(groupId: number, sequence: number): Promise<void> {
|
||||
const request = protobuf_encode<GroupRecallRequest>({
|
||||
type: 1,
|
||||
groupUin: groupId,
|
||||
info: { sequence, random: 0, field3: 0 },
|
||||
settings: { field1: 0 },
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Recall a c2c (private) message. Needs more positional info than
|
||||
* the group variant because c2c messages are identified by the
|
||||
* `(clientSequence, msgSequence, random, timestamp)` tuple rather
|
||||
* than a single group-side sequence.
|
||||
*/
|
||||
async recallPrivate(
|
||||
userUin: number,
|
||||
clientSeq: number,
|
||||
msgSeq: number,
|
||||
random: number,
|
||||
timestamp: number,
|
||||
): Promise<void> {
|
||||
const targetUid = await this.ctx.resolveUserUid(userUin);
|
||||
const request = protobuf_encode<C2CRecallRequest>({
|
||||
type: 1,
|
||||
targetUid,
|
||||
info: {
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
messageId: BigInt((0x01000000 * 0x100000000) + random),
|
||||
timestamp,
|
||||
field5: 0,
|
||||
messageSequence: msgSeq,
|
||||
},
|
||||
settings: { field1: false, field2: false },
|
||||
field6: false,
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
|
||||
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
|
||||
* NT client's own "scrolled to bottom" behaviour so subsequent
|
||||
* sync packets don't replay messages we've already processed.
|
||||
*/
|
||||
async markGroupRead(groupId: number, sequence: number): Promise<void> {
|
||||
const request = protobuf_encode<SsoReadedReportReq>({
|
||||
groupList: [
|
||||
{
|
||||
groupUin: BigInt(groupId),
|
||||
lastReadSeq: BigInt(sequence),
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark group message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a c2c read-report. Same wire-cmd as the group variant but
|
||||
* keyed by friend uid (resolved from uin via IdentityService).
|
||||
* `lastReadTime` defaults to "now" — matches the QQ NT client
|
||||
* which also uses wall-clock seconds rather than the read-message
|
||||
* timestamp.
|
||||
*/
|
||||
async markPrivateRead(userId: number, sequence: number): Promise<void> {
|
||||
const uid = await this.ctx.resolveUserUid(userId);
|
||||
const request = protobuf_encode<SsoReadedReportReq>({
|
||||
c2cList: [
|
||||
{
|
||||
uid,
|
||||
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
|
||||
lastReadSeq: BigInt(sequence),
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
78
packages/core/src/apis/misc.ts
Normal file
78
packages/core/src/apis/misc.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import type {
|
||||
MiniAppShareReq,
|
||||
MiniAppShareResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
// Migrated OIDB cmds — facade methods are one-line forwarders.
|
||||
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
|
||||
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
|
||||
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
translateEn2Zh(words: string[]): Promise<string[]> {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
if (type === 'weibo') {
|
||||
appid = '1109224783';
|
||||
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
} else if (type !== 'bili') {
|
||||
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
|
||||
}
|
||||
|
||||
const request = protobuf_encode<MiniAppShareReq>({
|
||||
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
|
||||
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
|
||||
|
||||
if (!result.success || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'get mini app ark failed');
|
||||
}
|
||||
|
||||
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
|
||||
const jsonStr = decoded?.body?.jsonStr;
|
||||
|
||||
if (!jsonStr) {
|
||||
throw new Error('mini app share json empty');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
|
||||
|
||||
return {
|
||||
data: {
|
||||
ver: parsed.ver,
|
||||
prompt: parsed.prompt,
|
||||
config: parsed.config,
|
||||
app: parsed.appName,
|
||||
view: parsed.appView,
|
||||
meta: parsed.metaData,
|
||||
miniappShareOrigin: 3,
|
||||
miniappOpenRefer: '10002',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
clickInlineKeyboardButton(
|
||||
groupId: number,
|
||||
botAppid: number,
|
||||
buttonId: string,
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
): Promise<JsonValue> {
|
||||
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
|
||||
}
|
||||
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
}
|
||||
147
packages/core/src/apis/profile.ts
Normal file
147
packages/core/src/apis/profile.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import type {
|
||||
FaceroamOpReq,
|
||||
FaceroamOpResp,
|
||||
GroupAvatarExtra,
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
|
||||
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
|
||||
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class ProfileApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── status / profile setters ───────────────
|
||||
|
||||
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
|
||||
await this.dispatchSetStatus({ 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.
|
||||
*/
|
||||
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
|
||||
await this.dispatchSetStatus({
|
||||
status: 10,
|
||||
extStatus: 2000,
|
||||
batteryStatus: 0,
|
||||
customExt: { faceId, text: wording, faceType },
|
||||
});
|
||||
}
|
||||
|
||||
private async dispatchSetStatus(value: {
|
||||
status: number;
|
||||
extStatus: number;
|
||||
batteryStatus: number;
|
||||
customExt?: { faceId: number; text: string; faceType: number };
|
||||
}): Promise<void> {
|
||||
const request = protobuf_encode<SetStatusReq>(value);
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
|
||||
request,
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protobuf_decode<SetStatusResp>(result.responseData);
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
if (resp.errCode !== undefined && resp.errCode !== 0) {
|
||||
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setProfile(nickname?: string, personalNote?: string): Promise<void> {
|
||||
return SetProfile.invoke(this.ctx, { nickname, personalNote });
|
||||
}
|
||||
|
||||
setSelfLongNick(longNick: string): Promise<void> {
|
||||
return SetSelfLongNick.invoke(this.ctx, { longNick });
|
||||
}
|
||||
|
||||
setInputStatus(userId: number, eventType: number): Promise<void> {
|
||||
return SetInputStatus.invoke(this.ctx, { userId, eventType });
|
||||
}
|
||||
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = this.ctx;
|
||||
const loaded = await loadBinarySource(source, 'avatar');
|
||||
if (!loaded.bytes.length) throw new Error('avatar file is empty');
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
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.
|
||||
*/
|
||||
async setGroupAvatar(groupId: number, source: string): Promise<void> {
|
||||
const bridge = this.ctx;
|
||||
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 = protobuf_encode<GroupAvatarExtra>({
|
||||
type: 101,
|
||||
groupUin: groupId,
|
||||
field3: { field1: 1 },
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
|
||||
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
|
||||
return GetLike.invoke(this.ctx, { userId, start, limit });
|
||||
}
|
||||
|
||||
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
|
||||
return GetUnidirectionalFriendList.invoke(this.ctx);
|
||||
}
|
||||
|
||||
async fetchCustomFace(count = 10): Promise<string[]> {
|
||||
const req = {
|
||||
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
|
||||
uin: BigInt(this.ctx.identity.uin),
|
||||
field3: 1,
|
||||
field6: 1,
|
||||
};
|
||||
const request = protobuf_encode<FaceroamOpReq>(req);
|
||||
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'fetch custom face failed');
|
||||
}
|
||||
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
|
||||
if (!resp || resp.retCode !== 0) {
|
||||
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
|
||||
}
|
||||
const faceIds = resp.item?.faceIds || [];
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,6 @@
|
||||
// Shared private helpers for the action modules. None of this is part
|
||||
// of the public Bridge API; keeping it here avoids re-importing the
|
||||
// same five-line utility from every themed file.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
/**
|
||||
* Coerce numbers, strings, and bigints to a plain integer.
|
||||
* Returns 0 for anything we can't interpret — every action that
|
||||
* threads this through OIDB has an explicit `<=0` validation later.
|
||||
*/
|
||||
export function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'bigint') {
|
||||
@@ -40,7 +32,7 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
|
||||
* `selfProfile`; forward/profile actions need this fast path before
|
||||
* warmup completes.
|
||||
*/
|
||||
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
|
||||
export async function resolveSelfUid(bridge: BridgeContext): Promise<string> {
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (selfUid) return selfUid;
|
||||
|
||||
335
packages/core/src/apis/web.ts
Normal file
335
packages/core/src/apis/web.ts
Normal file
@@ -0,0 +1,335 @@
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
getGroupNoticeWebAPI,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
type SetNoticeRetSuccess,
|
||||
} from '@snowluma/protocol/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export type ClientKeyInfo = NamespaceClientKeyInfo;
|
||||
|
||||
export interface WebHonorInfo {
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
group_id: number;
|
||||
current_talkative: WebHonorItem | null;
|
||||
talkative_list: WebHonorItem[];
|
||||
performer_list: WebHonorItem[];
|
||||
legend_list: WebHonorItem[];
|
||||
emotion_list: WebHonorItem[];
|
||||
strong_newbie_list: WebHonorItem[];
|
||||
}
|
||||
|
||||
export interface WebNoticeInfo {
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
notice_id: string;
|
||||
sender_id: number;
|
||||
publish_time: number;
|
||||
message: {
|
||||
text: string;
|
||||
image: Array<{ id: string; height: number; width: number }>;
|
||||
images: Array<{ id: string; height: number; width: number }>;
|
||||
};
|
||||
settings: import('@snowluma/common/json').JsonValue;
|
||||
read_num: number;
|
||||
}
|
||||
|
||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||
|
||||
function forceFetchClientKeyInner(bridge: BridgeContext): Promise<ClientKeyInfo> {
|
||||
return ForceFetchClientKey.invoke(bridge);
|
||||
}
|
||||
|
||||
function getPSkey(bridge: BridgeContext, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
return GetPskey.invoke(bridge, { domainList });
|
||||
}
|
||||
|
||||
async function getCookies(bridge: BridgeContext, domain: string): Promise<Record<string, string>> {
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
|
||||
// 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.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
|
||||
// for the same domain. Errors are swallowed so the caller can
|
||||
// still proceed with whatever cookies it did get.
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async function getSKey(bridge: BridgeContext): Promise<string> {
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
|
||||
if (!ClientKeyData.clientKey) {
|
||||
throw new Error('getClientKey Error: clientKey is empty');
|
||||
}
|
||||
|
||||
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.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=' + u1 +
|
||||
'&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const skey = cookies['skey'];
|
||||
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
|
||||
return skey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard QQ bkn hash (also known as token / csrf_token) derived from
|
||||
* skey or p_skey. djb2 hash truncated to 31 bits.
|
||||
*/
|
||||
function getBknFromSKey(skey: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return hash & 2147483647;
|
||||
}
|
||||
|
||||
export class WebApi {
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── cookie / token primitives ───────────────
|
||||
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> {
|
||||
return forceFetchClientKeyInner(this.ctx);
|
||||
}
|
||||
|
||||
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
|
||||
* (qzone.qq.com) and by every other web helper here. */
|
||||
async getCookies(domain: string): Promise<Record<string, string>> {
|
||||
return getCookies(this.ctx, domain);
|
||||
}
|
||||
|
||||
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
|
||||
async getCookiesStr(domain: string): Promise<string> {
|
||||
const cookieObject = await getCookies(this.ctx, domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
async getCsrfToken(): Promise<number> {
|
||||
const skey = await getSKey(this.ctx);
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
|
||||
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
|
||||
const cookieObject = await getCookies(this.ctx, domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
const token = skey ? getBknFromSKey(skey) : 0;
|
||||
|
||||
return {
|
||||
cookies: cookiesStr,
|
||||
token,
|
||||
csrf_token: token,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── group essence ───────────────
|
||||
|
||||
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
|
||||
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
|
||||
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
|
||||
}
|
||||
|
||||
/** Walks every page and returns the concatenated result. */
|
||||
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
}
|
||||
|
||||
// ─────────────── group honor ───────────────
|
||||
|
||||
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const honorInfo: WebHonorInfo = {
|
||||
group_id: groupId,
|
||||
current_talkative: null,
|
||||
talkative_list: [],
|
||||
performer_list: [],
|
||||
legend_list: [],
|
||||
emotion_list: [],
|
||||
strong_newbie_list: [],
|
||||
};
|
||||
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
}
|
||||
}
|
||||
|
||||
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
|
||||
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
|
||||
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
|
||||
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
|
||||
}
|
||||
|
||||
return honorInfo;
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
|
||||
async sendNotice(
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // local path, http URL, or undefined (text-only)
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
confirm_required?: number;
|
||||
},
|
||||
): Promise<SetNoticeRetSuccess> {
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
let picId = '';
|
||||
let imgWidth = 540;
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
let imageBuffer: Buffer;
|
||||
|
||||
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
|
||||
const response = await fetch(options.image);
|
||||
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
|
||||
imageBuffer = Buffer.from(await response.arrayBuffer());
|
||||
} else {
|
||||
const { readFileSync } = await import('fs');
|
||||
imageBuffer = readFileSync(options.image);
|
||||
}
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
options?.pinned ?? 0,
|
||||
options?.type ?? 1,
|
||||
1,
|
||||
1,
|
||||
options?.confirm_required ?? 1,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
);
|
||||
|
||||
if (!ret || ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
if (!ret) {
|
||||
throw new Error('获取公告失败');
|
||||
}
|
||||
|
||||
const retNotices: WebNoticeInfo[] = [];
|
||||
|
||||
if (ret.feeds) {
|
||||
for (const key in ret.feeds) {
|
||||
const feed = ret.feeds[key];
|
||||
if (!feed) continue;
|
||||
|
||||
const image = feed.msg?.pics?.map((pic) => ({
|
||||
id: pic.id,
|
||||
height: pic.h,
|
||||
width: pic.w,
|
||||
})) || [];
|
||||
|
||||
retNotices.push({
|
||||
notice_id: feed.fid,
|
||||
sender_id: feed.u,
|
||||
publish_time: feed.pubt,
|
||||
message: {
|
||||
text: feed.msg?.text || '',
|
||||
image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
}
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
|
||||
}
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
// 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`);
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
// Forward-message upload / download via the long-message service.
|
||||
// Uses gzipped protobufs over `trpc.group.long_msg_interface`.
|
||||
// An in-memory cache keeps res_ids stable across rapid re-fetches
|
||||
// from the same OneBot client (avoids re-decoding the same payload).
|
||||
|
||||
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';
|
||||
import type { ForwardNodePayload } from '../events';
|
||||
import type { PacketInfo } from '../../protocol/types';
|
||||
import {
|
||||
LongMsgResultSchema,
|
||||
RecvLongMsgReqSchema,
|
||||
RecvLongMsgRespSchema,
|
||||
SendLongMsgReqSchema,
|
||||
SendLongMsgRespSchema,
|
||||
} from '../proto/longmsg';
|
||||
import { PushMsgSchema } from '../proto/message';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
|
||||
// of the process — that's enough because OneBot clients typically
|
||||
// resolve a forward immediately after receiving the parent message.
|
||||
const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
|
||||
async function buildForwardPushBody(
|
||||
bridge: Bridge,
|
||||
node: ForwardNodePayload,
|
||||
groupId?: number,
|
||||
userUid?: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
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);
|
||||
// image/record/video upload inside a forward node must be scoped to the
|
||||
// forward's recipient: group → groupId, private → recipient uid.
|
||||
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
|
||||
// element builder throws "private image target uid is missing".
|
||||
const sendCtx = groupId !== undefined
|
||||
? { bridge, groupId }
|
||||
: userUid
|
||||
? { bridge, userUid }
|
||||
: { bridge };
|
||||
const elems = await buildSendElems(node.elements, sendCtx);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
|
||||
const seq = Math.floor(Math.random() * 9000000) + 1000000;
|
||||
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin,
|
||||
toUid: bridge.identity.selfUid ?? '',
|
||||
forward: {
|
||||
friendName: nickname,
|
||||
},
|
||||
},
|
||||
contentHead: {
|
||||
msgType: 9,
|
||||
subType: 4,
|
||||
msgId: random,
|
||||
sequence: seq,
|
||||
timestamp: now,
|
||||
divSeq: 0,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
elems,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function uploadForwardNodes(
|
||||
bridge: Bridge,
|
||||
nodes: ForwardNodePayload[],
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<string> {
|
||||
if (!Array.isArray(nodes) || nodes.length === 0) {
|
||||
throw new Error('forward nodes are required');
|
||||
}
|
||||
|
||||
// For a private forward to `userId`, any image/record/video inside a node
|
||||
// needs the recipient's uid as upload scene. Resolve it once up-front,
|
||||
// and only when at least one node actually contains media (saves an RPC
|
||||
// for text-only forwards).
|
||||
let userUid: string | undefined;
|
||||
if (groupId === undefined && userId !== undefined && userId > 0) {
|
||||
const hasMedia = nodes.some(node => node.elements.some(
|
||||
e => e.type === 'image' || e.type === 'record' || e.type === 'video',
|
||||
));
|
||||
if (hasMedia) {
|
||||
const resolved = await bridge.resolveUserUid(userId);
|
||||
if (resolved) userUid = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid)));
|
||||
const longMsgResult = protoEncode({
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: { msgBody: msgBody as any },
|
||||
},
|
||||
],
|
||||
}, LongMsgResultSchema);
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const info: any = {
|
||||
type: groupId ? 3 : 1,
|
||||
uid: { uid: groupId ? String(groupId) : selfUid },
|
||||
payload: gzipSync(Buffer.from(longMsgResult)),
|
||||
};
|
||||
if (groupId) info.groupUin = groupId;
|
||||
|
||||
const request = protoEncode({
|
||||
info,
|
||||
settings: {
|
||||
field1: 4,
|
||||
field2: 1,
|
||||
field3: 7,
|
||||
field4: 0,
|
||||
},
|
||||
}, SendLongMsgReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'upload forward message failed');
|
||||
}
|
||||
|
||||
const resp = protoDecode(result.responseData, SendLongMsgRespSchema);
|
||||
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
|
||||
if (!resId) {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId ?? groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
|
||||
})));
|
||||
|
||||
return resId;
|
||||
}
|
||||
|
||||
export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<ForwardNodePayload[]> {
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
return cached.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
}
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const request = protoEncode({
|
||||
info: {
|
||||
uid: { uid: selfUid },
|
||||
resId,
|
||||
acquire: true,
|
||||
},
|
||||
settings: {
|
||||
field1: 2,
|
||||
field2: 0,
|
||||
field3: 0,
|
||||
field4: 0,
|
||||
},
|
||||
}, RecvLongMsgReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'download forward message failed');
|
||||
}
|
||||
|
||||
const resp = protoDecode(result.responseData, RecvLongMsgRespSchema);
|
||||
const payload = resp?.result?.payload;
|
||||
if (!(payload instanceof Uint8Array) || payload.length === 0) {
|
||||
throw new Error('download forward message payload is empty');
|
||||
}
|
||||
|
||||
const inflate = gunzipSync(Buffer.from(payload));
|
||||
const longMsg = protoDecode(inflate, LongMsgResultSchema);
|
||||
const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
for (const msgBody of msgBodyList) {
|
||||
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
|
||||
const pkt: PacketInfo = {
|
||||
pid: 0,
|
||||
uin: bridge.identity.uin,
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 0,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: wrapped,
|
||||
};
|
||||
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;
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
nodes.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderCard || event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgId: event.msgId,
|
||||
msgSeq: event.msgSeq,
|
||||
groupId: event.groupId,
|
||||
senderCard: event.senderCard,
|
||||
messageType: 'group',
|
||||
});
|
||||
} else if (event.kind === 'friend_message') {
|
||||
nodes.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgId: event.msgId,
|
||||
msgSeq: event.msgSeq,
|
||||
messageType: 'private',
|
||||
});
|
||||
} else {
|
||||
nodes.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgSeq: event.msgSeq,
|
||||
groupId: event.groupId,
|
||||
messageType: 'private',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
})));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
// Friend-list operations: accept/reject add request, delete, set the
|
||||
// local remark label. Each one resolves a UID first because the OIDB
|
||||
// protocol uses opaque UIDs rather than QQ uin numbers.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
OidbDeleteFriendSchema,
|
||||
OidbFriendRequestActionSchema,
|
||||
OidbSetFriendRemarkSchema,
|
||||
} from '../proto/oidb-action';
|
||||
|
||||
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
let targetUid = uidOrFlag;
|
||||
if (/^\d+$/.test(uidOrFlag)) {
|
||||
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
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 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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Refresh friend cache after deletion so subsequent reads don't
|
||||
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
|
||||
// shouldn't make the delete itself look failed.
|
||||
try { await bridge.fetchFriendList(); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
|
||||
const uid = await bridge.resolveUserUid(userId);
|
||||
await runOidb(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xb6e_2',
|
||||
oidbCmd: 0xB6E, subCmd: 2,
|
||||
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
|
||||
});
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
// Group admin actions: mute/kick/leave/role/profile + join-request approval.
|
||||
// Every function ultimately routes through one OIDB schema; the function
|
||||
// names match the OneBot action names (set_group_kick, set_group_ban, ...)
|
||||
// so callers can grep across the two layers.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
Oidb0x89a_0AddOptionSchema,
|
||||
Oidb0x89a_0SearchSchema,
|
||||
Oidb0x8a0ReqSchema,
|
||||
Oidb0x8a7ReqSchema,
|
||||
Oidb0x8a7RespSchema,
|
||||
OidbGroupRequestActionSchema,
|
||||
OidbKickMemberSchema,
|
||||
OidbLeaveGroupSchema,
|
||||
OidbMuteAllSchema,
|
||||
OidbMuteMemberSchema,
|
||||
OidbRenameGroupSchema,
|
||||
OidbRenameMemberSchema,
|
||||
OidbSetAdminSchema,
|
||||
OidbSpecialTitleSchema,
|
||||
Oidb0xf16ReqSchema,
|
||||
} from '../proto/oidb-action';
|
||||
|
||||
// ─────────────── mute / un-mute ───────────────
|
||||
|
||||
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
|
||||
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 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 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 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(
|
||||
bridge: Bridge, groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
): Promise<void> {
|
||||
const subCmd = filtered ? 2 : 1;
|
||||
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
|
||||
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 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 => 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 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 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 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 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 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 ───────────────
|
||||
|
||||
// setGroupRemark is the bot's local-only label for the group; it lives
|
||||
// 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 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 ───────────────
|
||||
|
||||
export async function getGroupAtAllRemain(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
) {
|
||||
const req = {
|
||||
basic1: 1,
|
||||
basic2: 2,
|
||||
basic3: 1,
|
||||
uin: BigInt(bridge.identity.uin),
|
||||
groupId: BigInt(groupId),
|
||||
type: 0,
|
||||
};
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
// Cast numbers to plain Number: the OIDB layer may surface uint32 as
|
||||
// BigInt and the WebUI JSON serializer chokes on those.
|
||||
return {
|
||||
can_at_all: !!result.canAtAll,
|
||||
remain_at_all_count_for_group: Number(result.groupRemain || 0),
|
||||
remain_at_all_count_for_uin: Number(result.uinRemain || 0),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,826 +0,0 @@
|
||||
// Group + private file operations: upload (with highway fast-path),
|
||||
// folder management, file listing, file/media URL fetch. All upload
|
||||
// paths share the same shape (resolve target → OIDB metadata exchange
|
||||
// → highway HTTP PUT if the server says we must), but the OIDB schemas
|
||||
// and field layouts differ enough between group and private that they
|
||||
// stay as separate functions.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { protoEncode } from '../../protobuf/decode';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
|
||||
import {
|
||||
OidbGroupFileCountViewReqSchema,
|
||||
OidbGroupFileCountViewRespSchema,
|
||||
OidbGroupFileFolderReqSchema,
|
||||
OidbGroupFileFolderRespSchema,
|
||||
OidbGroupFileReqSchema,
|
||||
OidbGroupFileRespSchema,
|
||||
OidbGroupFileViewReqSchema,
|
||||
OidbGroupFileViewRespSchema,
|
||||
OidbPrivateFileDownloadReqSchema,
|
||||
OidbPrivateFileDownloadRespSchema,
|
||||
OidbPrivateFileUploadReqSchema,
|
||||
OidbPrivateFileUploadRespSchema,
|
||||
NTV2RichMediaReqSchema,
|
||||
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 ───────────────
|
||||
|
||||
export interface GroupFileInfo {
|
||||
fileId: string;
|
||||
fileName: string;
|
||||
busId: number;
|
||||
fileSize: number;
|
||||
uploadTime: number;
|
||||
deadTime: number;
|
||||
modifyTime: number;
|
||||
downloadTimes: number;
|
||||
uploader: number;
|
||||
uploaderName: string;
|
||||
}
|
||||
|
||||
export interface GroupFolderInfo {
|
||||
folderId: string;
|
||||
folderName: string;
|
||||
createTime: number;
|
||||
creator: number;
|
||||
creatorName: string;
|
||||
totalFileCount: number;
|
||||
}
|
||||
|
||||
export interface GroupFilesResult {
|
||||
files: GroupFileInfo[];
|
||||
folders: GroupFolderInfo[];
|
||||
}
|
||||
|
||||
export interface UploadFileResult {
|
||||
fileId: string | null;
|
||||
fileHash?: string | null;
|
||||
}
|
||||
|
||||
// Re-export so this file is a one-stop-shop for the file API surface
|
||||
// (bridge.ts imports MediaIndexNode through here for type symmetry).
|
||||
export type { MediaIndexNode } from './shared';
|
||||
|
||||
// ─────────────── file-specific helpers ───────────────
|
||||
|
||||
function normalizeDirectory(dir?: string): string {
|
||||
if (!dir || !dir.trim()) return '/';
|
||||
return dir;
|
||||
}
|
||||
|
||||
function bytesToHexUpper(data: unknown): string {
|
||||
if (!(data instanceof Uint8Array) || data.length === 0) return '';
|
||||
return toHexUpper(data);
|
||||
}
|
||||
|
||||
function normalizeUploadFileName(name: string, fallback: string): string {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed) return trimmed;
|
||||
const safeFallback = fallback.trim();
|
||||
return safeFallback || 'file.bin';
|
||||
}
|
||||
|
||||
function md5First10MB(bytes: Uint8Array): Uint8Array {
|
||||
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
|
||||
return computeMd5(bytes.subarray(0, limit));
|
||||
}
|
||||
|
||||
function buildGroupFileUploadExt(
|
||||
senderUin: number,
|
||||
groupId: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
fileId: string,
|
||||
uploadKey: Uint8Array,
|
||||
checkKey: Uint8Array,
|
||||
uploadHost: string,
|
||||
uploadPort: number,
|
||||
): Uint8Array {
|
||||
return protoEncode({
|
||||
unknown1: 100,
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: BigInt(groupId),
|
||||
groupCode: BigInt(groupId),
|
||||
},
|
||||
fileEntry: {
|
||||
fileSize: BigInt(Math.max(0, fileSize)),
|
||||
md5,
|
||||
md5S2: md5,
|
||||
checkKey,
|
||||
fileId,
|
||||
uploadKey,
|
||||
},
|
||||
clientInfo: {
|
||||
clientType: 3,
|
||||
appId: '100',
|
||||
terminalType: 3,
|
||||
clientVer: '1.1.1',
|
||||
unknown: 4,
|
||||
},
|
||||
fileNameInfo: {
|
||||
fileName,
|
||||
},
|
||||
host: {
|
||||
hosts: [
|
||||
{
|
||||
url: {
|
||||
host: uploadHost,
|
||||
unknown: 1,
|
||||
},
|
||||
port: uploadPort,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
unknown200: 0,
|
||||
}, FileUploadExtSchema);
|
||||
}
|
||||
|
||||
function buildPrivateFileUploadExt(
|
||||
senderUin: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
sha1: Uint8Array,
|
||||
fileId: string,
|
||||
uploadKey: Uint8Array,
|
||||
uploadHost: string,
|
||||
uploadPort: number,
|
||||
): Uint8Array {
|
||||
return protoEncode({
|
||||
unknown1: 100,
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: 0n,
|
||||
groupCode: 0n,
|
||||
},
|
||||
fileEntry: {
|
||||
fileSize: BigInt(Math.max(0, fileSize)),
|
||||
md5,
|
||||
md5S2: md5,
|
||||
checkKey: sha1,
|
||||
fileId,
|
||||
uploadKey,
|
||||
},
|
||||
clientInfo: {
|
||||
clientType: 3,
|
||||
appId: '100',
|
||||
terminalType: 3,
|
||||
clientVer: '1.1.1',
|
||||
unknown: 4,
|
||||
},
|
||||
fileNameInfo: {
|
||||
fileName,
|
||||
},
|
||||
host: {
|
||||
hosts: [
|
||||
{
|
||||
url: {
|
||||
host: uploadHost,
|
||||
unknown: 1,
|
||||
},
|
||||
port: uploadPort,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
unknown3: 0,
|
||||
unknown200: 1,
|
||||
}, FileUploadExtSchema);
|
||||
}
|
||||
|
||||
function normalizeMediaNode(node: MediaIndexNode): Record<string, unknown> {
|
||||
const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
|
||||
if (!fileUuid) throw new Error('media node fileUuid is required');
|
||||
|
||||
const info = node.info ?? {};
|
||||
const type = info.type ?? {};
|
||||
|
||||
return {
|
||||
info: {
|
||||
fileSize: toInt(info.fileSize),
|
||||
fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
|
||||
fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
|
||||
fileName: typeof info.fileName === 'string' ? info.fileName : '',
|
||||
type: {
|
||||
type: toInt(type.type),
|
||||
picFormat: toInt(type.picFormat),
|
||||
videoFormat: toInt(type.videoFormat),
|
||||
voiceFormat: toInt(type.voiceFormat),
|
||||
},
|
||||
width: toInt(info.width),
|
||||
height: toInt(info.height),
|
||||
time: toInt(info.time),
|
||||
original: toInt(info.original),
|
||||
},
|
||||
fileUuid,
|
||||
storeId: toInt(node.storeId),
|
||||
uploadTime: toInt(node.uploadTime),
|
||||
ttl: toInt(node.ttl),
|
||||
subType: toInt(node.subType),
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchNtv2DownloadUrl(
|
||||
bridge: Bridge,
|
||||
serviceCmd: string,
|
||||
oidbCmd: number,
|
||||
payload: Record<string, unknown>,
|
||||
): Promise<string> {
|
||||
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 : '';
|
||||
const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : '';
|
||||
const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : '';
|
||||
|
||||
if (!domain || !path) {
|
||||
throw new Error('ntv2 download response invalid');
|
||||
}
|
||||
return `https://${domain}${path}${rKeyParam}`;
|
||||
}
|
||||
|
||||
// ─────────────── file count ───────────────
|
||||
|
||||
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── upload ───────────────
|
||||
|
||||
export async function uploadGroupFile(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
source: string,
|
||||
name = '',
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileRespSchema },
|
||||
});
|
||||
|
||||
const upload = resp?.upload;
|
||||
if (!upload) throw new Error('group file upload response missing');
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
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)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
}
|
||||
|
||||
export async function uploadPrivateFile(
|
||||
bridge: Bridge,
|
||||
userId: number,
|
||||
source: string,
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await bridge.resolveUserUid(userId);
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (!selfUid) {
|
||||
const selfUin = toInt(bridge.identity.uin);
|
||||
if (selfUin > 0) {
|
||||
selfUid = await bridge.resolveUserUid(selfUin);
|
||||
}
|
||||
}
|
||||
if (!selfUid) throw new Error('self uid is unavailable');
|
||||
|
||||
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 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,
|
||||
},
|
||||
},
|
||||
response: { schema: OidbPrivateFileUploadRespSchema },
|
||||
});
|
||||
|
||||
const upload = resp?.upload;
|
||||
if (!upload) throw new Error('private file upload response missing');
|
||||
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
|
||||
|
||||
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
|
||||
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
|
||||
if (!fileId) throw new Error('private file upload response missing file_id');
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('private file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildPrivateFileUploadExt(
|
||||
senderUin,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
hashes.sha1,
|
||||
fileId,
|
||||
upload.mediaPlatformUploadKey instanceof Uint8Array
|
||||
? upload.mediaPlatformUploadKey
|
||||
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
|
||||
return { fileId, fileHash };
|
||||
}
|
||||
|
||||
// ─────────────── list ───────────────
|
||||
|
||||
export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise<GroupFilesResult> {
|
||||
const targetDirectory = normalizeDirectory(folderId);
|
||||
const files: GroupFileInfo[] = [];
|
||||
const folders: GroupFolderInfo[] = [];
|
||||
|
||||
const pageSize = 20;
|
||||
let startIndex = 0;
|
||||
for (let page = 0; page < 200; page++) {
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileViewRespSchema },
|
||||
});
|
||||
|
||||
const list = resp?.list;
|
||||
if (!list) break;
|
||||
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
|
||||
|
||||
for (const item of list.items ?? []) {
|
||||
const type = toInt(item?.type);
|
||||
if (type === 1 && item?.fileInfo) {
|
||||
const file = item.fileInfo;
|
||||
const uploader = toInt(file.uploaderUin);
|
||||
const cached = bridge.identity.findGroupMember(groupId, uploader);
|
||||
files.push({
|
||||
fileId: typeof file.fileId === 'string' ? file.fileId : '',
|
||||
fileName: typeof file.fileName === 'string' ? file.fileName : '',
|
||||
busId: toInt(file.busId),
|
||||
fileSize: toInt(file.fileSize),
|
||||
uploadTime: toInt(file.uploadedTime),
|
||||
deadTime: toInt(file.expireTime),
|
||||
modifyTime: toInt(file.modifiedTime),
|
||||
downloadTimes: toInt(file.downloadedTimes),
|
||||
uploader,
|
||||
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
});
|
||||
} else if (type === 2 && item?.folderInfo) {
|
||||
const folder = item.folderInfo;
|
||||
const creator = toInt(folder.creatorUin);
|
||||
const cached = bridge.identity.findGroupMember(groupId, creator);
|
||||
folders.push({
|
||||
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
|
||||
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
|
||||
createTime: toInt(folder.createTime),
|
||||
creator,
|
||||
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
totalFileCount: toInt(folder.totalFileCount),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (list.isEnd) break;
|
||||
startIndex += pageSize;
|
||||
}
|
||||
|
||||
return { files, folders };
|
||||
}
|
||||
|
||||
// ─────────────── url fetch (group / private files) ───────────────
|
||||
|
||||
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileRespSchema },
|
||||
});
|
||||
|
||||
const download = resp?.download;
|
||||
if (!download) throw new Error('group file url response missing');
|
||||
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
|
||||
|
||||
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|
||||
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|
||||
|| '';
|
||||
const hexUrl = bytesToHexUpper(download.downloadUrl);
|
||||
if (!dns || !hexUrl) {
|
||||
throw new Error('group file url response invalid');
|
||||
}
|
||||
|
||||
// Keep the same behavior as Lagrange: append file_id after ?fname=
|
||||
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
|
||||
}
|
||||
|
||||
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
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]),
|
||||
},
|
||||
},
|
||||
response: { schema: OidbPrivateFileDownloadRespSchema },
|
||||
});
|
||||
|
||||
const result = resp?.body?.result;
|
||||
const server = typeof result?.server === 'string' ? result.server : '';
|
||||
const port = toInt(result?.port);
|
||||
const url = typeof result?.url === 'string' ? result.url : '';
|
||||
if (!server || !port || !url) {
|
||||
throw new Error('private file url response invalid');
|
||||
}
|
||||
return `http://${server}:${port}${url}&isthumb=0`;
|
||||
}
|
||||
|
||||
// ─────────────── delete / move ───────────────
|
||||
|
||||
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileRespSchema },
|
||||
});
|
||||
|
||||
const result = resp?.delete;
|
||||
if (!result) throw new Error('group file delete response missing');
|
||||
ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording);
|
||||
}
|
||||
|
||||
export async function moveGroupFile(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
fileId: string,
|
||||
parentDirectory: string,
|
||||
targetDirectory: string,
|
||||
): Promise<void> {
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileRespSchema },
|
||||
});
|
||||
|
||||
const result = resp?.move;
|
||||
if (!result) throw new Error('group file move response missing');
|
||||
ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording);
|
||||
}
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileFolderRespSchema },
|
||||
});
|
||||
|
||||
const result = resp?.create;
|
||||
if (!result) throw new Error('group folder create response missing');
|
||||
ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
|
||||
}
|
||||
|
||||
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
|
||||
const resp = await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0x6d7_1',
|
||||
oidbCmd: 0x6D7, subCmd: 1,
|
||||
request: {
|
||||
schema: OidbGroupFileFolderReqSchema,
|
||||
value: {
|
||||
delete: {
|
||||
groupUin: groupId,
|
||||
folderId,
|
||||
},
|
||||
},
|
||||
isUid: true,
|
||||
},
|
||||
response: { schema: OidbGroupFileFolderRespSchema },
|
||||
});
|
||||
|
||||
const result = resp?.delete;
|
||||
if (!result) throw new Error('group folder delete response missing');
|
||||
ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording);
|
||||
}
|
||||
|
||||
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
|
||||
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,
|
||||
},
|
||||
response: { schema: OidbGroupFileFolderRespSchema },
|
||||
});
|
||||
|
||||
const result = resp?.rename;
|
||||
if (!result) throw new Error('group folder rename response missing');
|
||||
ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording);
|
||||
}
|
||||
|
||||
// ─────────────── rich-media URL by node ───────────────
|
||||
|
||||
export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
|
||||
const normalizedNode = normalizeMediaNode(node);
|
||||
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, {
|
||||
reqHead: {
|
||||
common: { requestId: 4, command: 200 },
|
||||
scene: {
|
||||
requestType: 1,
|
||||
businessType: 3,
|
||||
sceneType: 2,
|
||||
group: { groupUin: groupId },
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
download: {
|
||||
node: normalizedNode,
|
||||
download: { video: { busiType: 0, sceneType: 0 } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const normalizedNode = normalizeMediaNode(node);
|
||||
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 200 },
|
||||
scene: {
|
||||
requestType: 1,
|
||||
businessType: 3,
|
||||
sceneType: 1,
|
||||
c2c: {
|
||||
accountType: 2,
|
||||
targetUid: selfUid,
|
||||
},
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
download: {
|
||||
node: normalizedNode,
|
||||
download: { video: { busiType: 0, sceneType: 0 } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
|
||||
const normalizedNode = normalizeMediaNode(node);
|
||||
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 200 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 2,
|
||||
sceneType: 2,
|
||||
group: { groupUin: groupId },
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
download: {
|
||||
node: normalizedNode,
|
||||
download: { video: { busiType: 0, sceneType: 0 } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const normalizedNode = normalizeMediaNode(node);
|
||||
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 200 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 2,
|
||||
sceneType: 1,
|
||||
c2c: {
|
||||
accountType: 2,
|
||||
targetUid: selfUid,
|
||||
},
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
download: {
|
||||
node: normalizedNode,
|
||||
download: { video: { busiType: 0, sceneType: 0 } },
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
// Operations targeting an existing message: recall (group / private),
|
||||
// mark-as-read (group / private), and the "essence" highlight toggle.
|
||||
// All of these take a message identifier and modify server-side state
|
||||
// without producing a downstream observable event.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { protoEncode } from '../../protobuf/decode';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
C2CRecallRequestSchema,
|
||||
GroupRecallRequestSchema,
|
||||
OidbEssenceSchema,
|
||||
SsoReadedReportReqSchema,
|
||||
} from '../proto/oidb-action';
|
||||
|
||||
export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise<void> {
|
||||
const request = protoEncode({
|
||||
type: 1,
|
||||
groupUin: groupId,
|
||||
info: { sequence, random: 0, field3: 0 },
|
||||
settings: { field1: 0 },
|
||||
}, GroupRecallRequestSchema);
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
|
||||
}
|
||||
|
||||
export async function recallPrivateMessage(
|
||||
bridge: Bridge, userUin: number, clientSeq: number,
|
||||
msgSeq: number, random: number, timestamp: number,
|
||||
): Promise<void> {
|
||||
const targetUid = await bridge.resolveUserUid(userUin);
|
||||
const request = protoEncode({
|
||||
type: 1,
|
||||
targetUid,
|
||||
info: {
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
messageId: BigInt((0x01000000 * 0x100000000) + random),
|
||||
timestamp,
|
||||
field5: 0,
|
||||
messageSequence: msgSeq,
|
||||
},
|
||||
settings: { field1: false, field2: false },
|
||||
field6: false,
|
||||
}, C2CRecallRequestSchema);
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
||||
}
|
||||
|
||||
export async function markPrivateMessageRead(
|
||||
bridge: Bridge,
|
||||
userId: number,
|
||||
msgSeq: number,
|
||||
timestamp: number = Math.floor(Date.now() / 1000),
|
||||
): Promise<void> {
|
||||
const uid = await bridge.resolveUserUid(userId);
|
||||
|
||||
const request = protoEncode({
|
||||
c2cList: [
|
||||
{
|
||||
uid,
|
||||
lastReadTime: BigInt(timestamp),
|
||||
lastReadSeq: BigInt(msgSeq),
|
||||
},
|
||||
],
|
||||
}, SsoReadedReportReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function markGroupMessageRead(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
): Promise<void> {
|
||||
const request = protoEncode({
|
||||
groupList: [
|
||||
{
|
||||
groupUin: BigInt(groupId),
|
||||
lastReadSeq: BigInt(msgSeq),
|
||||
},
|
||||
],
|
||||
}, SsoReadedReportReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark group message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
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 runOidb(bridge, {
|
||||
cmd,
|
||||
oidbCmd: 0xEAC, subCmd,
|
||||
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
|
||||
});
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
// Lightweight social-interaction actions: poke, like, emoji reaction,
|
||||
// and the related read-side "who reacted with X" query. None of these
|
||||
// edit message content — they're purely social signals.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
Oidb0x9083ReqSchema,
|
||||
Oidb0x9083RespSchema,
|
||||
OidbGroupReactionSchema,
|
||||
OidbLikeSchema,
|
||||
OidbPokeSchema,
|
||||
} from '../proto/oidb-action';
|
||||
|
||||
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
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 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';
|
||||
// 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(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType: number = 1,
|
||||
count: number = 10,
|
||||
cookie: string = '',
|
||||
): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> {
|
||||
const req = {
|
||||
groupId: BigInt(groupId),
|
||||
sequence,
|
||||
emojiType,
|
||||
emojiId,
|
||||
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
|
||||
field7: 0,
|
||||
count,
|
||||
field12: 1,
|
||||
};
|
||||
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') : '';
|
||||
return { users, cookie: respCookie, isLast: !respCookie };
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
// Grab-bag: action verbs that don't share a theme with anything else.
|
||||
// Kept together so the directory stays small; if any of these grow new
|
||||
// related siblings, lift the whole group out into its own file.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { protoDecode, protoEncode } from '../../protobuf/decode';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
MiniAppShareReqSchema,
|
||||
MiniAppShareRespSchema,
|
||||
Oidb0x112eReqSchema,
|
||||
Oidb0x112eRespSchema,
|
||||
Oidb0x990ReqSchema,
|
||||
Oidb0x990RespSchema,
|
||||
Oidb0xeb7ReqSchema,
|
||||
Oidb0xeb7RespSchema,
|
||||
} from '../proto/oidb-action';
|
||||
|
||||
export async function translateEn2Zh(
|
||||
bridge: Bridge,
|
||||
words: string[],
|
||||
) {
|
||||
const req = {
|
||||
translateReq: {
|
||||
srcLang: 'en',
|
||||
dstLang: 'zh',
|
||||
words: words,
|
||||
},
|
||||
tag10: 1,
|
||||
tag12: 1,
|
||||
};
|
||||
|
||||
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) {
|
||||
throw new Error('translate response empty');
|
||||
}
|
||||
|
||||
return resp.dstWords || [];
|
||||
}
|
||||
|
||||
export async function getMiniAppArk(
|
||||
bridge: Bridge,
|
||||
type: string,
|
||||
title: string,
|
||||
desc: string,
|
||||
picUrl: string,
|
||||
jumpUrl: string,
|
||||
) {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
if (type === 'weibo') {
|
||||
appid = '1109224783';
|
||||
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
} else if (type !== 'bili') {
|
||||
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
|
||||
}
|
||||
|
||||
const request = protoEncode({
|
||||
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
|
||||
body: {
|
||||
appid,
|
||||
title,
|
||||
desc,
|
||||
picUrl,
|
||||
jumpUrl,
|
||||
iconUrl,
|
||||
},
|
||||
}, MiniAppShareReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
|
||||
|
||||
if (!result.success || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'get mini app ark failed');
|
||||
}
|
||||
|
||||
const decoded = protoDecode(result.responseData, MiniAppShareRespSchema);
|
||||
const jsonStr = decoded?.body?.jsonStr;
|
||||
|
||||
if (!jsonStr) {
|
||||
throw new Error('mini app share json empty');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr);
|
||||
|
||||
return {
|
||||
data: {
|
||||
ver: parsed.ver,
|
||||
prompt: parsed.prompt,
|
||||
config: parsed.config,
|
||||
app: parsed.appName,
|
||||
view: parsed.appView,
|
||||
meta: parsed.metaData,
|
||||
miniappShareOrigin: 3,
|
||||
miniappOpenRefer: '10002',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function clickInlineKeyboardButton(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
botAppid: number,
|
||||
buttonId: string,
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
) {
|
||||
const req = {
|
||||
botAppid: BigInt(botAppid),
|
||||
msgSeq: BigInt(msgSeq),
|
||||
buttonId: String(buttonId),
|
||||
callbackData: String(callbackData || ''),
|
||||
unknown7: 0,
|
||||
groupId: BigInt(groupId),
|
||||
unknown9: 1,
|
||||
};
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
return {
|
||||
result: Number(result.result || 0),
|
||||
errMsg: result.errMsg || '',
|
||||
status: 0,
|
||||
promptText: result.promptText || '',
|
||||
promptType: 0,
|
||||
promptIcon: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function sendGroupSign(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
) {
|
||||
const req = {
|
||||
signInInfo: {
|
||||
uin: String(bridge.identity.uin),
|
||||
groupId: String(groupId),
|
||||
version: '9.0.90',
|
||||
},
|
||||
};
|
||||
|
||||
await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xEB7_1',
|
||||
oidbCmd: 0xEB7, subCmd: 1,
|
||||
request: { schema: Oidb0xeb7ReqSchema, value: req },
|
||||
response: { schema: Oidb0xeb7RespSchema },
|
||||
});
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
// Operations that touch the bot's own profile / status, plus the
|
||||
// related queries about my profile likes and unidirectional friends.
|
||||
// All of these read/write fields on the self-uin via OIDB.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { protoDecode, protoEncode } from '../../protobuf/decode';
|
||||
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,
|
||||
Oidb0x7edRespSchema,
|
||||
Oidb0xcd4ReqSchema,
|
||||
Oidb0xcd4RespSchema,
|
||||
Oidb0xe17ReqSchema,
|
||||
Oidb0xe17RespSchema,
|
||||
OidbSetProfileSchema,
|
||||
SetStatusReqSchema,
|
||||
SetStatusRespSchema,
|
||||
} from '../proto/oidb-action';
|
||||
import { resolveSelfUid } from './shared';
|
||||
|
||||
// ─────────────── status / profile setters ───────────────
|
||||
|
||||
export async function setOnlineStatus(
|
||||
bridge: Bridge,
|
||||
status: number,
|
||||
extStatus: number = 0,
|
||||
batteryStatus: number = 100,
|
||||
): Promise<void> {
|
||||
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);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protoDecode(result.responseData, SetStatusRespSchema);
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
if (resp.errCode !== undefined && resp.errCode !== 0) {
|
||||
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function setProfile(
|
||||
bridge: Bridge,
|
||||
nickname?: string,
|
||||
personalNote?: string,
|
||||
): Promise<void> {
|
||||
const uin = BigInt(bridge.identity.uin);
|
||||
const stringProfiles: any[] = [];
|
||||
const intProfiles: any[] = [];
|
||||
|
||||
if (nickname !== undefined) {
|
||||
stringProfiles.push({ fieldId: 20002, value: nickname });
|
||||
}
|
||||
|
||||
if (personalNote !== undefined) {
|
||||
stringProfiles.push({ fieldId: 102, value: personalNote });
|
||||
}
|
||||
|
||||
if (stringProfiles.length === 0 && intProfiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const req = {
|
||||
uin,
|
||||
stringProfiles,
|
||||
};
|
||||
|
||||
await runOidb(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0x112a_2',
|
||||
oidbCmd: 0x112A, subCmd: 2,
|
||||
request: { schema: OidbSetProfileSchema, value: req },
|
||||
});
|
||||
}
|
||||
|
||||
export async function setSelfLongNick(
|
||||
bridge: Bridge,
|
||||
longNick: string,
|
||||
) {
|
||||
const req = {
|
||||
uin: BigInt(bridge.identity.uin),
|
||||
profile: {
|
||||
tag: 102,
|
||||
value: String(longNick),
|
||||
},
|
||||
};
|
||||
|
||||
await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0x112a_2',
|
||||
oidbCmd: 0x112A, subCmd: 2,
|
||||
request: { schema: Oidb0x112aReqSchema, value: req },
|
||||
response: { schema: Oidb0x112aRespSchema },
|
||||
});
|
||||
}
|
||||
|
||||
export async function setInputStatus(
|
||||
bridge: Bridge,
|
||||
userId: number,
|
||||
eventType: number,
|
||||
) {
|
||||
const targetUid = await bridge.resolveUserUid(userId);
|
||||
|
||||
if (!targetUid) {
|
||||
throw new Error('target uid not found');
|
||||
}
|
||||
|
||||
const req = {
|
||||
reqBody: {
|
||||
uid: targetUid,
|
||||
chatType: 0,
|
||||
eventType: eventType,
|
||||
},
|
||||
};
|
||||
|
||||
await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xcd4_1',
|
||||
oidbCmd: 0xCD4, subCmd: 1,
|
||||
request: { schema: Oidb0xcd4ReqSchema, value: req },
|
||||
response: { schema: Oidb0xcd4RespSchema },
|
||||
});
|
||||
}
|
||||
|
||||
export async function setAvatar(
|
||||
bridge: Bridge,
|
||||
source: string,
|
||||
): Promise<void> {
|
||||
const loaded = await loadBinarySource(source, 'avatar');
|
||||
if (!loaded.bytes.length) throw new Error('avatar file is empty');
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
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(
|
||||
bridge: Bridge,
|
||||
userId?: number,
|
||||
start: number = 0,
|
||||
limit: number = 10,
|
||||
) {
|
||||
const isSelf = !userId;
|
||||
const targetUid = isSelf
|
||||
? await resolveSelfUid(bridge)
|
||||
: await bridge.resolveUserUid(userId);
|
||||
|
||||
if (!targetUid) {
|
||||
throw new Error('target uid not found');
|
||||
}
|
||||
|
||||
const req = {
|
||||
targetUid: targetUid,
|
||||
basic: 1,
|
||||
vote: 1,
|
||||
favorite: 1,
|
||||
start: start,
|
||||
limit: limit,
|
||||
};
|
||||
|
||||
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) {
|
||||
throw new Error('get profile like info empty');
|
||||
}
|
||||
|
||||
return {
|
||||
uid: data.uid,
|
||||
time: Number(data.time),
|
||||
favoriteInfo: {
|
||||
total_count: data.favoriteInfo?.totalCount || 0,
|
||||
last_time: Number(data.favoriteInfo?.lastTime || 0),
|
||||
today_count: data.favoriteInfo?.newCount || 0,
|
||||
userInfos: [],
|
||||
},
|
||||
voteInfo: {
|
||||
total_count: data.voteInfo?.totalCount || 0,
|
||||
new_count: data.voteInfo?.newCount || 0,
|
||||
new_nearby_count: 0,
|
||||
last_visit_time: Number(data.voteInfo?.lastTime || 0),
|
||||
userInfos: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getUnidirectionalFriendList(
|
||||
bridge: Bridge,
|
||||
) {
|
||||
const reqObj = {
|
||||
uint64_uin: String(bridge.identity.uin),
|
||||
uint64_top: 0,
|
||||
uint32_req_num: 99,
|
||||
bytes_cookies: '',
|
||||
};
|
||||
|
||||
const req = {
|
||||
jsonBody: JSON.stringify(reqObj),
|
||||
};
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(result.jsonBody);
|
||||
return parsed.rpt_block_list || [];
|
||||
}
|
||||
|
||||
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.identity.uin),
|
||||
field3: 1,
|
||||
field6: 1,
|
||||
};
|
||||
const request = protoEncode(req, FaceroamOpReqSchema);
|
||||
const result = await bridge.sendRawPacket('Faceroam.OpReq', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'fetch custom face failed');
|
||||
}
|
||||
const resp = protoDecode(result.responseData, FaceroamOpRespSchema);
|
||||
if (!resp || (resp as any).retCode !== 0) {
|
||||
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.identity.uin}/${id}/0`);
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
// Contact / info-fetching operations extracted from Bridge.
|
||||
|
||||
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 { runOidb } from './bridge-oidb';
|
||||
import {
|
||||
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
|
||||
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
|
||||
OidbSvcTrpcTcp0xFE7_3ResponseSchema,
|
||||
OidbSvcTrpcTcp0x10C0ResponseSchema,
|
||||
} from './proto/oidb';
|
||||
import {
|
||||
OidbFriendListRequestSchema,
|
||||
OidbGroupListRequestSchema,
|
||||
OidbGroupMemberListRequestSchema,
|
||||
OidbUserInfoRequestSchema,
|
||||
OidbUserInfoResponseSchema,
|
||||
AvatarInfoSchema,
|
||||
OidbGroupRequestListSchema,
|
||||
NTV2RichMediaReqSchema,
|
||||
NTV2RichMediaRespSchema,
|
||||
} from './proto/oidb-action';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function buildFriendProperties(raw: any): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
for (const additional of raw.additional ?? []) {
|
||||
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
|
||||
for (const property of additional.layer1.properties ?? []) {
|
||||
props.set(property.code ?? 0, property.value ?? '');
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
export function permissionToRole(permission: number): string {
|
||||
switch (permission) {
|
||||
case 1: return 'owner';
|
||||
case 2: return 'admin';
|
||||
default: return 'member';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Friend list
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
|
||||
do {
|
||||
const body: any = {
|
||||
friendCount: 300,
|
||||
field4: 0,
|
||||
field6: 1,
|
||||
field7: 0x7FFFFFFF,
|
||||
body: [
|
||||
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||
],
|
||||
field10002: [13578, 13579, 13573, 13572, 13568],
|
||||
field10003: 4051,
|
||||
};
|
||||
if (nextUin !== null) {
|
||||
body.nextUin = { uin: nextUin };
|
||||
}
|
||||
|
||||
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) {
|
||||
const props = buildFriendProperties(raw);
|
||||
friends.push({
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
nextUin = resp?.next?.uin ?? null;
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
|
||||
bridge.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Group list
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
const allTrue = true;
|
||||
const body = {
|
||||
config: {
|
||||
config1: {
|
||||
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
|
||||
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
|
||||
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
|
||||
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
|
||||
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
|
||||
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
|
||||
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
|
||||
},
|
||||
config2: {
|
||||
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
|
||||
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
};
|
||||
|
||||
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) {
|
||||
for (const raw of resp.groups) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
});
|
||||
}
|
||||
}
|
||||
bridge.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Group member list
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
|
||||
do {
|
||||
const body: any = {
|
||||
groupUin: groupId,
|
||||
field2: 5,
|
||||
field3: 2,
|
||||
body: {
|
||||
memberName: true, memberCard: true, level: true, field13: true,
|
||||
field16: true, specialTitle: true, field18: true, field20: true,
|
||||
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
|
||||
shutUpTimestamp: true, field103: true, field104: true, field105: true,
|
||||
field106: true, permission: true, field200: true, field201: true,
|
||||
},
|
||||
};
|
||||
if (token) body.token = token;
|
||||
|
||||
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) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
token = resp?.token ?? '';
|
||||
} while (token);
|
||||
|
||||
bridge.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// User profile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
|
||||
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
|
||||
const body = {
|
||||
uin,
|
||||
field2: 0,
|
||||
keys: keys.map(k => ({ key: k })),
|
||||
};
|
||||
|
||||
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');
|
||||
|
||||
const info: UserProfileInfo = {
|
||||
uin: resp.body.uin ?? uin,
|
||||
uid: resp.body.uid ?? '',
|
||||
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
||||
};
|
||||
|
||||
if (resp.body.properties) {
|
||||
const bytesMap = new Map<number, Uint8Array>();
|
||||
const numMap = new Map<number, number>();
|
||||
for (const bp of resp.body.properties.bytesProperties ?? []) {
|
||||
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
|
||||
}
|
||||
for (const np of resp.body.properties.numberProperties ?? []) {
|
||||
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
|
||||
}
|
||||
|
||||
const getString = (code: number) => {
|
||||
const b = bytesMap.get(code);
|
||||
return b ? Buffer.from(b).toString('utf8') : '';
|
||||
};
|
||||
|
||||
info.nickname = getString(20002);
|
||||
info.remark = getString(103);
|
||||
info.qid = getString(27394);
|
||||
info.sign = getString(102);
|
||||
|
||||
const avatarBytes = bytesMap.get(101);
|
||||
if (avatarBytes) {
|
||||
const av = protoDecode(avatarBytes, AvatarInfoSchema);
|
||||
if (av?.url) info.avatar = av.url + '640';
|
||||
}
|
||||
|
||||
const sexNum = numMap.get(20009) ?? 0;
|
||||
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
|
||||
info.age = numMap.get(20037) ?? 0;
|
||||
}
|
||||
|
||||
bridge.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Group requests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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 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 ?? []) {
|
||||
requests.push({
|
||||
groupId: raw.group?.groupUin ?? 0,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid: raw.target?.uid ?? '',
|
||||
targetUin: 0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid: raw.invitor?.uid ?? '',
|
||||
invitorUin: 0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid: raw.operatorUser?.uid ?? '',
|
||||
operatorUin: 0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence: Number(raw.sequence ?? 0),
|
||||
state: raw.state ?? 0,
|
||||
eventType: raw.eventType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
});
|
||||
}
|
||||
bridge.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Download RKeys
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyInfo[]> {
|
||||
const PRIVATE_IMAGE = 10;
|
||||
const GROUP_IMAGE = 20;
|
||||
const FALLBACK_IMAGE = 2;
|
||||
|
||||
const body = {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 202 },
|
||||
scene: { requestType: 2, businessType: 1, sceneType: 0 },
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
downloadRkey: {
|
||||
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
|
||||
},
|
||||
};
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
for (const entry of resp?.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
if (rkey && type) {
|
||||
result.push({
|
||||
rkey,
|
||||
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
|
||||
storeId: entry.storeId ?? 0,
|
||||
createTime: entry.rkeyCreateTime ?? 0,
|
||||
type,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
// 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 }>;
|
||||
|
||||
// ─── Forward ───
|
||||
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: 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>;
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
// 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';
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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');
|
||||
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) throwIfOidbError(resp);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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 ?? ''}`);
|
||||
}
|
||||
}
|
||||
@@ -1,575 +0,0 @@
|
||||
// Bridge — per-UIN session: handler registration, packet dispatch, event routing.
|
||||
// Supports packet sending via native addon.
|
||||
// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions.
|
||||
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
|
||||
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
|
||||
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,
|
||||
SendMessageResponseSchema,
|
||||
} from './proto/action';
|
||||
|
||||
// Delegated modules
|
||||
import {
|
||||
fetchFriendList as fetchFriendList_,
|
||||
fetchGroupList as fetchGroupList_,
|
||||
fetchGroupMemberList as fetchGroupMemberList_,
|
||||
fetchUserProfile as fetchUserProfile_,
|
||||
fetchGroupRequests as fetchGroupRequests_,
|
||||
fetchDownloadRKeys as fetchDownloadRKeys_,
|
||||
} from './bridge-contacts';
|
||||
import type { WebHonorType } from './web/group-honor';
|
||||
import {
|
||||
muteGroupMember as muteGroupMember_,
|
||||
muteGroupAll as muteGroupAll_,
|
||||
setGroupAddOption as setGroupAddOption_,
|
||||
setGroupSearch as setGroupSearch_,
|
||||
setGroupAddRequest as setGroupAddRequest_,
|
||||
kickGroupMember as kickGroupMember_,
|
||||
kickGroupMembers as kickGroupMembers_,
|
||||
leaveGroup as leaveGroup_,
|
||||
setGroupAdmin as setGroupAdmin_,
|
||||
setGroupCard as setGroupCard_,
|
||||
setGroupName as setGroupName_,
|
||||
setGroupSpecialTitle as setGroupSpecialTitle_,
|
||||
setGroupRemark as setGroupRemark_,
|
||||
getGroupAtAllRemain as getGroupAtAllRemain_,
|
||||
} from './actions/group-admin';
|
||||
import {
|
||||
uploadGroupFile as uploadGroupFile_,
|
||||
uploadPrivateFile as uploadPrivateFile_,
|
||||
fetchGroupFiles as fetchGroupFiles_,
|
||||
fetchGroupFileUrl as fetchGroupFileUrl_,
|
||||
fetchPrivateFileUrl as fetchPrivateFileUrl_,
|
||||
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
|
||||
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
|
||||
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
|
||||
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
|
||||
deleteGroupFile as deleteGroupFile_,
|
||||
moveGroupFile as moveGroupFile_,
|
||||
createGroupFileFolder as createGroupFileFolder_,
|
||||
deleteGroupFileFolder as deleteGroupFileFolder_,
|
||||
renameGroupFileFolder as renameGroupFileFolder_,
|
||||
fetchGroupFileCount as fetchGroupFileCount_,
|
||||
} from './actions/group-file';
|
||||
import {
|
||||
recallGroupMessage as recallGroupMessage_,
|
||||
recallPrivateMessage as recallPrivateMessage_,
|
||||
markPrivateMessageRead as markGroupMsgAsRead_,
|
||||
markGroupMessageRead as markPrivateMsgAsRead_,
|
||||
setGroupEssence as setGroupEssence_,
|
||||
} from './actions/group-message';
|
||||
import {
|
||||
sendPoke as sendPoke_,
|
||||
sendLike as sendLike_,
|
||||
setGroupReaction as setGroupReaction_,
|
||||
getEmojiLikes as getEmojiLikes_,
|
||||
} from './actions/interaction';
|
||||
import {
|
||||
uploadForwardNodes as uploadForwardNodes_,
|
||||
fetchForwardNodes as fetchForwardNodes_,
|
||||
} from './actions/forward';
|
||||
import {
|
||||
setFriendAddRequest as setFriendAddRequest_,
|
||||
deleteFriend as deleteFriend_,
|
||||
setFriendRemark as setFriendRemark_,
|
||||
} 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_,
|
||||
} from './actions/profile';
|
||||
import {
|
||||
translateEn2Zh as translateEn2Zh_,
|
||||
getMiniAppArk as getMiniAppArk_,
|
||||
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_,
|
||||
getGroupEssence as getGroupEssence_,
|
||||
getGroupEssenceAll as getGroupEssenceAll_,
|
||||
sendGroupNotice as sendGroupNotice_,
|
||||
getGroupNotice as getGroupNotice_,
|
||||
deleteGroupNoticeByFid as deleteGroupNotice_,
|
||||
getCookiesStr as getCookiesStr_,
|
||||
getCsrfToken as getCsrfToken_,
|
||||
getCredentials as getCredentials_,
|
||||
} from './web-actions';
|
||||
import type { GroupFilesResult } from './actions/group-file';
|
||||
import type { MediaIndexNode } from './actions/shared';
|
||||
import { BridgeEventBus } from './event-bus';
|
||||
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
sequence: number;
|
||||
clientSequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
storeId: number;
|
||||
createTime: number;
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
expireTime: string;
|
||||
keyIndex: string
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
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 the pipeline fans out in parallel.
|
||||
*/
|
||||
readonly events = new BridgeEventBus();
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
private packetClient_: PacketSender | null = null;
|
||||
// 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
|
||||
// get_group_member_info(no_cache=true) per inbound message) would
|
||||
// trigger one OIDB 0xfe7_3 per chat message per group; sustained rate
|
||||
// (>1k/h) is detected by Tencent risk-control and gets the account
|
||||
// banned for 7 days.
|
||||
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch_ = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
|
||||
// Sequence and random generators for outgoing messages
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
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);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.identity.close();
|
||||
this.events.clear();
|
||||
}
|
||||
|
||||
setPacketClient(client: PacketSender): void {
|
||||
this.packetClient_ = client;
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
this.pipeline.registerCmd(cmd, parser);
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.pipeline.handlesCmd(cmd);
|
||||
}
|
||||
|
||||
// --- PID management ---
|
||||
|
||||
attachPid(pid: number): void {
|
||||
this.pids_.add(pid);
|
||||
}
|
||||
detachPid(pid: number): void {
|
||||
this.pids_.delete(pid);
|
||||
}
|
||||
hasPid(pid: number): boolean { return this.pids_.has(pid); }
|
||||
get empty(): boolean { return this.pids_.size === 0; }
|
||||
get activePid(): number | null {
|
||||
for (const pid of this.pids_) return pid;
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Packet dispatch ---
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
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.identity.findGroup(groupId)) return false;
|
||||
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- Sequence / random generators ---
|
||||
|
||||
private nextClientSequence(): number {
|
||||
return ++this.clientSeq_;
|
||||
}
|
||||
|
||||
private nextMessageRandom(): number {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
|
||||
// --- Send packet (raw) ---
|
||||
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
}
|
||||
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
}
|
||||
|
||||
// --- Send message (high-level) ---
|
||||
|
||||
async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this, groupId });
|
||||
const random = this.nextMessageRandom();
|
||||
|
||||
const request = protoEncode({
|
||||
routingHead: {
|
||||
grp: { groupCode: BigInt(groupId) },
|
||||
} as any,
|
||||
contentHead: {
|
||||
type: 1,
|
||||
} as any,
|
||||
messageBody: {
|
||||
richText: {
|
||||
elems: protoElems,
|
||||
},
|
||||
} as any,
|
||||
clientSequence: 0,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
multiSendSeq: 0,
|
||||
}, SendMessageRequestSchema);
|
||||
|
||||
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
|
||||
const response = protoDecode(result.responseData, SendMessageResponseSchema);
|
||||
if (!response) {
|
||||
throw new Error('failed to decode SendMessageResponse');
|
||||
}
|
||||
if (response.result !== undefined && response.result !== 0) {
|
||||
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const seq = response.groupSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
|
||||
return {
|
||||
messageId,
|
||||
sequence: seq,
|
||||
clientSequence: 0,
|
||||
random,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
// Resolve UID for media upload and the final c2c routing head.
|
||||
let userUid = '';
|
||||
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
||||
if (hasMedia) {
|
||||
userUid = await this.resolveUserUid(userUin);
|
||||
}
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this, userUid });
|
||||
const random = this.nextMessageRandom();
|
||||
const clientSeq = this.nextClientSequence();
|
||||
|
||||
const request = protoEncode({
|
||||
routingHead: {
|
||||
c2c: {
|
||||
uin: userUin,
|
||||
...(userUid ? { uid: userUid } : {}),
|
||||
},
|
||||
} as any,
|
||||
contentHead: {
|
||||
type: 1,
|
||||
subType: 0,
|
||||
c2cCmd: 11,
|
||||
} as any,
|
||||
messageBody: {
|
||||
richText: {
|
||||
elems: protoElems,
|
||||
},
|
||||
} as any,
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
ctrl: {
|
||||
msgFlag: Math.floor(Date.now() / 1000),
|
||||
} as any,
|
||||
multiSendSeq: 0,
|
||||
}, SendMessageRequestSchema);
|
||||
|
||||
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
|
||||
const response = protoDecode(result.responseData, SendMessageResponseSchema);
|
||||
if (!response) {
|
||||
throw new Error('failed to decode SendMessageResponse');
|
||||
}
|
||||
if (response.result !== undefined && response.result !== 0) {
|
||||
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const seq = response.privateSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
|
||||
return {
|
||||
messageId,
|
||||
sequence: seq,
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Delegated: OIDB helpers ---
|
||||
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
|
||||
// --- Delegated: Contact / info queries ---
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
|
||||
async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
|
||||
const kMemberListTtlMs = 60_000;
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch_.get(groupId);
|
||||
if (!options.force && last && now - last.at < kMemberListTtlMs) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight_.get(groupId);
|
||||
if (inflight) return inflight;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const data = await fetchGroupMemberList_(this, groupId);
|
||||
this.memberListLastFetch_.set(groupId, { at: Date.now(), data });
|
||||
return data;
|
||||
} finally {
|
||||
this.memberListInflight_.delete(groupId);
|
||||
}
|
||||
})();
|
||||
this.memberListInflight_.set(groupId, task);
|
||||
return task;
|
||||
}
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> { return fetchUserProfile_(this, uin); }
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> { return fetchGroupRequests_(this, filtered); }
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> { return fetchDownloadRKeys_(this); }
|
||||
|
||||
// --- Delegated: Admin / action methods ---
|
||||
|
||||
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
|
||||
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
|
||||
async setGroupAddOption(groupId: number, addType: number): Promise<void> { return setGroupAddOption_(this, groupId, addType); }
|
||||
async setGroupSearch(groupId: number): Promise<void> { return setGroupSearch_(this, groupId); }
|
||||
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
|
||||
async kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> { return kickGroupMembers_(this, groupId, userIds, reject); }
|
||||
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
|
||||
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
|
||||
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
|
||||
async setGroupName(groupId: number, name: string): Promise<void> { return setGroupName_(this, groupId, name); }
|
||||
async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void> { return setGroupSpecialTitle_(this, groupId, userId, title); }
|
||||
async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void> { return setFriendAddRequest_(this, uidOrFlag, approve); }
|
||||
async deleteFriend(userId: number, block = false): Promise<void> { return deleteFriend_(this, userId, block); }
|
||||
async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> {
|
||||
return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile);
|
||||
}
|
||||
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
|
||||
return uploadPrivateFile_(this, userId, file, name, uploadFile);
|
||||
}
|
||||
async fetchGroupFiles(groupId: number, folderId = '/'): Promise<GroupFilesResult> { return fetchGroupFiles_(this, groupId, folderId); }
|
||||
async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise<string> { return fetchGroupFileUrl_(this, groupId, fileId, busId); }
|
||||
async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
|
||||
async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupPttUrlByNode_(this, groupId, node); }
|
||||
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
|
||||
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
|
||||
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
|
||||
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId, userId); }
|
||||
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
|
||||
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
|
||||
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
|
||||
async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise<void> { return createGroupFileFolder_(this, groupId, name, parentId); }
|
||||
async deleteGroupFileFolder(groupId: number, folderId: string): Promise<void> { return deleteGroupFileFolder_(this, groupId, folderId); }
|
||||
async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); }
|
||||
async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise<void> { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); }
|
||||
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { return sendPoke_(this, isGroup, peerUin, targetUin); }
|
||||
async sendLike(userId: number, count: number): Promise<void> { return sendLike_(this, userId, count); }
|
||||
async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { return setGroupEssence_(this, groupId, sequence, random, enable); }
|
||||
async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { return setGroupReaction_(this, groupId, sequence, code, isSet); }
|
||||
async recallGroupMessage(groupId: number, sequence: number): Promise<void> { return recallGroupMessage_(this, groupId, sequence); }
|
||||
async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void> { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); }
|
||||
async markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
|
||||
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 getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
|
||||
return getGroupHonorInfo_(this, groupId, type);
|
||||
}
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this)}
|
||||
async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise<any> {
|
||||
return getGroupEssence_(this, groupId, pageStart, pageLimit);
|
||||
}
|
||||
|
||||
async getGroupEssenceAll(groupId: number): Promise<any> {
|
||||
return getGroupEssenceAll_(this, groupId);
|
||||
}
|
||||
|
||||
async sendGroupNotice(groupId: number, content: string, options?: any) {
|
||||
return sendGroupNotice_(this, groupId, content, options);
|
||||
}
|
||||
|
||||
async getGroupNotice(groupId: number) {
|
||||
return getGroupNotice_(this, groupId);
|
||||
}
|
||||
|
||||
async deleteGroupNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
return deleteGroupNotice_(this, groupId, fid);
|
||||
}
|
||||
|
||||
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||
|
||||
async getGroupAtAllRemain(groupId: number) {
|
||||
return getGroupAtAllRemain_(this, groupId);
|
||||
}
|
||||
// extend
|
||||
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);
|
||||
}
|
||||
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
|
||||
async getCsrfToken(): Promise<number> { return getCsrfToken_(this); }
|
||||
async getCredentials(domain: string) { return getCredentials_(this, domain); }
|
||||
async getProfileLike(userId?: number, start?: number, limit?: number) {
|
||||
return getProfileLike_(this, userId, start, limit);
|
||||
}
|
||||
async getUnidirectionalFriendList() {
|
||||
return getUnidirectionalFriendList_(this);
|
||||
}
|
||||
async setSelfLongNick(longNick: string) {
|
||||
return setSelfLongNick_(this, longNick);
|
||||
}
|
||||
async setInputStatus(userId: number, eventType: number) {
|
||||
return setInputStatus_(this, userId, eventType);
|
||||
}
|
||||
async translateEn2Zh(words: string[]) {
|
||||
return translateEn2Zh_(this, words);
|
||||
}
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
|
||||
return getMiniAppArk_(this, type, title, desc, picUrl, jumpUrl);
|
||||
}
|
||||
async clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) {
|
||||
return clickInlineKeyboardButton_(this, groupId, botAppid, buttonId, callbackData, msgSeq);
|
||||
}
|
||||
async sendGroupSign(groupId: number) {
|
||||
return sendGroupSign_(this, groupId);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
// --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) ---
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
// BridgeManager — manages per-UIN Bridge sessions.
|
||||
// onPacket() is the single entry point for parsed hook packets;
|
||||
// HookManager wires it as the default packet sink for every HookSession.
|
||||
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
|
||||
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import { Bridge } from './bridge';
|
||||
import { IdentityService } from './identity-service';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
|
||||
interface QQSession {
|
||||
bridge: Bridge;
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class BridgeManager {
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
private pidPacketClients_ = new Map<number, PacketSender>();
|
||||
|
||||
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||
|
||||
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
this.pidPacketClients_.delete(pid);
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return;
|
||||
|
||||
this.pidToUin_.delete(pid);
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session) return;
|
||||
|
||||
session.bridge.detachPid(pid);
|
||||
if (session.bridge.empty) {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||
session.bridge.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!BridgeManager.isRealUin(uin)) return;
|
||||
|
||||
this.pidPacketClients_.set(pid, packetClient);
|
||||
|
||||
const { session, created } = this.ensureSession(uin);
|
||||
session.bridge.attachPid(pid);
|
||||
session.bridge.setPacketClient(packetClient);
|
||||
this.pidToUin_.set(pid, uin);
|
||||
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
|
||||
const uin = pkt.uin;
|
||||
|
||||
// Ensure session exists
|
||||
const { session, created } = this.ensureSession(uin);
|
||||
|
||||
// Attach PID if known
|
||||
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
|
||||
session.bridge.attachPid(pkt.pid);
|
||||
this.pidToUin_.set(pkt.pid, uin);
|
||||
|
||||
const client = this.pidPacketClients_.get(pkt.pid);
|
||||
if (client) session.bridge.setPacketClient(client);
|
||||
}
|
||||
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge
|
||||
session.bridge.onPacket(pkt);
|
||||
}
|
||||
|
||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||
let session = this.sessions_.get(uin);
|
||||
if (session) return { session, created: false };
|
||||
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin));
|
||||
session = { bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Each downstream consumer (e.g. OneBotInstance) subscribes to
|
||||
// `bridge.events` directly via the per-kind bus — there is no longer a
|
||||
// generic firehose to wire here.
|
||||
return { session, created: true };
|
||||
}
|
||||
|
||||
getSession(uin: string): QQSession | null {
|
||||
return this.sessions_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get sessions(): Map<string, { bridge: Bridge }> {
|
||||
return this.sessions_;
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// 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';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
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);
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
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];
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// 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,
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
// Proto schemas for outgoing message actions.
|
||||
// Port of src/bridge/include/bridge/proto/action.h
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
import { ElemSchema } from './element';
|
||||
|
||||
// --- Routing ---
|
||||
|
||||
export const RoutingC2CSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RoutingGroupSchema = {
|
||||
groupCode: { field: 1, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RoutingHeadSchema = {
|
||||
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
|
||||
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Content Head (for send) ---
|
||||
|
||||
export const SendContentHeadSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
subType: { field: 2, type: 'uint32' as const },
|
||||
c2cCmd: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Message Control ---
|
||||
|
||||
export const MessageControlSchema = {
|
||||
msgFlag: { field: 1, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- RichText (for send — only elems) ---
|
||||
|
||||
export const SendRichTextSchema = {
|
||||
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- MessageBody (for send) ---
|
||||
|
||||
export const SendMessageBodySchema = {
|
||||
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- SendMessageRequest ---
|
||||
|
||||
export const SendMessageRequestSchema = {
|
||||
routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema },
|
||||
contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema },
|
||||
messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema },
|
||||
clientSequence: { field: 4, type: 'uint32' as const },
|
||||
random: { field: 5, type: 'uint32' as const },
|
||||
syncCookie: { field: 6, type: 'bytes' as const },
|
||||
via: { field: 8, type: 'uint32' as const },
|
||||
dataStatist: { field: 9, type: 'uint32' as const },
|
||||
ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema },
|
||||
multiSendSeq: { field: 14, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- SendMessageResponse ---
|
||||
|
||||
export const SendMessageResponseSchema = {
|
||||
result: { field: 1, type: 'int32' as const },
|
||||
errMsg: { field: 2, type: 'string' as const },
|
||||
timestamp1: { field: 3, type: 'uint32' as const },
|
||||
field10: { field: 10, type: 'uint32' as const },
|
||||
groupSequence: { field: 11, type: 'uint32' as const },
|
||||
timestamp2: { field: 12, type: 'uint32' as const },
|
||||
privateSequence: { field: 14, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- MentionExtra (for building @mention text element) ---
|
||||
|
||||
export const MentionExtraSendSchema = {
|
||||
type: { field: 3, type: 'int32' as const },
|
||||
uin: { field: 4, type: 'uint32' as const },
|
||||
field5: { field: 5, type: 'int32' as const },
|
||||
uid: { field: 9, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- MarkdownData ---
|
||||
|
||||
export const MarkdownDataSchema = {
|
||||
content: { field: 1, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -1,418 +0,0 @@
|
||||
// Proto schemas for QQ message elements.
|
||||
// Port of src/bridge/include/bridge/proto/element.h
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
|
||||
// --- Nested / helper schemas ---
|
||||
|
||||
export const CustomFacePbReserveSchema = {
|
||||
subType: { field: 1, type: 'int32' as const },
|
||||
summary: { field: 9, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NotOnlineImagePbReserve2Schema = {
|
||||
field1: { field: 1, type: 'int32' as const },
|
||||
field2: { field: 2, type: 'string' as const },
|
||||
field3: { field: 3, type: 'int32' as const },
|
||||
field4: { field: 4, type: 'int32' as const },
|
||||
field5: { field: 5, type: 'int32' as const },
|
||||
field7: { field: 7, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NotOnlineImagePbReserveSchema = {
|
||||
subType: { field: 1, type: 'int32' as const },
|
||||
field3: { field: 3, type: 'int32' as const },
|
||||
field4: { field: 4, type: 'int32' as const },
|
||||
summary: { field: 8, type: 'string' as const },
|
||||
field10: { field: 10, type: 'int32' as const },
|
||||
field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema },
|
||||
url: { field: 30, type: 'string' as const },
|
||||
md5Str: { field: 31, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Core element schemas ---
|
||||
|
||||
export const TextElemSchema = {
|
||||
str: { field: 1, type: 'string' as const },
|
||||
link: { field: 2, type: 'string' as const },
|
||||
attr6Buf: { field: 3, type: 'bytes' as const },
|
||||
attr7Buf: { field: 4, type: 'bytes' as const },
|
||||
buf: { field: 11, type: 'bytes' as const },
|
||||
pbReserve: { field: 12, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FaceElemSchema = {
|
||||
index: { field: 1, type: 'int32' as const },
|
||||
oldData: { field: 2, type: 'bytes' as const },
|
||||
buf: { field: 11, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OnlineImageSchema = {
|
||||
guid: { field: 1, type: 'bytes' as const },
|
||||
filePath: { field: 2, type: 'bytes' as const },
|
||||
oldVerSendFile: { field: 3, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NotOnlineImageSchema = {
|
||||
filePath: { field: 1, type: 'string' as const },
|
||||
fileLen: { field: 2, type: 'uint32' as const },
|
||||
downloadPath: { field: 3, type: 'string' as const },
|
||||
oldVerSendFile: { field: 4, type: 'bytes' as const },
|
||||
imgType: { field: 5, type: 'int32' as const },
|
||||
previewsImage: { field: 6, type: 'bytes' as const },
|
||||
picMd5: { field: 7, type: 'bytes' as const },
|
||||
picHeight: { field: 8, type: 'uint32' as const },
|
||||
picWidth: { field: 9, type: 'uint32' as const },
|
||||
resId: { field: 10, type: 'string' as const },
|
||||
flag: { field: 11, type: 'bytes' as const },
|
||||
thumbUrl: { field: 12, type: 'string' as const },
|
||||
original: { field: 13, type: 'int32' as const },
|
||||
bigUrl: { field: 14, type: 'string' as const },
|
||||
origUrl: { field: 15, type: 'string' as const },
|
||||
bizType: { field: 16, type: 'int32' as const },
|
||||
result: { field: 17, type: 'int32' as const },
|
||||
index: { field: 18, type: 'int32' as const },
|
||||
opFaceBuf: { field: 19, type: 'bytes' as const },
|
||||
oldPicMd5: { field: 20, type: 'bool' as const },
|
||||
thumbWidth: { field: 21, type: 'int32' as const },
|
||||
thumbHeight: { field: 22, type: 'int32' as const },
|
||||
fileId: { field: 23, type: 'int32' as const },
|
||||
showLen: { field: 24, type: 'uint32' as const },
|
||||
downloadLen: { field: 25, type: 'uint32' as const },
|
||||
x400Url: { field: 26, type: 'string' as const },
|
||||
x400Width: { field: 27, type: 'int32' as const },
|
||||
x400Height: { field: 28, type: 'int32' as const },
|
||||
pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const TransElemSchema = {
|
||||
elemType: { field: 1, type: 'int32' as const },
|
||||
elemValue: { field: 2, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const MarketFaceSchema = {
|
||||
faceName: { field: 1, type: 'string' as const },
|
||||
itemType: { field: 2, type: 'uint32' as const },
|
||||
faceInfo: { field: 3, type: 'uint32' as const },
|
||||
faceId: { field: 4, type: 'bytes' as const },
|
||||
tabId: { field: 5, type: 'uint32' as const },
|
||||
subType: { field: 6, type: 'uint32' as const },
|
||||
key: { field: 7, type: 'bytes' as const },
|
||||
param: { field: 8, type: 'bytes' as const },
|
||||
mediaType: { field: 9, type: 'uint32' as const },
|
||||
imageWidth: { field: 10, type: 'uint32' as const },
|
||||
imageHeight: { field: 11, type: 'uint32' as const },
|
||||
mobileParam: { field: 12, type: 'bytes' as const },
|
||||
pbReserve: { field: 13, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const CustomFaceSchema = {
|
||||
guid: { field: 1, type: 'bytes' as const },
|
||||
filePath: { field: 2, type: 'string' as const },
|
||||
shortcut: { field: 3, type: 'string' as const },
|
||||
buffer: { field: 4, type: 'bytes' as const },
|
||||
flag: { field: 5, type: 'bytes' as const },
|
||||
oldData: { field: 6, type: 'bytes' as const },
|
||||
fileId: { field: 7, type: 'uint32' as const },
|
||||
serverIp: { field: 8, type: 'int32' as const },
|
||||
serverPort: { field: 9, type: 'int32' as const },
|
||||
fileType: { field: 10, type: 'int32' as const },
|
||||
signature: { field: 11, type: 'bytes' as const },
|
||||
useful: { field: 12, type: 'int32' as const },
|
||||
md5: { field: 13, type: 'bytes' as const },
|
||||
thumbUrl: { field: 14, type: 'string' as const },
|
||||
bigUrl: { field: 15, type: 'string' as const },
|
||||
origUrl: { field: 16, type: 'string' as const },
|
||||
bizType: { field: 17, type: 'int32' as const },
|
||||
repeatIndex: { field: 18, type: 'int32' as const },
|
||||
repeatImage: { field: 19, type: 'int32' as const },
|
||||
imageType: { field: 20, type: 'int32' as const },
|
||||
index: { field: 21, type: 'int32' as const },
|
||||
width: { field: 22, type: 'int32' as const },
|
||||
height: { field: 23, type: 'int32' as const },
|
||||
source: { field: 24, type: 'int32' as const },
|
||||
size: { field: 25, type: 'uint32' as const },
|
||||
origin: { field: 26, type: 'int32' as const },
|
||||
thumbWidth: { field: 27, type: 'int32' as const },
|
||||
thumbHeight: { field: 28, type: 'int32' as const },
|
||||
showLen: { field: 29, type: 'int32' as const },
|
||||
downloadLen: { field: 30, type: 'int32' as const },
|
||||
x400Url: { field: 31, type: 'string' as const },
|
||||
x400Width: { field: 32, type: 'int32' as const },
|
||||
x400Height: { field: 33, type: 'int32' as const },
|
||||
pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RichMsgSchema = {
|
||||
template1: { field: 1, type: 'bytes' as const },
|
||||
serviceId: { field: 2, type: 'int32' as const },
|
||||
msgResId: { field: 3, type: 'bytes' as const },
|
||||
rand: { field: 4, type: 'int32' as const },
|
||||
seq: { field: 5, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupFileElemSchema = {
|
||||
filename: { field: 1, type: 'string' as const },
|
||||
fileSize: { field: 2, type: 'uint64' as const },
|
||||
fileId: { field: 3, type: 'string' as const },
|
||||
batchId: { field: 4, type: 'string' as const },
|
||||
fileKey: { field: 5, type: 'string' as const },
|
||||
mark: { field: 6, type: 'bytes' as const },
|
||||
sequence: { field: 7, type: 'uint64' as const },
|
||||
batchItemId: { field: 8, type: 'bytes' as const },
|
||||
feedMsgTime: { field: 9, type: 'int32' as const },
|
||||
pbReserve: { field: 10, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const ExtraInfoSchema = {
|
||||
nick: { field: 1, type: 'bytes' as const },
|
||||
groupCard: { field: 2, type: 'bytes' as const },
|
||||
level: { field: 3, type: 'int32' as const },
|
||||
flags: { field: 4, type: 'int32' as const },
|
||||
groupMask: { field: 5, type: 'int32' as const },
|
||||
msgTailId: { field: 6, type: 'int32' as const },
|
||||
senderTitle: { field: 7, type: 'bytes' as const },
|
||||
apnsTips: { field: 8, type: 'bytes' as const },
|
||||
uin: { field: 9, type: 'uint64' as const },
|
||||
msgStateFlag: { field: 10, type: 'int32' as const },
|
||||
apnsSoundType: { field: 11, type: 'int32' as const },
|
||||
newGroupFlag: { field: 12, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const VideoFileSchema = {
|
||||
fileUuid: { field: 1, type: 'string' as const },
|
||||
fileMd5: { field: 2, type: 'bytes' as const },
|
||||
fileName: { field: 3, type: 'string' as const },
|
||||
fileFormat: { field: 4, type: 'int32' as const },
|
||||
fileTime: { field: 5, type: 'int32' as const },
|
||||
fileSize: { field: 6, type: 'int32' as const },
|
||||
thumbWidth: { field: 7, type: 'int32' as const },
|
||||
thumbHeight: { field: 8, type: 'int32' as const },
|
||||
thumbFileMd5: { field: 9, type: 'bytes' as const },
|
||||
source: { field: 10, type: 'bytes' as const },
|
||||
thumbFileSize:{ field: 11, type: 'int32' as const },
|
||||
busiType: { field: 12, type: 'int32' as const },
|
||||
fromChatType: { field: 13, type: 'int32' as const },
|
||||
toChatType: { field: 14, type: 'int32' as const },
|
||||
supportProgressive: { field: 15, type: 'bool' as const },
|
||||
fileWidth: { field: 16, type: 'int32' as const },
|
||||
fileHeight: { field: 17, type: 'int32' as const },
|
||||
subBusiType: { field: 18, type: 'int32' as const },
|
||||
videoAttr: { field: 19, type: 'int32' as const },
|
||||
pbReserve: { field: 24, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SrcMsgSchema = {
|
||||
origSeqs: { field: 1, type: 'repeated_uint32' as const },
|
||||
senderUin: { field: 2, type: 'uint64' as const },
|
||||
time: { field: 3, type: 'int32' as const },
|
||||
flag: { field: 4, type: 'int32' as const },
|
||||
elemsRaw: { field: 5, type: 'repeated_bytes' as const },
|
||||
type: { field: 6, type: 'int32' as const },
|
||||
richMsg: { field: 7, type: 'bytes' as const },
|
||||
pbReserve: { field: 8, type: 'bytes' as const },
|
||||
sourceMsg: { field: 9, type: 'bytes' as const },
|
||||
toUin: { field: 10, type: 'uint64' as const },
|
||||
troopName: { field: 11, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const LightAppElemSchema = {
|
||||
data: { field: 1, type: 'bytes' as const },
|
||||
msgResid: { field: 2, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const CommonElemSchema = {
|
||||
serviceType: { field: 1, type: 'int32' as const },
|
||||
pbElem: { field: 2, type: 'bytes' as const },
|
||||
businessType: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GeneralFlagsSchema = {
|
||||
bubbleDiyTextId: { field: 1, type: 'int32' as const },
|
||||
groupFlagNew: { field: 2, type: 'int32' as const },
|
||||
uin: { field: 3, type: 'uint64' as const },
|
||||
longTextFlag: { field: 6, type: 'int32' as const },
|
||||
longTextResId: { field: 7, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Elem (union of all element types) ---
|
||||
|
||||
export const ElemSchema = {
|
||||
text: { field: 1, type: 'message' as const, schema: TextElemSchema },
|
||||
face: { field: 2, type: 'message' as const, schema: FaceElemSchema },
|
||||
onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema },
|
||||
notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema },
|
||||
transElem: { field: 5, type: 'message' as const, schema: TransElemSchema },
|
||||
marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema },
|
||||
customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema },
|
||||
richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema },
|
||||
groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema },
|
||||
extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema },
|
||||
videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema },
|
||||
generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema },
|
||||
srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema },
|
||||
lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema },
|
||||
commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Extra decode types (for CommonElem.pbElem sub-messages) ---
|
||||
|
||||
export const MentionExtraSchema = {
|
||||
type: { field: 3, type: 'int32' as const },
|
||||
uin: { field: 4, type: 'uint32' as const },
|
||||
field5: { field: 5, type: 'int32' as const },
|
||||
uid: { field: 9, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const QFaceExtraSchema = {
|
||||
packId: { field: 1, type: 'string' as const },
|
||||
stickerId: { field: 2, type: 'string' as const },
|
||||
qsid: { field: 3, type: 'int32' as const },
|
||||
sourceType: { field: 4, type: 'int32' as const },
|
||||
stickerType: { field: 5, type: 'int32' as const },
|
||||
resultId: { field: 6, type: 'string' as const },
|
||||
text: { field: 7, type: 'string' as const },
|
||||
randomType: { field: 9, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const QSmallFaceExtraSchema = {
|
||||
faceId: { field: 1, type: 'uint32' as const },
|
||||
preview: { field: 2, type: 'string' as const },
|
||||
preview2: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- NTQQ MsgInfo types (CommonElem service_type 48) ---
|
||||
|
||||
export const FileTypeSchema = {
|
||||
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 FileInfoSchema = {
|
||||
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: FileTypeSchema },
|
||||
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 IndexNodeSchema = {
|
||||
info: { field: 1, type: 'message' as const, schema: FileInfoSchema },
|
||||
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 PicUrlExtInfoSchema = {
|
||||
originalParameter: { field: 1, type: 'string' as const },
|
||||
bigParameter: { field: 2, type: 'string' as const },
|
||||
thumbParameter: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const PictureInfoSchema = {
|
||||
urlPath: { field: 1, type: 'string' as const },
|
||||
ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema },
|
||||
domain: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const PicExtDataSchema = {
|
||||
subType: { field: 1, type: 'uint32' as const },
|
||||
textSummary: { field: 9, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const PicExtBizInfoSchema = {
|
||||
bizType: { field: 1, type: 'uint32' as const },
|
||||
textSummary: { field: 2, type: 'string' as const },
|
||||
bytesPbReserveC2c: { field: 11, type: 'bytes' as const },
|
||||
extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema },
|
||||
fromScene: { field: 1001, type: 'uint32' as const },
|
||||
toScene: { field: 1002, type: 'uint32' as const },
|
||||
oldFileId: { field: 1003, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const VideoExtBizInfoSchema = {
|
||||
fromScene: { field: 1, type: 'uint32' as const },
|
||||
toScene: { field: 2, type: 'uint32' as const },
|
||||
bytesPbReserve: { field: 3, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const PttExtBizInfoSchema = {
|
||||
srcUin: { field: 1, type: 'uint64' as const },
|
||||
pttScene: { field: 2, type: 'uint32' as const },
|
||||
pttType: { field: 3, type: 'uint32' as const },
|
||||
changeVoice: { field: 4, type: 'uint32' as const },
|
||||
waveform: { field: 5, type: 'bytes' as const },
|
||||
autoConvertText: { field: 6, type: 'uint32' as const },
|
||||
bytesReserve: { field: 11, type: 'bytes' as const },
|
||||
bytesPbReserve: { field: 12, type: 'bytes' as const },
|
||||
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const ExtBizInfoSchema = {
|
||||
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
|
||||
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
|
||||
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
|
||||
busiType: { field: 10, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const C2cSourceSchema = {
|
||||
friendUid: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const TroopSourceSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HashSumSchema = {
|
||||
bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema },
|
||||
troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const MsgInfoBodySchema = {
|
||||
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
|
||||
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
|
||||
fileExist: { field: 5, type: 'bool' as const },
|
||||
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const MsgInfoSchema = {
|
||||
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema },
|
||||
extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- GroupFileExtra (TransElem type=24) ---
|
||||
|
||||
export const GroupFileInfoSchema = {
|
||||
busId: { field: 1, type: 'uint32' as const },
|
||||
fileId: { field: 2, type: 'string' as const },
|
||||
fileSize: { field: 3, type: 'uint64' as const },
|
||||
fileName: { field: 4, type: 'string' as const },
|
||||
fileSha: { field: 5, type: 'bytes' as const },
|
||||
extInfoString: { field: 6, type: 'string' as const },
|
||||
fileMd5: { field: 7, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupFileExtraInnerSchema = {
|
||||
info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupFileExtraSchema = {
|
||||
inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Preserve (for message receipt info) ---
|
||||
|
||||
export const PreserveSchema = {
|
||||
messageId: { field: 3, type: 'uint64' as const },
|
||||
senderUid: { field: 6, type: 'string' as const },
|
||||
receiverUid: { field: 7, type: 'string' as const },
|
||||
clientSequence: { field: 8, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -1,336 +0,0 @@
|
||||
// Proto schemas for highway upload protocol.
|
||||
// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn)
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
import {
|
||||
IndexNodeSchema,
|
||||
PictureInfoSchema,
|
||||
HashSumSchema,
|
||||
PicExtBizInfoSchema,
|
||||
VideoExtBizInfoSchema,
|
||||
PttExtBizInfoSchema,
|
||||
} from '../proto/element';
|
||||
|
||||
// --- DataHighwayHead ---
|
||||
|
||||
export const DataHighwayHeadSchema = {
|
||||
version: { field: 1, type: 'uint32' as const },
|
||||
uin: { field: 2, type: 'string' as const },
|
||||
command: { field: 3, type: 'string' as const },
|
||||
seq: { field: 4, type: 'uint32' as const },
|
||||
retryTimes:{ field: 5, type: 'uint32' as const },
|
||||
appId: { field: 6, type: 'uint32' as const },
|
||||
dataFlag: { field: 7, type: 'uint32' as const },
|
||||
commandId: { field: 8, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SegHeadSchema = {
|
||||
serviceId: { field: 1, type: 'uint32' as const },
|
||||
filesize: { field: 2, type: 'uint64' as const },
|
||||
dataOffset: { field: 3, type: 'uint64' as const },
|
||||
dataLength: { field: 4, type: 'uint32' as const },
|
||||
retCode: { field: 5, type: 'uint32' as const },
|
||||
serviceTicket: { field: 6, type: 'bytes' as const },
|
||||
flag: { field: 7, type: 'uint32' as const },
|
||||
md5: { field: 8, type: 'bytes' as const },
|
||||
fileMd5: { field: 9, type: 'bytes' as const },
|
||||
cacheAddr: { field: 10, type: 'uint32' as const },
|
||||
cachePort: { field: 13, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const LoginSigHeadSchema = {
|
||||
loginSigType: { field: 1, type: 'uint32' as const },
|
||||
appId: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const ReqDataHighwayHeadSchema = {
|
||||
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
|
||||
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
|
||||
bytesReqExtendInfo: { field: 3, type: 'bytes' as const },
|
||||
timestamp: { field: 4, type: 'uint64' as const },
|
||||
msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RespDataHighwayHeadSchema = {
|
||||
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
|
||||
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
|
||||
errorCode: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Highway extend (NTV2RichMediaHighwayExt) ---
|
||||
|
||||
export const HighwayDomainSchema = {
|
||||
isEnable: { field: 1, type: 'bool' as const },
|
||||
ip: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HighwayIPv4Schema = {
|
||||
domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema },
|
||||
port: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HighwayNetworkSchema = {
|
||||
ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HighwayHashSchema = {
|
||||
fileSha1: { field: 1, type: 'repeated_bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HighwayMsgInfoBodySchema = {
|
||||
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
|
||||
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
|
||||
fileExist: { field: 5, type: 'bool' as const },
|
||||
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2RichMediaHighwayExtSchema = {
|
||||
fileUuid: { field: 1, type: 'string' as const },
|
||||
uKey: { field: 2, type: 'string' as const },
|
||||
network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema },
|
||||
msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
|
||||
blockSize: { field: 10, type: 'uint32' as const },
|
||||
hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- File upload extend (group/private file highway) ---
|
||||
|
||||
export const FileUploadUrlSchema = {
|
||||
unknown: { field: 1, type: 'int32' as const },
|
||||
host: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadHostSchema = {
|
||||
url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema },
|
||||
port: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadHostConfigSchema = {
|
||||
hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadNameInfoSchema = {
|
||||
fileName: { field: 100, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadClientInfoSchema = {
|
||||
clientType: { field: 100, type: 'int32' as const },
|
||||
appId: { field: 200, type: 'string' as const },
|
||||
terminalType: { field: 300, type: 'int32' as const },
|
||||
clientVer: { field: 400, type: 'string' as const },
|
||||
unknown: { field: 600, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadFileEntrySchema = {
|
||||
fileSize: { field: 100, type: 'uint64' as const },
|
||||
md5: { field: 200, type: 'bytes' as const },
|
||||
checkKey: { field: 300, type: 'bytes' as const },
|
||||
md5S2: { field: 400, type: 'bytes' as const },
|
||||
fileId: { field: 600, type: 'string' as const },
|
||||
uploadKey: { field: 700, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadBusiInfoSchema = {
|
||||
busId: { field: 1, type: 'int32' as const },
|
||||
senderUin: { field: 100, type: 'uint64' as const },
|
||||
receiverUin: { field: 200, type: 'uint64' as const },
|
||||
groupCode: { field: 400, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadEntrySchema = {
|
||||
busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema },
|
||||
fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema },
|
||||
clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema },
|
||||
fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema },
|
||||
host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileUploadExtSchema = {
|
||||
unknown1: { field: 1, type: 'int32' as const },
|
||||
unknown2: { field: 2, type: 'int32' as const },
|
||||
unknown3: { field: 3, type: 'int32' as const },
|
||||
entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema },
|
||||
unknown200: { field: 200, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Encodable MsgInfo (for embedding in message element) ---
|
||||
|
||||
export const EncodableMediaExtBizInfoSchema = {
|
||||
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
|
||||
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
|
||||
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
|
||||
busiType: { field: 10, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const EncodableMediaMsgInfoSchema = {
|
||||
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
|
||||
extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- HttpConn.0x6ff_501 (highway session) ---
|
||||
|
||||
export const HttpConnSchema = {
|
||||
field1: { field: 1, type: 'int32' as const },
|
||||
field2: { field: 2, type: 'int32' as const },
|
||||
field3: { field: 3, type: 'int32' as const },
|
||||
field4: { field: 4, type: 'int32' as const },
|
||||
field6: { field: 6, type: 'int32' as const },
|
||||
serviceTypes: { field: 7, type: 'repeated_uint32' as const },
|
||||
field9: { field: 9, type: 'int32' as const },
|
||||
field10: { field: 10, type: 'int32' as const },
|
||||
field11: { field: 11, type: 'int32' as const },
|
||||
ver: { field: 15, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HttpConn0x6FF501RequestSchema = {
|
||||
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const ServerAddrSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32
|
||||
port: { field: 3, type: 'uint32' as const },
|
||||
area: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const ServerInfoSchema = {
|
||||
serviceType: { field: 1, type: 'uint32' as const },
|
||||
serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HttpConnResponseSchema = {
|
||||
sigSession: { field: 1, type: 'bytes' as const },
|
||||
sessionKey: { field: 2, type: 'bytes' as const },
|
||||
serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const HttpConn0x6FF501ResponseSchema = {
|
||||
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ---
|
||||
|
||||
export const NTV2FileTypeSchema = {
|
||||
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 NTV2FileInfoSchema = {
|
||||
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: NTV2FileTypeSchema },
|
||||
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 NTV2UploadInfoSchema = {
|
||||
fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
|
||||
subFileType: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// The NTV2 upload request + response carry the same ExtBizInfo shape that
|
||||
// element-side incoming-message decoding uses. Pulling those schemas in
|
||||
// directly (instead of redefining stub copies) keeps the round-trip
|
||||
// `server response → finalizeMediaMsgInfo → commonElem.pbElem` from
|
||||
// silently dropping fields the QQ NT server later validates against —
|
||||
// the video `fromScene`/`toScene` drop was already responsible for c2c
|
||||
// `result=79` rejections on `send_private_msg [{type:'video'}]`.
|
||||
export const NTV2ExtBizInfoSchema = {
|
||||
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
|
||||
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
|
||||
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
|
||||
busiType: { field: 10, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadReqSchema = {
|
||||
uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema },
|
||||
tryFastUploadCompleted: { field: 2, type: 'bool' as const },
|
||||
srvSendMsg: { field: 3, type: 'bool' as const },
|
||||
clientRandomId: { field: 4, type: 'uint64' as const },
|
||||
compatQmsgSceneType: { field: 5, type: 'uint32' as const },
|
||||
extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
|
||||
clientSeq: { field: 7, type: 'uint32' as const },
|
||||
noNeedCompatMsg: { field: 8, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2C2CUserInfoSchema = {
|
||||
accountType: { field: 1, type: 'uint32' as const },
|
||||
targetUid: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2GroupInfoSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadSceneInfoSchema = {
|
||||
requestType: { field: 101, type: 'uint32' as const },
|
||||
businessType: { field: 102, type: 'uint32' as const },
|
||||
sceneType: { field: 200, type: 'uint32' as const },
|
||||
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
|
||||
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2CommonHeadSchema = {
|
||||
requestId: { field: 1, type: 'uint32' as const },
|
||||
command: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2ClientMetaSchema = {
|
||||
agentType: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadReqHeadSchema = {
|
||||
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||
scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema },
|
||||
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadRichMediaReqSchema = {
|
||||
reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema },
|
||||
upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- NTV2 Upload Response ---
|
||||
|
||||
export const NTV2IPv4Schema = {
|
||||
outIp: { field: 1, type: 'uint32' as const },
|
||||
outPort: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2SubFileInfoRespSchema = {
|
||||
subType: { field: 1, type: 'uint32' as const },
|
||||
uKey: { field: 2, type: 'string' as const },
|
||||
uKeyTtl: { field: 3, type: 'uint32' as const },
|
||||
ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadRespMsgInfoSchema = {
|
||||
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
|
||||
extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadRespBodySchema = {
|
||||
uKey: { field: 1, type: 'string' as const },
|
||||
uKeyTtl: { field: 2, type: 'uint32' as const },
|
||||
ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
|
||||
msgSeq: { field: 5, type: 'uint64' as const },
|
||||
msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema },
|
||||
subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadRespHeadSchema = {
|
||||
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||
retCode: { field: 2, type: 'uint32' as const },
|
||||
message: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2UploadRichMediaRespSchema = {
|
||||
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
|
||||
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -1,68 +0,0 @@
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
import { PushMsgBodySchema } from './message';
|
||||
|
||||
export const LongMsgUidSchema = {
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const LongMsgSettingsSchema = {
|
||||
field1: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SendLongMsgInfoSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema },
|
||||
groupUin: { field: 3, type: 'uint32' as const },
|
||||
payload: { field: 4, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SendLongMsgReqSchema = {
|
||||
info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema },
|
||||
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SendLongMsgRespResultSchema = {
|
||||
resId: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SendLongMsgRespSchema = {
|
||||
result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema },
|
||||
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RecvLongMsgInfoSchema = {
|
||||
uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema },
|
||||
resId: { field: 2, type: 'string' as const },
|
||||
acquire: { field: 3, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RecvLongMsgReqSchema = {
|
||||
info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema },
|
||||
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RecvLongMsgRespResultSchema = {
|
||||
resId: { field: 3, type: 'string' as const },
|
||||
payload: { field: 4, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RecvLongMsgRespSchema = {
|
||||
result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema },
|
||||
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const LongMsgContentSchema = {
|
||||
msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const LongMsgActionSchema = {
|
||||
actionCommand: { field: 1, type: 'string' as const },
|
||||
actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const LongMsgResultSchema = {
|
||||
action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -1,113 +0,0 @@
|
||||
// Proto schemas for message envelopes (PushMsg).
|
||||
// Port of src/bridge/include/bridge/proto/message.h
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
import { ElemSchema } from './element';
|
||||
|
||||
// --- ResponseHead.Grp ---
|
||||
|
||||
export const ResponseGrpSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
memberName: { field: 2, type: 'string' as const },
|
||||
groupName: { field: 4, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const ResponseForwardSchema = {
|
||||
friendName: { field: 6, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- ResponseHead ---
|
||||
|
||||
export const ResponseHeadSchema = {
|
||||
fromUin: { field: 1, type: 'uint32' as const },
|
||||
fromUid: { field: 2, type: 'string' as const },
|
||||
type: { field: 3, type: 'uint32' as const },
|
||||
sigMap: { field: 4, type: 'uint32' as const },
|
||||
toUin: { field: 5, type: 'uint32' as const },
|
||||
toUid: { field: 6, type: 'string' as const },
|
||||
forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema },
|
||||
grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- ContentHead ---
|
||||
|
||||
export const ContentHeadSchema = {
|
||||
msgType: { field: 1, type: 'uint32' as const },
|
||||
subType: { field: 2, type: 'uint32' as const },
|
||||
divSeq: { field: 3, type: 'uint32' as const },
|
||||
msgId: { field: 4, type: 'uint32' as const },
|
||||
sequence: { field: 5, type: 'uint32' as const },
|
||||
timestamp: { field: 6, type: 'uint32' as const },
|
||||
field7: { field: 7, type: 'uint64' as const },
|
||||
newId: { field: 12, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Ptt (voice) ---
|
||||
|
||||
export const PttSchema = {
|
||||
fileType: { field: 1, type: 'uint32' as const },
|
||||
fileId: { field: 2, type: 'uint64' as const },
|
||||
fileUuid: { field: 3, type: 'bytes' as const },
|
||||
fileMd5: { field: 4, type: 'bytes' as const },
|
||||
fileName: { field: 5, type: 'string' as const },
|
||||
fileSize: { field: 6, type: 'uint32' as const },
|
||||
groupFileKey: { field: 10, type: 'string' as const },
|
||||
fileKey: { field: 14, type: 'bytes' as const },
|
||||
time: { field: 19, type: 'uint32' as const },
|
||||
format: { field: 29, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- NotOnlineFile (C2C file) ---
|
||||
|
||||
export const NotOnlineFileSchema = {
|
||||
fileType: { field: 1, type: 'uint32' as const },
|
||||
fileUuid: { field: 3, type: 'string' as const },
|
||||
fileMd5: { field: 4, type: 'bytes' as const },
|
||||
fileName: { field: 5, type: 'string' as const },
|
||||
fileSize: { field: 6, type: 'uint64' as const },
|
||||
fileHash: { field: 57, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- RichText ---
|
||||
|
||||
export const RichTextSchema = {
|
||||
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
|
||||
notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema },
|
||||
ptt: { field: 4, type: 'message' as const, schema: PttSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- MessageBody ---
|
||||
|
||||
export const MessageBodySchema = {
|
||||
richText: { field: 1, type: 'message' as const, schema: RichTextSchema },
|
||||
msgContent: { field: 2, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- FileExtra (for C2C file in msg_content) ---
|
||||
|
||||
export const FileExtraInfoSchema = {
|
||||
fileSize: { field: 1, type: 'uint64' as const },
|
||||
fileName: { field: 2, type: 'string' as const },
|
||||
fileMd5: { field: 3, type: 'bytes' as const },
|
||||
fileUuid: { field: 4, type: 'string' as const },
|
||||
fileHash: { field: 5, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FileExtraSchema = {
|
||||
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- PushMsgBody ---
|
||||
|
||||
export const PushMsgBodySchema = {
|
||||
responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema },
|
||||
contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema },
|
||||
body: { field: 3, type: 'message' as const, schema: MessageBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- PushMsg (top-level) ---
|
||||
|
||||
export const PushMsgSchema = {
|
||||
message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema },
|
||||
status: { field: 3, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -1,207 +0,0 @@
|
||||
// Proto schemas for notification types.
|
||||
// Port of src/bridge/include/bridge/proto/notify.h
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
|
||||
export const OperatorField1Schema = {
|
||||
uid: { field: 1, type: 'string' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'bytes' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
field5: { field: 5, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OperatorInfoSchema = {
|
||||
operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupChangeSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
flag: { field: 2, type: 'uint32' as const },
|
||||
memberUid: { field: 3, type: 'string' as const },
|
||||
decreaseType: { field: 4, type: 'uint32' as const },
|
||||
operatorBytes: { field: 5, type: 'bytes' as const },
|
||||
increaseType: { field: 6, type: 'uint32' as const },
|
||||
field7: { field: 7, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupAdminExtraSchema = {
|
||||
adminUid: { field: 1, type: 'string' as const },
|
||||
isPromote: { field: 2, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupAdminBodySchema = {
|
||||
extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema },
|
||||
extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupAdminSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
flag: { field: 2, type: 'uint32' as const },
|
||||
isPromote: { field: 3, type: 'bool' as const },
|
||||
body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const InvitationInnerSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
targetUid: { field: 5, type: 'string' as const },
|
||||
invitorUid: { field: 6, type: 'string' as const },
|
||||
field7: { field: 7, type: 'uint32' as const },
|
||||
field9: { field: 9, type: 'uint32' as const },
|
||||
field10: { field: 10, type: 'bytes' as const },
|
||||
field11: { field: 11, type: 'uint32' as const },
|
||||
field12: { field: 12, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const InvitationInfoSchema = {
|
||||
inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupInvitationSchema = {
|
||||
cmd: { field: 1, type: 'int32' as const },
|
||||
info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupInviteSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
invitorUid: { field: 5, type: 'string' as const },
|
||||
hashes: { field: 6, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupJoinSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
targetUid: { field: 3, type: 'string' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
field6: { field: 6, type: 'uint32' as const },
|
||||
field7: { field: 7, type: 'string' as const },
|
||||
field8: { field: 8, type: 'uint32' as const },
|
||||
field9: { field: 9, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FriendRequestInfoSchema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
sourceUid: { field: 2, type: 'string' as const },
|
||||
newSource: { field: 5, type: 'string' as const },
|
||||
message: { field: 10, type: 'string' as const },
|
||||
source: { field: 11, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FriendRequestSchema = {
|
||||
info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FriendRecallTipInfoSchema = {
|
||||
tip: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FriendRecallInfoSchema = {
|
||||
fromUid: { field: 1, type: 'string' as const },
|
||||
toUid: { field: 2, type: 'string' as const },
|
||||
clientSequence: { field: 3, type: 'uint32' as const },
|
||||
newId: { field: 4, type: 'uint64' as const },
|
||||
time: { field: 5, type: 'uint32' as const },
|
||||
random: { field: 6, type: 'uint32' as const },
|
||||
pkgNum: { field: 7, type: 'uint32' as const },
|
||||
pkgIndex: { field: 8, type: 'uint32' as const },
|
||||
divSeq: { field: 9, type: 'uint32' as const },
|
||||
tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const FriendRecallSchema = {
|
||||
info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema },
|
||||
instId: { field: 2, type: 'uint32' as const },
|
||||
appId: { field: 3, type: 'uint32' as const },
|
||||
longMessageFlag: { field: 4, type: 'uint32' as const },
|
||||
reserved: { field: 5, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupMuteStateSchema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
duration: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupMuteDataSchema = {
|
||||
timestamp: { field: 1, type: 'uint32' as const },
|
||||
type: { field: 2, type: 'uint32' as const },
|
||||
state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupMuteSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
subType: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
operatorUid: { field: 4, type: 'string' as const },
|
||||
data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const RecallMessageSchema = {
|
||||
sequence: { field: 1, type: 'uint32' as const },
|
||||
time: { field: 2, type: 'uint32' as const },
|
||||
random: { field: 3, type: 'uint32' as const },
|
||||
type: { field: 4, type: 'uint32' as const },
|
||||
flag: { field: 5, type: 'uint32' as const },
|
||||
authorUid: { field: 6, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupRecallTipInfoSchema = {
|
||||
tip: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupRecallSchema = {
|
||||
operatorUid: { field: 1, type: 'string' as const },
|
||||
recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema },
|
||||
userDef: { field: 5, type: 'bytes' as const },
|
||||
groupType: { field: 6, type: 'int32' as const },
|
||||
opType: { field: 7, type: 'int32' as const },
|
||||
tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const TemplParamSchema = {
|
||||
name: { field: 1, type: 'string' as const },
|
||||
value: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GeneralGrayTipInfoSchema = {
|
||||
busiType: { field: 1, type: 'uint64' as const },
|
||||
busiId: { field: 2, type: 'uint64' as const },
|
||||
ctrlFlag: { field: 3, type: 'uint32' as const },
|
||||
c2cType: { field: 4, type: 'uint32' as const },
|
||||
serviceType: { field: 5, type: 'uint32' as const },
|
||||
templId: { field: 6, type: 'uint64' as const },
|
||||
msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema },
|
||||
content: { field: 8, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const EssenceMessageSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
msgSequence: { field: 2, type: 'uint32' as const },
|
||||
random: { field: 3, type: 'uint32' as const },
|
||||
setFlag: { field: 4, type: 'uint32' as const },
|
||||
memberUin: { field: 5, type: 'uint32' as const },
|
||||
operatorUin: { field: 6, type: 'uint32' as const },
|
||||
timestamp: { field: 7, type: 'uint32' as const },
|
||||
msgSequence2: { field: 8, type: 'uint32' as const },
|
||||
operatorNickname: { field: 9, type: 'string' as const },
|
||||
memberNickname: { field: 10, type: 'string' as const },
|
||||
setFlag2: { field: 11, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NotifyMessageBodySchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
groupUin: { field: 4, type: 'uint32' as const },
|
||||
eventParam: { field: 5, type: 'bytes' as const },
|
||||
recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema },
|
||||
field13: { field: 13, type: 'uint32' as const },
|
||||
operatorUid: { field: 21, type: 'string' as const },
|
||||
generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema },
|
||||
essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema },
|
||||
msgSequence: { field: 37, type: 'uint32' as const },
|
||||
field39: { field: 39, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,161 +0,0 @@
|
||||
// Proto schemas for OidbSvc service types.
|
||||
// Port of src/bridge/include/bridge/proto/oidb.h
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
|
||||
// --- OidbSvcTrpcTcpBase wrapper ---
|
||||
|
||||
export const OidbPropertySchema = {
|
||||
key: { field: 1, type: 'string' as const },
|
||||
value: { field: 2, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// Factory for OidbSvcTrpcTcpBase<T>
|
||||
export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema {
|
||||
return {
|
||||
command: { field: 1, type: 'uint32' as const },
|
||||
subCommand: { field: 2, type: 'uint32' as const },
|
||||
errorCode: { field: 3, type: 'uint32' as const },
|
||||
body: { field: 4, type: 'message' as const, schema: bodySchema },
|
||||
errorMsg: { field: 5, type: 'string' as const },
|
||||
properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema },
|
||||
reserved: { field: 12, type: 'int32' as const },
|
||||
};
|
||||
}
|
||||
|
||||
// --- Friend list (0xFD4_1) ---
|
||||
|
||||
export const OidbFriendPropertySchema = {
|
||||
code: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbFriendLayer1Schema = {
|
||||
properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbFriendAdditionalSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbFriendSchema = {
|
||||
uid: { field: 1, type: 'string' as const },
|
||||
customGroup:{ field: 2, type: 'uint32' as const },
|
||||
uin: { field: 3, type: 'uint32' as const },
|
||||
additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = {
|
||||
next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema },
|
||||
displayFriendCount: { field: 3, type: 'uint32' as const },
|
||||
timestamp: { field: 6, type: 'uint32' as const },
|
||||
selfUin: { field: 7, type: 'uint32' as const },
|
||||
friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema },
|
||||
groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Group list (0xFE5_2) ---
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE5_2MemberSchema = {
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = {
|
||||
groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema },
|
||||
createdTime: { field: 2, type: 'uint32' as const },
|
||||
memberMax: { field: 3, type: 'uint32' as const },
|
||||
memberCount: { field: 4, type: 'uint32' as const },
|
||||
groupName: { field: 5, type: 'string' as const },
|
||||
description: { field: 18, type: 'string' as const },
|
||||
question: { field: 19, type: 'string' as const },
|
||||
announcement: { field: 30, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = {
|
||||
remark: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE5_2GroupSchema = {
|
||||
groupUin: { field: 3, type: 'uint32' as const },
|
||||
info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema },
|
||||
customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = {
|
||||
groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Group member list (0xFE7_3) ---
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE7_3UinSchema = {
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
uin: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE7_3CardSchema = {
|
||||
memberCard: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE7_3LevelSchema = {
|
||||
infos: { field: 1, type: 'repeated_uint32' as const },
|
||||
level: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE7_3MemberSchema = {
|
||||
uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema },
|
||||
memberName: { field: 10, type: 'string' as const },
|
||||
specialTitle: { field: 17, type: 'string' as const },
|
||||
memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema },
|
||||
level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema },
|
||||
joinTimestamp: { field: 100, type: 'uint32' as const },
|
||||
lastMsgTimestamp: { field: 101, type: 'uint32' as const },
|
||||
shutUpTimestamp: { field: 102, type: 'uint32' as const },
|
||||
permission: { field: 107, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
memberChangeSeq: { field: 5, type: 'uint32' as const },
|
||||
memberCardChangeSeq:{ field: 6, type: 'uint32' as const },
|
||||
token: { field: 15, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Group request (0x10C0) ---
|
||||
|
||||
export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = {
|
||||
uid: { field: 1, type: 'string' as const },
|
||||
name: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
groupName: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = {
|
||||
sequence: { field: 1, type: 'uint64' as const },
|
||||
eventType: { field: 2, type: 'uint32' as const },
|
||||
state: { field: 3, type: 'uint32' as const },
|
||||
group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema },
|
||||
target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
|
||||
invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
|
||||
operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
|
||||
field9: { field: 9, type: 'string' as const },
|
||||
comment: { field: 10, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSvcTrpcTcp0x10C0ResponseSchema = {
|
||||
requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema },
|
||||
field2: { field: 2, type: 'uint64' as const },
|
||||
newLatestSeq: { field: 3, type: 'uint64' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
field5: { field: 5, type: 'uint64' as const },
|
||||
field6: { field: 6, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -1,155 +0,0 @@
|
||||
// Web-cookie / credential primitives — every other web-action in this
|
||||
// directory builds on these. Each Bridge-level web call ends up doing
|
||||
// roughly: forceFetchClientKey -> ptlogin2 jump -> cookie dict ->
|
||||
// thread the cookies into a qun.qq.com REST endpoint.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
OidbClientKeyRespSchema,
|
||||
OidbClientKeyReqSchema,
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema,
|
||||
} from '../proto/oidb-action';
|
||||
import { RequestUtil } from '../web/request-util';
|
||||
|
||||
export async function forceFetchClientKey(bridge: Bridge) {
|
||||
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
|
||||
// every NapCat-derived implementation uses when the server omits it.
|
||||
const keyIndex = String(resp?.keyIndex || '19');
|
||||
|
||||
return {
|
||||
clientKey,
|
||||
keyIndex,
|
||||
expireTime: String(resp?.expireTime || '1800'),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPSkey(bridge: Bridge, domainList: string[]) {
|
||||
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>();
|
||||
|
||||
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
|
||||
for (const item of resp.pskeyItems) {
|
||||
if (item.domain && item.pskey) {
|
||||
domainPskeyMap.set(item.domain, item.pskey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { domainPskeyMap };
|
||||
}
|
||||
|
||||
export async function getCookies(bridge: Bridge, domain: string) {
|
||||
const ClientKeyData = await forceFetchClientKey(bridge);
|
||||
|
||||
// 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.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
|
||||
// for the same domain. Errors are swallowed so the caller can
|
||||
// still proceed with whatever cookies it did get.
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getSKey(bridge: Bridge): Promise<string> {
|
||||
const ClientKeyData = await forceFetchClientKey(bridge);
|
||||
|
||||
if (!ClientKeyData.clientKey) {
|
||||
throw new Error('getClientKey Error: clientKey is empty');
|
||||
}
|
||||
|
||||
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.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=' + u1 +
|
||||
'&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const skey = cookies['skey'];
|
||||
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
|
||||
return skey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard QQ bkn hash (also known as token / csrf_token) derived from
|
||||
* skey or p_skey. djb2 hash truncated to 31 bits.
|
||||
*/
|
||||
export function getBknFromSKey(skey: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return hash & 2147483647;
|
||||
}
|
||||
|
||||
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
|
||||
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
|
||||
const cookieObject = await getCookies(bridge, domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
export async function getCsrfToken(bridge: Bridge): Promise<number> {
|
||||
const skey = await getSKey(bridge);
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
|
||||
export async function getCredentials(bridge: Bridge, domain: string) {
|
||||
const cookieObject = await getCookies(bridge, domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
const token = skey ? getBknFromSKey(skey) : 0;
|
||||
|
||||
return {
|
||||
cookies: cookiesStr,
|
||||
token: token,
|
||||
csrf_token: token,
|
||||
};
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// `get_essence_msg_list` — group essence (highlighted) messages.
|
||||
// Two flavors: paginated (`getGroupEssence`) and the convenience
|
||||
// fetch-everything (`getGroupEssenceAll`).
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence';
|
||||
import { getCookies } from './cookies';
|
||||
|
||||
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
|
||||
export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
|
||||
|
||||
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
|
||||
}
|
||||
|
||||
/** Walks every page and returns the concatenated result. */
|
||||
export async function getGroupEssenceAll(bridge: Bridge, groupId: number) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
|
||||
return essenceDataAll;
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
// `get_group_honor_info` — queries the per-group honor leaderboards
|
||||
// (talkative / performer / legend / emotion / strong_newbie).
|
||||
// Each honor type is a separate web call; ALL fetches all four
|
||||
// non-newbie lists and folds them into one response.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { getHonorListWebAPI, WebHonorType } from '../web/group-honor';
|
||||
import { getCookies } from './cookies';
|
||||
|
||||
export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const honorInfo: any = {
|
||||
group_id: groupId,
|
||||
current_talkative: null,
|
||||
talkative_list: [],
|
||||
performer_list: [],
|
||||
legend_list: [],
|
||||
emotion_list: [],
|
||||
strong_newbie_list: [],
|
||||
};
|
||||
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
}
|
||||
}
|
||||
|
||||
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
|
||||
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
|
||||
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
|
||||
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
|
||||
}
|
||||
|
||||
return honorInfo;
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// Group notice (`群公告`) web actions: send / list / delete.
|
||||
// `sendGroupNotice` can attach an optional image; when present it
|
||||
// stages the bytes (HTTP URL or local file) and uploads via the
|
||||
// notice-image endpoint before posting the notice itself.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import {
|
||||
setGroupNoticeWebAPI,
|
||||
getGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
deleteGroupNotice,
|
||||
} from '../web/group-notice';
|
||||
import { getCookies } from './cookies';
|
||||
|
||||
export async function sendGroupNotice(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // local path, http URL, or undefined (text-only)
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
confirm_required?: number;
|
||||
},
|
||||
) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
let picId = '';
|
||||
let imgWidth = 540;
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
let imageBuffer: Buffer;
|
||||
|
||||
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
|
||||
const response = await fetch(options.image);
|
||||
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
|
||||
imageBuffer = Buffer.from(await response.arrayBuffer());
|
||||
} else {
|
||||
const { readFileSync } = await import('fs');
|
||||
imageBuffer = readFileSync(options.image);
|
||||
}
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
options?.pinned ?? 0,
|
||||
options?.type ?? 1,
|
||||
1,
|
||||
1,
|
||||
options?.confirm_required ?? 1,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
);
|
||||
|
||||
if (!ret || ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
export async function getGroupNotice(bridge: Bridge, groupId: number) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
if (!ret) {
|
||||
throw new Error('获取公告失败');
|
||||
}
|
||||
|
||||
const retNotices: any[] = [];
|
||||
|
||||
if (ret.feeds) {
|
||||
for (const key in ret.feeds) {
|
||||
const feed = ret.feeds[key];
|
||||
if (!feed) continue;
|
||||
|
||||
const image = feed.msg?.pics?.map((pic) => ({
|
||||
id: pic.id,
|
||||
height: pic.h,
|
||||
width: pic.w,
|
||||
})) || [];
|
||||
|
||||
retNotices.push({
|
||||
notice_id: feed.fid,
|
||||
sender_id: feed.u,
|
||||
publish_time: feed.pubt,
|
||||
message: {
|
||||
text: feed.msg?.text || '',
|
||||
image: image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
}
|
||||
|
||||
export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise<boolean> {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await deleteGroupNotice(cookieObject, groupCode, fid);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// Barrel for the web-action themed split. `bridge.ts` imports
|
||||
// everything from this directory as if it were a single file; the
|
||||
// per-theme files keep the implementation discoverable.
|
||||
|
||||
export {
|
||||
forceFetchClientKey,
|
||||
getPSkey,
|
||||
getCookies,
|
||||
getSKey,
|
||||
getBknFromSKey,
|
||||
getCookiesStr,
|
||||
getCsrfToken,
|
||||
getCredentials,
|
||||
} from './cookies';
|
||||
|
||||
export { getGroupHonorInfo } from './group-honor';
|
||||
|
||||
export {
|
||||
getGroupEssence,
|
||||
getGroupEssenceAll,
|
||||
} from './group-essence';
|
||||
|
||||
export {
|
||||
sendGroupNotice,
|
||||
getGroupNotice,
|
||||
deleteGroupNoticeByFid,
|
||||
} from './group-notice';
|
||||
@@ -1,71 +0,0 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[]; // 具体结构视需要补充
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceMsg(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
pageStart: number = 0,
|
||||
pageLimit: number = 50
|
||||
): Promise<GroupEssenceMsgRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
|
||||
bkn: bkn,
|
||||
page_start: pageStart.toString(),
|
||||
page_limit: pageLimit.toString(),
|
||||
group_code: groupCode,
|
||||
}).toString()}`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息 (最多循环 20 页)
|
||||
*/
|
||||
export async function getGroupEssenceMsgAll(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<GroupEssenceMsgRet[]> {
|
||||
const ret: GroupEssenceMsgRet[] = [];
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
|
||||
|
||||
if (!data) break;
|
||||
|
||||
ret.push(data);
|
||||
|
||||
if (data.data?.is_end) break;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
PERFORMER = 'performer',
|
||||
LEGEND = 'legend',
|
||||
EMOTION = 'emotion',
|
||||
ALL = 'all',
|
||||
}
|
||||
|
||||
|
||||
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
let resJson;
|
||||
try {
|
||||
const res = await RequestUtil.HttpGetText(
|
||||
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
|
||||
gc: groupCode,
|
||||
type: type.toString(),
|
||||
}).toString()}`,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
|
||||
if (match?.[1]) {
|
||||
resJson = JSON.parse(match[1].trim());
|
||||
}
|
||||
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
|
||||
} catch (e) {
|
||||
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
try {
|
||||
const data = await fetchHonorData(cookieObject, groupCode, type);
|
||||
if (!data) return [];
|
||||
|
||||
return data.map((item: any) => ({
|
||||
user_id: item?.uin,
|
||||
nickname: item?.name,
|
||||
avatar: item?.avatar,
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user