Compare commits
250
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08b7ab7f15 | ||
|
|
e088167476 | ||
|
|
ee0f159b7e | ||
|
|
4a92dd71ad | ||
|
|
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 | ||
|
|
1bd0cbc359 | ||
|
|
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 | ||
|
|
fe567caeec | ||
|
|
941e60dea5 | ||
|
|
b99f5c0bf1 | ||
|
|
562fd4f7f9 | ||
|
|
ba899782fe | ||
|
|
6a7c9a5de1 | ||
|
|
7a2de230bf | ||
|
|
a460433175 | ||
|
|
24056c3de0 | ||
|
|
a07521d9de | ||
|
|
c62f51750a | ||
|
|
231d60411b | ||
|
|
b94775cb6f | ||
|
|
5524c73eed | ||
|
|
4c513c015d | ||
|
|
4a49c55775 | ||
|
|
e04a539b26 | ||
|
|
257686eac6 | ||
|
|
84e746c278 | ||
|
|
7ec479bb88 | ||
|
|
1ba45e2659 | ||
|
|
1d66693cc3 | ||
|
|
93b9b03667 | ||
|
|
51f46e15fd | ||
|
|
bee1e67c60 | ||
|
|
c6f4d5c5a2 | ||
|
|
82b52a3b2d | ||
|
|
360fe8bd49 | ||
|
|
71b0bda8f4 | ||
|
|
90884dfbb1 | ||
|
|
37dd7d2173 | ||
|
|
0c5eef87e6 | ||
|
|
0d54fd83c6 | ||
|
|
b3e37e2f7c | ||
|
|
b441647df4 | ||
|
|
d7252b6c31 | ||
|
|
593f5f42bc | ||
|
|
8a94188dc6 | ||
|
|
3e943e8f0d | ||
|
|
af1c50f4e7 | ||
|
|
bc9f7b49be | ||
|
|
a8661ea216 | ||
|
|
2d21316a74 | ||
|
|
ffe0c57abf | ||
|
|
d66f0b2c6b | ||
|
|
b40cee18cc | ||
|
|
b3df633c87 | ||
|
|
b2c53b56f7 | ||
|
|
917f08ce4d | ||
|
|
2c80e1a267 | ||
|
|
133cfc0c0e | ||
|
|
b959783ded | ||
|
|
655af833dc | ||
|
|
e2ee528939 | ||
|
|
463e0ffb5d | ||
|
|
c58f4d4085 | ||
|
|
16bdf1be1e | ||
|
|
0401ac4afb | ||
|
|
ad65aa5b1b | ||
|
|
a1a49944df | ||
|
|
caf724b25c | ||
|
|
7cef104f93 | ||
|
|
b89d51d984 | ||
|
|
47921eee12 | ||
|
|
9d55e86b1c | ||
|
|
7da52bc591 | ||
|
|
29f28d611f | ||
|
|
97ad2e22bb | ||
|
|
f7457e3e59 | ||
|
|
ee62f5aa0b | ||
|
|
78d42029ba | ||
|
|
6b236f70bf | ||
|
|
1a072bc6f1 | ||
|
|
5f88e00135 | ||
|
|
07449788c6 | ||
|
|
85b59bc3a1 | ||
|
|
7f53bcd085 | ||
|
|
29fa2696c8 | ||
|
|
37140b4ddd | ||
|
|
e6b609dd4e | ||
|
|
59cdfa98a2 | ||
|
|
ac10c663f1 | ||
|
|
030336a25c | ||
|
|
2e4dd9b01e | ||
|
|
a7fecf2a53 | ||
|
|
fe4af70562 | ||
|
|
564eec21bb | ||
|
|
b176e929b9 | ||
|
|
00a70b1ccc | ||
|
|
e438f353af | ||
|
|
ea5a1d505a | ||
|
|
545a732385 | ||
|
|
ada591b1b4 | ||
|
|
61e3867197 | ||
|
|
c9fa119a50 | ||
|
|
c2f22d8daf | ||
|
|
6abde40b9c | ||
|
|
6760008c5c | ||
|
|
37b835c537 | ||
|
|
9068ce3108 | ||
|
|
9216b54427 | ||
|
|
1b2dd836b8 | ||
|
|
fbb7504afe | ||
|
|
dd02535a73 | ||
|
|
069548918b | ||
|
|
8a49f0c21d | ||
|
|
49281726f1 | ||
|
|
269cd6f081 | ||
|
|
b32a8110af | ||
|
|
8506b60d07 | ||
|
|
e91a506bf5 | ||
|
|
ef4a321175 | ||
|
|
4fc52578a5 | ||
|
|
5ce8aa60de | ||
|
|
fd9a239241 | ||
|
|
8636222d91 | ||
|
|
6f506ff52c | ||
|
|
e917720d9d | ||
|
|
af80855d2d | ||
|
|
9a30a40a1f | ||
|
|
df5e3a26ac | ||
|
|
bf0a89e221 | ||
|
|
5a4028d5dc | ||
|
|
6f6ce1144b | ||
|
|
d02e7cc3ab | ||
|
|
bec23c4dbb | ||
|
|
c343021318 | ||
|
|
9ab4128799 | ||
|
|
95df5234fb | ||
|
|
9938545788 | ||
|
|
a7b3809a12 | ||
|
|
7149bc8689 | ||
|
|
c39b3f5c4e | ||
|
|
9802128421 | ||
|
|
2af273b9e2 | ||
|
|
144e0fdd59 | ||
|
|
a572d05c25 | ||
|
|
cb06624d12 | ||
|
|
7b93839186 | ||
|
|
d0085ec052 |
No files matched your search
@@ -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
|
||||
@@ -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 链接等
|
||||
@@ -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 前,请先确认已使用最新发布版本
|
||||
@@ -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: 暂时只提建议
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
name: Publish SDK to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/sdk/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: sdk-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build, test, and publish SDK
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check SDK
|
||||
run: pnpm --filter @snowluma/sdk typecheck
|
||||
|
||||
- name: Test SDK
|
||||
run: pnpm --filter @snowluma/sdk test
|
||||
|
||||
- name: Build SDK
|
||||
run: pnpm --filter @snowluma/sdk build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/sdk
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
|
||||
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
|
||||
|
||||
{
|
||||
echo "package_name=${package_name}"
|
||||
echo "package_version=${package_version}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
|
||||
echo "already_published=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
|
||||
else
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish SDK to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/sdk
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## SDK npm publish"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -0,0 +1,103 @@
|
||||
name: Publish UI to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/ui/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: ui-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build and publish UI
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check UI
|
||||
run: pnpm --filter @snowluma/ui typecheck
|
||||
|
||||
- name: Build UI
|
||||
run: pnpm --filter @snowluma/ui build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/ui
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
|
||||
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
|
||||
|
||||
{
|
||||
echo "package_name=${package_name}"
|
||||
echo "package_version=${package_version}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
|
||||
echo "already_published=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
|
||||
else
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish UI to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/ui
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## UI npm publish"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -11,6 +11,7 @@ dist/
|
||||
|
||||
/config/
|
||||
/data/
|
||||
logs/
|
||||
|
||||
# macOS metadata
|
||||
.DS_Store
|
||||
@@ -0,0 +1,90 @@
|
||||
# 贡献者公约 (Contributor Covenant Code of Conduct)
|
||||
|
||||
本文档改编自 [Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/),是 SnowLuma 社区共同遵守的行为准则。
|
||||
|
||||
## 我们的承诺
|
||||
|
||||
身为社区成员、贡献者、维护者,我们承诺:让每一个参与 SnowLuma 项目和社区的人,不因年龄、体型、可见或不可见的身体差异、身心障碍、族裔、性别特征、性别认同与表达、经验水平、教育背景、社会经济地位、国籍、外貌、种族、宗教信仰、或性取向,而遭受骚扰。
|
||||
|
||||
我们承诺以营造开放、热情、多元、包容、健康社区的方式行事和互动。
|
||||
|
||||
## 我们的准则
|
||||
|
||||
有助于建立正向社区环境的行为包括但不限于:
|
||||
|
||||
- 对他人展现同理心与善意
|
||||
- 尊重不同的意见、观点与经验
|
||||
- 给予并优雅地接受建设性反馈
|
||||
- 承担责任并向受我们错误影响的人致歉,并从中吸取教训
|
||||
- 关注的不仅是个人,更是整个社区的最大利益
|
||||
|
||||
不可接受的行为包括但不限于:
|
||||
|
||||
- 使用情色化的语言或意象,及任何形式的性关注或性骚扰
|
||||
- 嘲讽、侮辱或贬损性的评论,以及人身或政治攻击
|
||||
- 公开或私下的骚扰
|
||||
- 未经明确许可,公布他人的私人信息,例如物理或电子邮件地址
|
||||
- 其他在专业场合中可被合理认定为不当的行为
|
||||
|
||||
## 适用范围
|
||||
|
||||
本行为准则适用于所有社区场所,也适用于个人在公开场合代表社区时的言行。代表本社区的情形包括但不限于:使用项目官方电子邮件地址、通过项目官方社交媒体账号发文、以指定代表身份出席线上或线下活动。
|
||||
|
||||
具体到 SnowLuma,本准则适用于:
|
||||
|
||||
- 本仓库(含 issue、PR、discussion、commit message、code review 评论)
|
||||
- 项目相关的 QQ 群、Telegram 群以及未来可能新增的官方社群
|
||||
- 任何以 SnowLuma 名义对外发起的活动或交流
|
||||
|
||||
## 执行责任
|
||||
|
||||
社区维护者负责诠释并执行我们所认定的可接受行为标准,并将对任何他们认为不当、具威胁性、冒犯性或有害的行为采取适当且公正的纠正措施。
|
||||
|
||||
社区维护者有权且有责任删除、编辑或拒绝任何不符合本行为准则的评论、提交、代码、wiki 编辑、issue 及其他贡献,并将在适当时机说明做出审核决策的理由。
|
||||
|
||||
## 举报方式
|
||||
|
||||
如果你目击或亲身经历了不当行为,请通过以下任一渠道**私下**联系维护者:
|
||||
|
||||
- QQ:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)(私聊管理员,请勿在群内公开)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)(私聊管理员)
|
||||
|
||||
请勿在 GitHub issue 或公开频道直接发布举报内容,以免对相关方造成二次伤害。
|
||||
|
||||
所有投诉都会被及时和公平地审查与调查。所有社区维护者都有义务尊重举报者的隐私与人身安全。
|
||||
|
||||
## 执行准则
|
||||
|
||||
社区维护者将依据以下「社区影响指引」来判定违反本行为准则之行为的处置方式:
|
||||
|
||||
### 1. 更正 (Correction)
|
||||
|
||||
**社区影响**:使用了不恰当的言语,或其他在社区中被视为不专业或不受欢迎的行为。
|
||||
|
||||
**后果**:由社区维护者私下提出书面警告,明确指出该行为违反规则之处并解释为何不妥。可能要求公开致歉。
|
||||
|
||||
### 2. 警告 (Warning)
|
||||
|
||||
**社区影响**:通过单一事件或一系列行为造成违规。
|
||||
|
||||
**后果**:警告并说明持续行为的后果。在指定时间内禁止与相关人员互动,包括主动联系本行为准则执行者。这包括避免在社区场所及外部渠道(如社交媒体)的互动。违反这些条款可能导致临时或永久封禁。
|
||||
|
||||
### 3. 临时封禁 (Temporary Ban)
|
||||
|
||||
**社区影响**:严重违反社区准则,包括持续的不当行为。
|
||||
|
||||
**后果**:在指定时间内禁止与社区进行任何形式的互动或公开交流。在此期间不得与相关人员有任何公开或私下的互动,包括主动联系本行为准则执行者。违反这些条款可能导致永久封禁。
|
||||
|
||||
### 4. 永久封禁 (Permanent Ban)
|
||||
|
||||
**社区影响**:表现出违反社区准则的模式,包括持续的不当行为、骚扰个人、或对某类群体进行攻击或贬低。
|
||||
|
||||
**后果**:永久禁止在社区内进行任何形式的公开互动。
|
||||
|
||||
## 致谢
|
||||
|
||||
本行为准则改编自 [Contributor Covenant 2.1 版](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html)。
|
||||
|
||||
社区影响指引灵感来自 [Mozilla 的行为准则执行阶梯](https://github.com/mozilla/diversity)。
|
||||
|
||||
如需了解本准则的常见问题,请参阅 [FAQ](https://www.contributor-covenant.org/faq)。中文版译本可参考 [Contributor Covenant 中文翻译](https://www.contributor-covenant.org/zh-cn/version/2/1/code_of_conduct/)。
|
||||
+212
-31
@@ -1,49 +1,233 @@
|
||||
# 贡献指南
|
||||
|
||||
## 分支模型
|
||||
欢迎!如果你正在阅读这份文档,多半是因为你想给 SnowLuma 提一个 PR、修一个 bug,或者只是想了解这个项目是怎么运作的。无论你是第一次接触开源、还是已经有十年经验,我们都希望让你尽快上手。
|
||||
|
||||
参与项目即视为你同意遵守 [行为准则(Code of Conduct)](./CODE_OF_CONDUCT.md)。在开始之前请花两分钟读一下,它定义了我们希望社区维持的氛围。
|
||||
|
||||
---
|
||||
|
||||
## 在动手之前
|
||||
|
||||
SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时可能变化**。如果你打算做较大的改动,强烈建议先在 issue 或者社群里和维护者对齐一下方向,避免做了一半发现已经被另一条路替代。
|
||||
|
||||
不知道从哪里入手?以下几类贡献最容易被合并:
|
||||
|
||||
- 修复你在使用中遇到的具体 bug,附最小复现步骤。
|
||||
- 改善错误提示、文档、注释、类型签名。
|
||||
- 给已有模块补测试,尤其是 `packages/core` 下覆盖率较低的部分。
|
||||
- 实现 [RoadMap.md](./RoadMap.md) 中列出的、还没被认领的项。
|
||||
|
||||
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
|
||||
|
||||
---
|
||||
|
||||
## 项目结构速览
|
||||
|
||||
这是一个 pnpm workspace monorepo,主要 package 如下:
|
||||
|
||||
| 路径 | 作用 |
|
||||
| --- | --- |
|
||||
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
|
||||
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
|
||||
| `packages/runtime` | 运行时辅助包 |
|
||||
| `packages/websocket` | WebSocket 实现 |
|
||||
| `packages/webui` | 基于 Vite + React 的前端控制台 |
|
||||
| `tools/` | 版本管理、发布脚本 |
|
||||
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
|
||||
|
||||
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
|
||||
|
||||
---
|
||||
|
||||
## 本地开发环境
|
||||
|
||||
### 系统要求
|
||||
|
||||
- **Node.js ≥ 22**(`engines` 字段强制,低版本会报错)
|
||||
- **pnpm 10.28.0+**(项目通过 `packageManager` 字段锁定,建议用 `corepack enable` 安装匹配版本)
|
||||
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
|
||||
|
||||
### 拉代码、装依赖、跑起来
|
||||
|
||||
```bash
|
||||
# 1. Fork 仓库后克隆你自己的 fork
|
||||
git clone https://github.com/<你的用户名>/SnowLuma.git
|
||||
cd SnowLuma
|
||||
|
||||
# 2. 切到 dev 分支(所有开发都基于 dev,不是 main)
|
||||
git checkout dev
|
||||
|
||||
# 3. 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 4. 跑类型检查,确认环境 OK
|
||||
pnpm typecheck
|
||||
|
||||
# 5. 跑测试
|
||||
pnpm test
|
||||
|
||||
# 6. 启动开发模式
|
||||
pnpm dev # core
|
||||
pnpm dev:web # webui
|
||||
```
|
||||
|
||||
如果 `pnpm install` 卡住或报错,先确认 Node 版本和 pnpm 版本,再看 `.npmrc` 里是否配置了你环境下可用的 registry。
|
||||
|
||||
---
|
||||
|
||||
## 第一次提交 PR
|
||||
|
||||
### 1. 创建分支
|
||||
|
||||
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
|
||||
|
||||
```bash
|
||||
git checkout dev
|
||||
git pull upstream dev # 假设你把官方仓库设为 upstream remote
|
||||
git checkout -b fix/onebot-mention-encoding
|
||||
```
|
||||
|
||||
分支命名没有强制规则,但建议用 `fix/...`、`feat/...`、`docs/...`、`refactor/...` 这种前缀,便于一眼看出意图。
|
||||
|
||||
### 2. 写代码
|
||||
|
||||
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
|
||||
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
|
||||
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
|
||||
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
|
||||
|
||||
提交之前请本地跑一遍:
|
||||
|
||||
```bash
|
||||
pnpm typecheck
|
||||
pnpm test
|
||||
```
|
||||
|
||||
CI 上跑的是同一套检查,本地通过几乎能保证 CI 通过。
|
||||
|
||||
### 3. 提交信息
|
||||
|
||||
我们大致遵循 [Conventional Commits](https://www.conventionalcommits.org/zh-hans/v1.0.0/):
|
||||
|
||||
```
|
||||
<type>(<scope>): <subject>
|
||||
|
||||
<body>
|
||||
```
|
||||
|
||||
`type` 常用:`feat` / `fix` / `docs` / `refactor` / `test` / `chore` / `perf`。
|
||||
`scope` 常用:`core` / `sdk` / `webui` / `onebot` / `bridge` / `protocol` 等模块名。
|
||||
|
||||
示例:
|
||||
|
||||
```
|
||||
fix(onebot): handle empty mention segments in group messages
|
||||
refactor(bridge): extract BridgeInterface as the OneBot-facing seam
|
||||
docs: clarify dev environment setup steps
|
||||
```
|
||||
|
||||
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
|
||||
|
||||
### 4. 推送并发起 PR
|
||||
|
||||
```bash
|
||||
git push origin fix/onebot-mention-encoding
|
||||
```
|
||||
|
||||
到 GitHub 上发起 PR,**目标分支选 `dev`**。请在 PR 描述里写明:
|
||||
|
||||
- 这个 PR 解决什么问题 / 实现什么功能。
|
||||
- 主要的实现思路(如果有非显然的取舍)。
|
||||
- 测试方式(你跑了什么、怎么验证有效)。
|
||||
- 关联的 issue(如有)。
|
||||
|
||||
### 5. Code Review 与合并
|
||||
|
||||
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
|
||||
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
|
||||
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
|
||||
|
||||
---
|
||||
|
||||
## 风格与约定
|
||||
|
||||
### 代码风格
|
||||
|
||||
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
|
||||
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
|
||||
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
|
||||
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
|
||||
|
||||
### 测试
|
||||
|
||||
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
|
||||
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
|
||||
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
|
||||
|
||||
### 文档
|
||||
|
||||
- 用户/贡献者可见的行为变化,需要相应更新 README 或对应 package 下的文档。
|
||||
- SDK 的破坏性变更必须更新 `packages/sdk/CHANGELOG.md` 和 `packages/sdk/VERSIONING.md`。
|
||||
|
||||
---
|
||||
|
||||
## 报告 Bug / 请求功能
|
||||
|
||||
- **Bug 报告**:开 issue,附最小复现步骤、期望行为、实际行为、版本号、运行环境。能附上日志最好。
|
||||
- **功能请求**:先描述你想解决的实际场景,再描述你想要的接口。维护者更在意"为什么需要"而不是"具体怎么做"。
|
||||
- **安全问题**:请勿公开发 issue,先通过社群私聊联系维护者。
|
||||
|
||||
社群入口(见 [README](./README.md)):
|
||||
|
||||
- QQ:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
|
||||
|
||||
---
|
||||
|
||||
## 维护者参考:release & 自动合并流程
|
||||
|
||||
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
|
||||
|
||||
### 分支模型
|
||||
|
||||
SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先提交到 `dev`。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
|
||||
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
|
||||
|
||||
## 把 `dev` 合并到 `main`
|
||||
### 把 `dev` 合并到 `main`
|
||||
|
||||
新增工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。三种触发方式:
|
||||
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
|
||||
|
||||
无论使用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
|
||||
|
||||
### 1. 提交信息前缀(推荐日常使用)
|
||||
#### 1. 提交信息前缀(推荐日常使用)
|
||||
|
||||
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
|
||||
|
||||
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
|
||||
|
||||
> 注意:是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
|
||||
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
|
||||
|
||||
### 2. 推送 `chore.*` Tag
|
||||
#### 2. 推送 `chore.*` Tag
|
||||
|
||||
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发本工作流。这是和发布 tag 解耦的「合并触发 tag」:
|
||||
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
|
||||
|
||||
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
|
||||
- `v*` → 仅触发 `release.yml`(构建发布产物)
|
||||
|
||||
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已经过完所有检查的 `main` HEAD 构建。
|
||||
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
|
||||
|
||||
### 3. 手动触发
|
||||
#### 3. 手动触发
|
||||
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
|
||||
|
||||
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
|
||||
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
|
||||
|
||||
工作流会按照当前 `dev` 与 `main` 的差异开 / 更新 PR。
|
||||
### 启用 `main` 分支保护(必做)
|
||||
|
||||
## 启用 `main` 分支保护(必做)
|
||||
|
||||
仓库管理员需要在 GitHub 上为 `main` 配置一条规则集(Repository Rules)或经典分支保护,至少满足:
|
||||
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
|
||||
|
||||
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
|
||||
2. 选择 `main` 作为目标分支。
|
||||
@@ -62,7 +246,7 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
|
||||
|
||||
## 必需的 Secrets
|
||||
### 必需的 Secrets
|
||||
|
||||
`promote-dev-to-main.yml` 复用 `SnowLumaNative/build-native.yml` 同一个 GitHub App。请确认 SnowLuma 仓库(或 organization)级别已经配置:
|
||||
|
||||
@@ -71,22 +255,9 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
|
||||
|
||||
## 本地工作流速查
|
||||
### 本地工作流速查(维护者)
|
||||
|
||||
```bash
|
||||
# 切到 dev 开发
|
||||
git checkout dev
|
||||
git pull
|
||||
|
||||
# 写代码 / 跑测试
|
||||
pnpm install
|
||||
pnpm typecheck
|
||||
pnpm -s --filter @snowluma/core test
|
||||
|
||||
# 普通提交(不会触发 promote)
|
||||
git commit -m "fix: something"
|
||||
git push
|
||||
|
||||
# 把 dev 合入 main(三选一)
|
||||
|
||||
# 方式 A:commit-msg 前缀
|
||||
@@ -104,3 +275,13 @@ git checkout main && git pull
|
||||
git tag v1.7.0
|
||||
git push origin v1.7.0 # → 仅触发 release.yml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 还有问题?
|
||||
|
||||
- 看一下已有的 issue 和 PR,可能你的问题已经被讨论过。
|
||||
- 去社群问一句(QQ / TG 链接见上方)。
|
||||
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
|
||||
|
||||
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️
|
||||
@@ -1,22 +1,131 @@
|
||||
# ❄️ SnowLuma
|
||||
> Next Remote Protocol Framework.
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
</p>
|
||||
|
||||
## 关于项目
|
||||
项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
|
||||
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
|
||||
<a href="https://t.me/napcatqq">Telegram</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
|
||||
## 特性
|
||||
|
||||
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
|
||||
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
|
||||
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
|
||||
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
|
||||
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
|
||||
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
|
||||
或从源码开发:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
```
|
||||
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
|
||||
## 工作区
|
||||
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 包 | 说明 |
|
||||
| --- | --- |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@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 管理面板前端。 |
|
||||
|
||||
## 架构
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
|
||||
## 开发命令
|
||||
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
|
||||
## 鸣谢
|
||||
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||
|
||||
[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
|
||||
## 辅助编程
|
||||
## 贡献者
|
||||
|
||||
推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
|
||||
本项目大量使用Ai技术。
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## 加入我们
|
||||
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
## Star 趋势
|
||||
|
||||
[SnowLuma-TG](https://t.me/napcatqq)
|
||||
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
|
||||
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
+8
-2
@@ -1,3 +1,9 @@
|
||||
# V2.0.0 前计划
|
||||
- [ ] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
|
||||
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [x] 优化Debug体验,实现免打包Debug,同时数据目录正确。(Proton兜底思路改成ts+map提取类型,用于tsx和nodejs,vite正常打包的时候剥离)
|
||||
- [x] 拆分core,架构为Common(公共能力) OneBot(外层封装 协议转换),Core(Api raw能力,基础能力等功能),Bridge(封装和关键解析能力和Event message/sent group/member_add ...)
|
||||
- [x] 剥离ProtocolBuffer定义到单独package。
|
||||
- [x] 整理发送和解析消息链路,提高性能。`packages/{bridge,onebot}/bench/*.bench.ts` 拿到了基线数字。最大瓶颈不在 protobuf 解析(已经 sub-μs),而在两处 SQLite 反复 `db.prepare(sql)` 重 parse —— 把 `node:sqlite`(实验性)换成 `better-sqlite3`(稳定)+ 缓存 prepared statements 后:`group_member_join` 全链路 17.5μs → 4.7μs(**3.7x**),`storeMeta` 17μs → 11μs,`storeEvent` 23μs → 18μs,`findMeta` 5.4μs → 1.3μs(**4x**)。送侧组合 hot path(storeMeta + storeEvent)单条消息 40μs → 29μs。另外干掉 `Buffer.from(pkt.body)` 的冗余 alloc(pkt.body 本来就是 Uint8Array)。`elementsToJson` 同步快路径 / WAL checkpoint 调参 / JSON 序列化替换 等次要优化点保留,待真有 throughput 压力再做。
|
||||
- [x] 对齐NapCat设计采用Api层,挂到ctx,Core与Onebot都这么设计。
|
||||
- [x] Core 侧:13 个 Api 类(message/contacts/groupAdmin/groupFile/groupAlbum/interaction/friend/profile/forward/misc/extras/web)已挂到 `bridge.apis.<area>.method()`,`BridgeInterface` + `actions/*` 全部删除。
|
||||
- [x] OneBot 侧:`ApiActionContext` 砍掉 ~40 个纯转发字段(groupAdmin / groupFile / groupAlbum / friend / interaction / message / profile / web 八区),actions 直接 `ctx.bridge.apis.<area>.method(...)` 调用 Core 的 Api 层。保留的 ~30 个字段全是真组合 helper(module-level send/forward、message store reads、meta-lookup composers)。完全 NapCat 化(class-per-action / TypeBox schema / actionName 枚举 / auto-register decorator)暂未做——profile 文档/工具链需求出现后再做。
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "./qq.schema.json",
|
||||
"version": 1,
|
||||
"updatedAt": "2026-05-16T00:00:00Z",
|
||||
"policy": {
|
||||
"allowUnknown": true,
|
||||
"warnUnknown": true
|
||||
},
|
||||
"knownGoodVersions": [],
|
||||
"knownBadVersions": [],
|
||||
"minVersion": null,
|
||||
"notes": [
|
||||
"QQ 兼容性 manifest — Desktop 启动时拉 https://raw.githubusercontent.com/SnowLuma/SnowLuma/main/compat/qq.json 校验本地 QQ 版本",
|
||||
"policy.allowUnknown = true: 任何不在 knownBadVersions 里的版本都允许(理论上所有 QQ 新版本都可用)",
|
||||
"knownBadVersions: 列在这里的版本 Desktop 会拒绝注入,弹出引导让用户切版本",
|
||||
"minVersion: 设为 SemVer 字符串则更早的版本会被拒",
|
||||
"知道某个版本会破坏 Hook 后把它加进 knownBadVersions,加 reason 字段说明"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "SnowLuma QQ compatibility manifest",
|
||||
"type": "object",
|
||||
"required": ["version", "policy", "knownGoodVersions", "knownBadVersions"],
|
||||
"properties": {
|
||||
"$schema": { "type": "string" },
|
||||
"version": { "type": "integer", "const": 1 },
|
||||
"updatedAt": { "type": "string", "format": "date-time" },
|
||||
"policy": {
|
||||
"type": "object",
|
||||
"required": ["allowUnknown"],
|
||||
"properties": {
|
||||
"allowUnknown": {
|
||||
"type": "boolean",
|
||||
"description": "若 true,未在 known* 中列出的版本视为允许;若 false,需明确出现在 knownGoodVersions"
|
||||
},
|
||||
"warnUnknown": {
|
||||
"type": "boolean",
|
||||
"description": "未列出的版本启动时是否弹警告"
|
||||
}
|
||||
}
|
||||
},
|
||||
"knownGoodVersions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["version"],
|
||||
"properties": {
|
||||
"version": { "type": "string", "description": "QQ 版本号字符串,如 '9.9.20.123'" },
|
||||
"note": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"knownBadVersions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["version"],
|
||||
"properties": {
|
||||
"version": { "type": "string" },
|
||||
"reason": { "type": "string" },
|
||||
"fixedInDesktopVersion": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"minVersion": {
|
||||
"type": ["string", "null"],
|
||||
"description": "最低支持版本(SemVer),null = 不限"
|
||||
},
|
||||
"notes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
|
||||
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': 'off',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
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
-7
@@ -1,35 +1,49 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "0.1.0",
|
||||
"version": "1.9.1",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm --filter @snowluma/core build",
|
||||
"build:sdk": "pnpm --filter @snowluma/sdk build",
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"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",
|
||||
"start": "node dist/index.mjs"
|
||||
"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",
|
||||
"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": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// Receive-chain micro-benchmark (RoadMap #5).
|
||||
//
|
||||
// Measured paths:
|
||||
// 1. `parseMsgPush` — pure decode + decoder dispatch (no SQLite, no
|
||||
// event emit). The protobuf workload only.
|
||||
// 2. `IncomingPacketPipeline.process` — full receive pipeline:
|
||||
// decode + decoder + handleSideEffects (identity-service SQLite
|
||||
// writes) + event emit through BridgeEventBus.
|
||||
//
|
||||
// Run via: pnpm -F @snowluma/bridge bench
|
||||
//
|
||||
// Output is `tinybench` ops/sec — vitest's built-in `bench()` is just a
|
||||
// thin wrapper. Run before AND after a perf commit; the delta is what
|
||||
// matters (RoadMap #5 commit messages quote the % shift).
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { bench, describe } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { PushMsg } from '@snowluma/proto-defs/message';
|
||||
import type { GroupChange } from '@snowluma/proto-defs/notify';
|
||||
import { parseMsgPush, MSG_PUSH_CMD } from '../src/msg-push/index';
|
||||
import { IdentityService } from '../src/identity-service';
|
||||
import { BridgeEventBus } from '../src/event-bus';
|
||||
import { IncomingPacketPipeline } from '../src/packet-pipeline';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
const SENDER_UIN = 22222;
|
||||
const SENDER_UID = 'u_sender';
|
||||
|
||||
// ─── Synthetic packet builders ───
|
||||
|
||||
function makeGroupTextPacket(): PacketInfo {
|
||||
const body = protobuf_encode<PushMsg>({
|
||||
message: {
|
||||
responseHead: { fromUin: SENDER_UIN, fromUid: SENDER_UID },
|
||||
contentHead: {
|
||||
msgType: 82,
|
||||
subType: 1,
|
||||
sequence: 1234,
|
||||
timestamp: 1710000000,
|
||||
msgId: 999999,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
elems: [{ text: { str: 'hello world from bench' } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
status: 0,
|
||||
grpInfo: { groupUin: GROUP_ID },
|
||||
} as any);
|
||||
return {
|
||||
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD,
|
||||
seqId: 1, retCode: 0, fromClient: false, body,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMixedPacket(): PacketInfo {
|
||||
const body = protobuf_encode<PushMsg>({
|
||||
message: {
|
||||
responseHead: { fromUin: SENDER_UIN, fromUid: SENDER_UID },
|
||||
contentHead: {
|
||||
msgType: 82,
|
||||
subType: 1,
|
||||
sequence: 1235,
|
||||
timestamp: 1710000000,
|
||||
msgId: 999998,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
elems: [
|
||||
{ text: { str: '@some_user ' } },
|
||||
{ face: { index: 76 } },
|
||||
{ text: { str: 'hello ' } },
|
||||
{ srcMsg: { origSeqs: [4242] } },
|
||||
{ text: { str: ' world' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
status: 0,
|
||||
grpInfo: { groupUin: GROUP_ID },
|
||||
} as any);
|
||||
return {
|
||||
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD,
|
||||
seqId: 2, retCode: 0, fromClient: false, body,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupJoinPacket(): PacketInfo {
|
||||
const content = protobuf_encode<GroupChange>({
|
||||
groupUin: GROUP_ID,
|
||||
memberUid: 'u_newcomer',
|
||||
});
|
||||
const body = protobuf_encode<PushMsg>({
|
||||
message: {
|
||||
responseHead: { fromUin: GROUP_ID },
|
||||
contentHead: { msgType: 33, timestamp: 1710000000 },
|
||||
body: { msgContent: content },
|
||||
},
|
||||
status: 0,
|
||||
} as any);
|
||||
return {
|
||||
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD,
|
||||
seqId: 3, retCode: 0, fromClient: false, body,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Setup helpers ───
|
||||
|
||||
// In-memory identity (no SQLite writes) — used for the "pure decode"
|
||||
// bench to isolate proton + decoder cost from DB cost.
|
||||
function makeIdentity(): IdentityService {
|
||||
return IdentityService.memory(SELF_UIN);
|
||||
}
|
||||
|
||||
// SQLite-backed identity in a temp file — used for the full-pipeline
|
||||
// bench so we capture per-event identity writes. Temp dir is cleaned
|
||||
// implicitly on process exit (OS tmp policy); we don't need to unlink
|
||||
// because each `bench()` recreates it.
|
||||
function makeIdentityWithDb(): IdentityService {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-bench-recv-'));
|
||||
return new IdentityService(SELF_UIN, path.join(dir, 'identity.db'));
|
||||
}
|
||||
|
||||
function makePipeline(identity: IdentityService): IncomingPacketPipeline {
|
||||
const events = new BridgeEventBus();
|
||||
events.on('group_message', () => { /* drain */ });
|
||||
events.on('group_member_join', () => { /* drain */ });
|
||||
const pipeline = new IncomingPacketPipeline({
|
||||
identity,
|
||||
events,
|
||||
refreshMemberCache: async () => false,
|
||||
});
|
||||
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
// ─── Benches ───
|
||||
|
||||
const groupText = makeGroupTextPacket();
|
||||
const groupMixed = makeGroupMixedPacket();
|
||||
const groupJoin = makeGroupJoinPacket();
|
||||
|
||||
describe('parseMsgPush — pure decode + dispatch (no SQLite, no emit)', () => {
|
||||
const identityPure = makeIdentity();
|
||||
bench('group_message (text only)', () => {
|
||||
parseMsgPush(groupText, identityPure);
|
||||
});
|
||||
bench('group_message (5 mixed elements)', () => {
|
||||
parseMsgPush(groupMixed, identityPure);
|
||||
});
|
||||
bench('group_member_join', () => {
|
||||
parseMsgPush(groupJoin, identityPure);
|
||||
});
|
||||
});
|
||||
|
||||
describe('IncomingPacketPipeline.process — full pipeline (with SQLite identity writes)', () => {
|
||||
const pipelineText = makePipeline(makeIdentityWithDb());
|
||||
const pipelineMixed = makePipeline(makeIdentityWithDb());
|
||||
const pipelineJoin = makePipeline(makeIdentityWithDb());
|
||||
|
||||
bench('group_message (text only)', () => {
|
||||
pipelineText.process(groupText);
|
||||
});
|
||||
bench('group_message (5 mixed elements)', () => {
|
||||
pipelineMixed.process(groupMixed);
|
||||
});
|
||||
bench('group_member_join', () => {
|
||||
pipelineJoin.process(groupJoin);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/bridge/<x>'`.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./events": {
|
||||
"types": "./src/events.ts",
|
||||
"default": "./src/events.ts"
|
||||
},
|
||||
"./event-bus": {
|
||||
"types": "./src/event-bus.ts",
|
||||
"default": "./src/event-bus.ts"
|
||||
},
|
||||
"./identity-service": {
|
||||
"types": "./src/identity-service.ts",
|
||||
"default": "./src/identity-service.ts"
|
||||
},
|
||||
"./packet-pipeline": {
|
||||
"types": "./src/packet-pipeline.ts",
|
||||
"default": "./src/packet-pipeline.ts"
|
||||
},
|
||||
"./element-builder": {
|
||||
"types": "./src/element-builder.ts",
|
||||
"default": "./src/element-builder.ts"
|
||||
},
|
||||
"./bridge-oidb": {
|
||||
"types": "./src/bridge-oidb.ts",
|
||||
"default": "./src/bridge-oidb.ts"
|
||||
},
|
||||
"./bridge-context": {
|
||||
"types": "./src/bridge-context.ts",
|
||||
"default": "./src/bridge-context.ts"
|
||||
},
|
||||
"./qq-info": {
|
||||
"types": "./src/qq-info.ts",
|
||||
"default": "./src/qq-info.ts"
|
||||
},
|
||||
"./format": {
|
||||
"types": "./src/format.ts",
|
||||
"default": "./src/format.ts"
|
||||
},
|
||||
"./msg-push": {
|
||||
"types": "./src/msg-push/index.ts",
|
||||
"default": "./src/msg-push/index.ts"
|
||||
},
|
||||
"./msg-push/registry": {
|
||||
"types": "./src/msg-push/registry.ts",
|
||||
"default": "./src/msg-push/registry.ts"
|
||||
},
|
||||
"./msg-push/context": {
|
||||
"types": "./src/msg-push/context.ts",
|
||||
"default": "./src/msg-push/context.ts"
|
||||
},
|
||||
"./msg-push/decoders/event-0x2dc": {
|
||||
"types": "./src/msg-push/decoders/event-0x2dc.ts",
|
||||
"default": "./src/msg-push/decoders/event-0x2dc.ts"
|
||||
},
|
||||
"./highway": {
|
||||
"types": "./src/highway/highway-client.ts",
|
||||
"default": "./src/highway/highway-client.ts"
|
||||
},
|
||||
"./highway/utils": {
|
||||
"types": "./src/highway/utils.ts",
|
||||
"default": "./src/highway/utils.ts"
|
||||
},
|
||||
"./highway/pipeline": {
|
||||
"types": "./src/highway/pipeline.ts",
|
||||
"default": "./src/highway/pipeline.ts"
|
||||
},
|
||||
"./highway/image-upload": {
|
||||
"types": "./src/highway/image-upload.ts",
|
||||
"default": "./src/highway/image-upload.ts"
|
||||
},
|
||||
"./highway/ptt-upload": {
|
||||
"types": "./src/highway/ptt-upload.ts",
|
||||
"default": "./src/highway/ptt-upload.ts"
|
||||
},
|
||||
"./highway/video-upload": {
|
||||
"types": "./src/highway/video-upload.ts",
|
||||
"default": "./src/highway/video-upload.ts"
|
||||
},
|
||||
"./highway/ffmpeg-addon": {
|
||||
"types": "./src/highway/ffmpeg-addon.ts",
|
||||
"default": "./src/highway/ffmpeg-addon.ts"
|
||||
},
|
||||
"./web/group-album": {
|
||||
"types": "./src/web/group-album.ts",
|
||||
"default": "./src/web/group-album.ts"
|
||||
},
|
||||
"./web/group-essence": {
|
||||
"types": "./src/web/group-essence.ts",
|
||||
"default": "./src/web/group-essence.ts"
|
||||
},
|
||||
"./web/group-honor": {
|
||||
"types": "./src/web/group-honor.ts",
|
||||
"default": "./src/web/group-honor.ts"
|
||||
},
|
||||
"./web/group-notice": {
|
||||
"types": "./src/web/group-notice.ts",
|
||||
"default": "./src/web/group-notice.ts"
|
||||
},
|
||||
"./web/request-util": {
|
||||
"types": "./src/web/request-util.ts",
|
||||
"default": "./src/web/request-util.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "vitest bench --run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// BridgeContext — the protocol-layer surface that anything inside
|
||||
// @snowluma/bridge (highway uploaders, OIDB envelope helper, element
|
||||
// builder, msg-push parsers) accepts when it needs `bridge.identity`
|
||||
// or `bridge.sendRawPacket` plus the upload-metadata cache.
|
||||
//
|
||||
// Deliberately apis-less: @snowluma/bridge knows nothing about the
|
||||
// `apis.<area>.method()` hub that lives in @snowluma/core, so the
|
||||
// type that bridge code accepts must NOT mention `ApiHub`. The api-
|
||||
// layer's own extended context (with `apis: ApiHub`) lives at
|
||||
// @snowluma/core's same-named file and `extends` this one — Api
|
||||
// classes import from THERE, bridge helpers import from HERE.
|
||||
//
|
||||
// The concrete `Bridge` class (in @snowluma/core) implements the
|
||||
// extended interface, which is a superset of this one. Passing a
|
||||
// `Bridge` where a slim `BridgeContext` is expected is a free upcast.
|
||||
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
/**
|
||||
* Metadata remembered after `upload_group_file` / `upload_private_file`
|
||||
* succeeds. Lets the OneBot send-message path reconstruct the full
|
||||
* payload when the caller only echoes the `file_id` back later. Lives
|
||||
* here (not on @snowluma/core's `bridge.ts`) so element-builder + the
|
||||
* forward-builder — both inside @snowluma/bridge — can read the cache
|
||||
* without circular-importing @snowluma/core.
|
||||
*/
|
||||
export interface UploadedFileMeta {
|
||||
fileId: string;
|
||||
scope: 'group' | 'private';
|
||||
/** Group id if scope='group', else `undefined`. */
|
||||
groupId?: number;
|
||||
/** Friend uin if scope='private', else `undefined`. */
|
||||
userId?: number;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
fileMd5: Uint8Array;
|
||||
fileSha1: Uint8Array;
|
||||
/** Server-issued hash returned alongside the upload (private only). */
|
||||
fileHash?: string;
|
||||
/** Insert time — used to evict the oldest entry when the cache fills. */
|
||||
rememberedAt: number;
|
||||
}
|
||||
|
||||
export interface BridgeContext {
|
||||
// ── Per-instance state (one set per QQ account in a multi-account
|
||||
// runtime; `BridgeManager` allocates one `Bridge` per uin and
|
||||
// each Bridge owns its own identity/events/pipeline/apis). ──
|
||||
readonly identity: IdentityService;
|
||||
readonly events: BridgeEventBus;
|
||||
|
||||
// ── Raw I/O ──
|
||||
/** Escape hatch for arbitrary protocol calls (used by Api classes
|
||||
* and by the `send_packet` OneBot action). Every typed wrapper on an
|
||||
* Api class eventually routes through here. */
|
||||
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
/** uin → uid lookup (cached in IdentityService). `groupId` is an
|
||||
* optional hint that lets the resolver fall back to a group-member
|
||||
* roster when the friend list doesn't have the uin. */
|
||||
resolveUserUid(uin: number, groupId?: number): Promise<string>;
|
||||
|
||||
// ── Send-side protocol helpers (Api classes that build a
|
||||
// `SendMessageRequest` need these monotonic generators to fill in
|
||||
// `clientSequence` and `random`). They were previously `private`
|
||||
// on Bridge — promoted to public so the new Api classes can call
|
||||
// them without `(bridge as any).nextXxx()`. ──
|
||||
nextMessageRandom(): number;
|
||||
nextClientSequence(): number;
|
||||
|
||||
// ── Uploaded-file metadata cache ──
|
||||
//
|
||||
// Bookkeeping shared between `GroupFileApi.upload*File` (writes the
|
||||
// tuple at upload time) and `MessageApi.sendPrivateMessage` (reads
|
||||
// it on later `send_msg` calls that carry only a file_id). Lives at
|
||||
// this layer rather than inside `GroupFileApi` because the message
|
||||
// send path is what queries the cache, and it shouldn't have to
|
||||
// reach into a different Api class for an infrastructure lookup.
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void;
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
|
||||
|
||||
/**
|
||||
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
|
||||
* encoding happens here — pair with `encodeOidbEnv<T>` to produce the
|
||||
* wire bytes.
|
||||
*
|
||||
* The `isUid` flag sets the envelope `reserved` field to 1; despite the
|
||||
* name (kept for back-compat with the legacy API), `reserved = 1`
|
||||
* empirically signals the UIN-form variant of an OIDB call. Omit
|
||||
* (default false) for genuinely UID-keyed calls.
|
||||
*/
|
||||
export function makeOidbEnvelope<T>(
|
||||
oidbCmd: number,
|
||||
subCmd: number,
|
||||
body: T,
|
||||
isUid: boolean = false,
|
||||
): OidbBase<T> {
|
||||
return {
|
||||
command: oidbCmd,
|
||||
subCommand: subCmd,
|
||||
errorCode: 0,
|
||||
body,
|
||||
errorMsg: '',
|
||||
reserved: isUid ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue one OIDB request and return the raw response bytes.
|
||||
*
|
||||
* Typical usage:
|
||||
* const env = makeOidbEnvelope<MyReq>(0x1253, 1, value);
|
||||
* const buf = await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
|
||||
* const resp = decodeOidbEnv<MyResp>(buf).body;
|
||||
*
|
||||
* Fire-and-check (no body decode):
|
||||
* await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
|
||||
*
|
||||
* Always peeks at the envelope errorCode via the non-generic
|
||||
* `OidbBaseMeta` view so a server-side rejection cannot slip past
|
||||
* silently. Returns the raw response bytes (empty `Uint8Array` if the
|
||||
* packet carried no payload).
|
||||
*/
|
||||
export async function runOidb(
|
||||
bridge: BridgeContext,
|
||||
cmd: string,
|
||||
envelopeBytes: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<Uint8Array> {
|
||||
const result = await bridge.sendRawPacket(cmd, envelopeBytes, timeoutMs);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
const bytes = result.responseData ?? new Uint8Array(0);
|
||||
if (bytes.length > 0) {
|
||||
const meta = protobuf_decode<OidbBaseMeta>(bytes);
|
||||
const code = meta?.errorCode;
|
||||
if (code && code !== 0) {
|
||||
throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
import type { MessageElement } from './events';
|
||||
import { uploadImageMsgInfo } from './highway/image-upload';
|
||||
import { hexToBytes } from './highway/pipeline';
|
||||
import { uploadPttMsgInfo } from './highway/ptt-upload';
|
||||
import { uploadVideoMsgInfo } from './highway/video-upload';
|
||||
import type {
|
||||
MarkdownData,
|
||||
MentionExtraSend,
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element';
|
||||
|
||||
type ProtoElem = Partial<Elem>;
|
||||
|
||||
export interface SendContext {
|
||||
bridge: BridgeContext;
|
||||
groupId?: number;
|
||||
userUid?: string;
|
||||
/**
|
||||
* Set by the forward-message upload path. When `true`, file segments
|
||||
* are encoded as receive-side wire shapes (group → `transElem(24)`,
|
||||
* c2c → caller writes `body.msgContent` separately) instead of being
|
||||
* dropped. The QQ-NT server rejects outgoing PbSendMsg with
|
||||
* `transElem(24)` (result=79), but the long-msg upload service does
|
||||
* NOT — it stores the gzipped protobuf verbatim, so the receiver
|
||||
* can walk it back through the regular decoder. Mirrors NapCat's
|
||||
* `PacketMsgFileElement.buildElement` + `buildContent` split (see
|
||||
* `dev/napcatQQ/.../packet/message/element.ts:530-610`).
|
||||
*/
|
||||
forwardFake?: boolean;
|
||||
}
|
||||
|
||||
function makeTextElem(text: string): ProtoElem {
|
||||
return {
|
||||
text: { str: text } as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFaceElem(faceId: number): ProtoElem {
|
||||
return {
|
||||
face: { index: faceId } as any,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
|
||||
if (!ctx || !targetUin) return '';
|
||||
if (ctx.groupId !== undefined) {
|
||||
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin);
|
||||
return member?.card?.trim() || member?.nickname?.trim() || '';
|
||||
}
|
||||
const friend = ctx.bridge.identity.findFriend(targetUin);
|
||||
return friend?.remark?.trim() || friend?.nickname?.trim() || '';
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem {
|
||||
const mentionAll = element.uid === 'all' || element.targetUin === 0;
|
||||
const targetUin = element.targetUin ?? 0;
|
||||
|
||||
const extra = protobuf_encode<MentionExtraSend>({
|
||||
type: mentionAll ? 1 : 2,
|
||||
uin: mentionAll ? 0 : targetUin,
|
||||
field5: 0,
|
||||
uid: mentionAll ? 'all' : (element.uid ?? ''),
|
||||
});
|
||||
|
||||
// Prefer an explicit display string from the caller; otherwise look the
|
||||
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
|
||||
// Falls back to the bare uin when the roster doesn't know them yet.
|
||||
let str = element.text;
|
||||
if (!str) {
|
||||
if (mentionAll) {
|
||||
str = '@全体成员 ';
|
||||
} else {
|
||||
const name = resolveMentionDisplay(ctx, targetUin);
|
||||
str = name ? `@${name} ` : `@${targetUin} `;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: {
|
||||
str,
|
||||
pbReserve: extra,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
const seq = element.replySeq! & 0xFFFFFFFF;
|
||||
|
||||
const srcMsg: any = {
|
||||
origSeqs: [seq],
|
||||
};
|
||||
|
||||
// Add additional fields if available for better reply display
|
||||
if (element.replySenderUin) {
|
||||
srcMsg.senderUin = BigInt(element.replySenderUin);
|
||||
}
|
||||
if (element.replyTime) {
|
||||
srcMsg.time = element.replyTime;
|
||||
}
|
||||
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 1,
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeXmlElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||
const data = protobuf_encode<MarkdownData>({ content: element.text ?? '' });
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 45,
|
||||
pbElem: data,
|
||||
businessType: 1,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
const resId = (element.resId ?? '').trim();
|
||||
if (!resId) {
|
||||
throw new Error('forward resId is required');
|
||||
}
|
||||
|
||||
// Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML.
|
||||
// `source` becomes the bold header (e.g. "群聊的聊天记录"), `news`
|
||||
// entries become per-line previews ("nick: text"), `summary` is the
|
||||
// grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief.
|
||||
const source = element.forwardSource && element.forwardSource.length > 0
|
||||
? element.forwardSource
|
||||
: '聊天记录';
|
||||
const summary = element.forwardSummary && element.forwardSummary.length > 0
|
||||
? element.forwardSummary
|
||||
: '查看转发消息';
|
||||
const prompt = element.forwardPrompt && element.forwardPrompt.length > 0
|
||||
? element.forwardPrompt
|
||||
: '[聊天记录]';
|
||||
const news = Array.isArray(element.forwardNews) ? element.forwardNews : [];
|
||||
const tSum = element.forwardTSum && element.forwardTSum > 0
|
||||
? element.forwardTSum
|
||||
: Math.max(news.length, 1);
|
||||
|
||||
const newsTitles = news
|
||||
.map(n => `<title size="26" color="#777777">${escapeXml(n.text ?? '')}</title>`)
|
||||
.join('');
|
||||
|
||||
const resIdAttr = escapeXml(resId);
|
||||
const xml =
|
||||
`<?xml version="1.0" encoding="utf-8"?>` +
|
||||
`<msg templateID="1" action="viewMultiMsg" serviceID="35"` +
|
||||
` brief="${escapeXml(prompt)}"` +
|
||||
` m_resid="${resIdAttr}" m_fileName="${resIdAttr}" actionData="${resIdAttr}"` +
|
||||
` tSum="${tSum}" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0">` +
|
||||
`<item layout="1">` +
|
||||
`<title size="34" color="#000000">${escapeXml(source)}</title>` +
|
||||
newsTitles +
|
||||
`<hr hidden="false" style="0"/>` +
|
||||
`<summary size="26" color="#808080">${escapeXml(summary)}</summary>` +
|
||||
`</item>` +
|
||||
`<source name="${escapeXml(source)}" icon="" action="" appid="-1"/>` +
|
||||
`</msg>`;
|
||||
|
||||
const encodedXml = new TextEncoder().encode(xml);
|
||||
const payload = new Uint8Array(encodedXml.length + 1);
|
||||
payload[0] = 0x00;
|
||||
payload.set(encodedXml, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 35,
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private image target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 20 : 10,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makePttElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private record target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
// commonElem.businessType is the QQ NT scene tag the receive-side
|
||||
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
|
||||
// c2c message bounces with PbSendMsg result=79.
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 22 : 12,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive-side group file element shape — `transElem(elemType=24,
|
||||
* elemValue: 0x01 | BE16(len) | GroupFileExtra)`.
|
||||
*
|
||||
* NOT used for outgoing PbSendMsg (the QQ-NT server rejects that with
|
||||
* result=79); the group-file send-side flow goes through dedicated
|
||||
* OIDB 0x6d9_4 via `bridge.apis.groupFile.publish`. This shape IS used
|
||||
* inside the long-msg upload (forward / multi-msg) — the long-msg
|
||||
* service stores the gzipped protobuf verbatim, and the receiver
|
||||
* decodes file entities from `transElem(24)` (see
|
||||
* `msg-push/rich-body-decoder.ts:169-187`).
|
||||
*
|
||||
* `ctx` is consulted to fill in size/name/md5/sha1 from the upload
|
||||
* metadata cache when the caller only threaded the file_id through.
|
||||
* Mirrors the c2c forward path in `apis/forward.ts::buildForwardPushBody`
|
||||
* which already does this lookup — without it the receiver sees a
|
||||
* "0 B" file with no name (OneBot11 `{type:'file', file_id}` segments
|
||||
* typically omit the metadata since the upload action returned only
|
||||
* the id).
|
||||
*/
|
||||
function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoElem {
|
||||
if (!element.fileId) throw new Error('file element missing fileId');
|
||||
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
|
||||
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
|
||||
const fileName = element.fileName ?? cached?.fileName ?? '';
|
||||
const md5 = element.md5Hex
|
||||
? hexToBytes(element.md5Hex)
|
||||
: (cached?.fileMd5 ?? new Uint8Array(0));
|
||||
const sha1 = element.sha1Hex
|
||||
? hexToBytes(element.sha1Hex)
|
||||
: (cached?.fileSha1 ?? new Uint8Array(0));
|
||||
|
||||
// Outer field1 is hardcoded to 6 in NapCat's encoder
|
||||
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
|
||||
// busId=102 + the file_id + name + size + sha1/md5 hashes.
|
||||
const extraBytes = protobuf_encode<GroupFileExtra>({
|
||||
field1: 6,
|
||||
fileName,
|
||||
inner: {
|
||||
info: {
|
||||
busId: 102,
|
||||
fileId: element.fileId,
|
||||
fileSize: BigInt(fileSize),
|
||||
fileName,
|
||||
fileSha: sha1,
|
||||
extInfoString: '',
|
||||
fileMd5: md5,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (extraBytes.length > 0xFFFF) {
|
||||
// The 16-bit length prefix caps the payload at 64 KiB; even the
|
||||
// densest GroupFileExtra (fileId/name/two hashes) is well under.
|
||||
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
|
||||
}
|
||||
const elemValue = new Uint8Array(3 + extraBytes.length);
|
||||
elemValue[0] = 0x01;
|
||||
elemValue[1] = (extraBytes.length >> 8) & 0xff;
|
||||
elemValue[2] = extraBytes.length & 0xff;
|
||||
elemValue.set(extraBytes, 3);
|
||||
|
||||
return {
|
||||
transElem: {
|
||||
elemType: 24,
|
||||
elemValue,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private video target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
// commonElem.businessType is the QQ NT scene tag the receive-side
|
||||
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
|
||||
// c2c message bounces with PbSendMsg result=79.
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 21 : 11,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build proto Elem objects from an array of MessageElements.
|
||||
* Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward.
|
||||
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
|
||||
*/
|
||||
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
|
||||
const result: ProtoElem[] = [];
|
||||
|
||||
for (const elem of elements) {
|
||||
switch (elem.type) {
|
||||
case 'text':
|
||||
if (elem.text) result.push(makeTextElem(elem.text));
|
||||
break;
|
||||
|
||||
case 'face':
|
||||
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
|
||||
break;
|
||||
|
||||
case 'at':
|
||||
result.push(makeMentionElem(elem, ctx));
|
||||
break;
|
||||
|
||||
case 'reply':
|
||||
if (elem.replySeq) result.push(makeReplyElem(elem));
|
||||
break;
|
||||
|
||||
case 'json':
|
||||
if (elem.text) result.push(makeJsonElem(elem));
|
||||
break;
|
||||
|
||||
case 'xml':
|
||||
if (elem.text) result.push(makeXmlElem(elem));
|
||||
break;
|
||||
|
||||
case 'markdown':
|
||||
if (elem.text) result.push(makeMarkdownElem(elem));
|
||||
break;
|
||||
|
||||
case 'image':
|
||||
if (ctx) {
|
||||
result.push(await makeImageElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] image send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'forward':
|
||||
if (elem.resId) result.push(makeForwardElem(elem));
|
||||
break;
|
||||
|
||||
case 'record':
|
||||
if (ctx) {
|
||||
result.push(await makePttElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] record send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'video':
|
||||
if (ctx) {
|
||||
result.push(await makeVideoElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] video send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'file':
|
||||
// Files split into two routes depending on whether this is a
|
||||
// live send or a forward-message fake-send:
|
||||
//
|
||||
// 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on
|
||||
// elems[]. The OneBot layer splits file segments off before
|
||||
// calling buildSendElems:
|
||||
// * c2c (private): split → `bridge.sendC2cFileMessage`
|
||||
// (routingHead.trans0x211 + msgContent FileExtra).
|
||||
// * group: split → `bridge.sendGroupFileMessage`
|
||||
// (OIDB 0x6d9_4 publish).
|
||||
// The QQ-NT server REJECTS outgoing PbSendMsg with a
|
||||
// transElem(24) (result=79), so an element reaching here
|
||||
// in live-send mode is a routing bug — drop with a warn.
|
||||
//
|
||||
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
|
||||
// The long-msg service stores the gzipped protobuf verbatim
|
||||
// and the receiver decodes file entities from transElem(24)
|
||||
// + msgContent FileExtra. Mirror NapCat's split (see
|
||||
// `dev/napcatQQ/.../packet/message/element.ts:530-610`):
|
||||
// * group → emit transElem(24) via makeGroupFileElem
|
||||
// * c2c → emit NOTHING here; the forward-builder pulls
|
||||
// the file segment off and writes msgContent
|
||||
// separately (because RichText.notOnlineFile +
|
||||
// FileExtra both live outside elems[]).
|
||||
if (ctx && ctx.forwardFake) {
|
||||
if (ctx.groupId !== undefined) {
|
||||
result.push(makeGroupFileElem(elem, ctx));
|
||||
}
|
||||
// c2c forwardFake intentionally falls through — handled by
|
||||
// the forward-builder at the msgContent level.
|
||||
} else {
|
||||
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from './events';
|
||||
|
||||
type EventKind = QQEventVariant['kind'];
|
||||
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
|
||||
|
||||
export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Promise<void>;
|
||||
export type AnyEventHandler = (event: QQEventVariant) => void | Promise<void>;
|
||||
|
||||
export interface EventBusOptions {
|
||||
/** Logger label for handler failures. Defaults to `Bridge.Events`. */
|
||||
loggerName?: string;
|
||||
/** Override the default error reporter (e.g. for tests). */
|
||||
onError?: (kind: EventKind | '*', err: unknown) => void;
|
||||
}
|
||||
|
||||
const DEFAULT_LOGGER = createLogger('Bridge.Events');
|
||||
|
||||
export class BridgeEventBus {
|
||||
// Per-kind subscribers are stored as `Set<unknown>` so the container
|
||||
// doesn't carry a contravariant function type that fights TS variance
|
||||
// rules. The runtime invariant is straightforward: handlers stored under
|
||||
// key `K` only ever see `EventOf<K>` events, which is what the single
|
||||
// narrowing cast at the dispatch site below relies on.
|
||||
private readonly handlers = new Map<EventKind, Set<unknown>>();
|
||||
private readonly anyHandlers = new Set<AnyEventHandler>();
|
||||
private readonly onError: (kind: EventKind | '*', err: unknown) => void;
|
||||
|
||||
constructor(opts: EventBusOptions = {}) {
|
||||
if (opts.onError) {
|
||||
this.onError = opts.onError;
|
||||
} else {
|
||||
const log = opts.loggerName ? createLogger(opts.loggerName) : DEFAULT_LOGGER;
|
||||
this.onError = (kind, err) => {
|
||||
log.error(
|
||||
'event handler error [%s]: %s',
|
||||
kind,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to one kind. Returns an unsubscribe function. */
|
||||
on<K extends EventKind>(kind: K, handler: EventHandler<K>): () => void {
|
||||
let set = this.handlers.get(kind);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.handlers.set(kind, set);
|
||||
}
|
||||
set.add(handler);
|
||||
return () => {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
/** Subscribe to every kind (low-volume callers like loggers). */
|
||||
onAny(handler: AnyEventHandler): () => void {
|
||||
this.anyHandlers.add(handler);
|
||||
return () => {
|
||||
this.anyHandlers.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
}
|
||||
|
||||
has(kind: EventKind): boolean {
|
||||
return (this.handlers.get(kind)?.size ?? 0) + this.anyHandlers.size > 0;
|
||||
}
|
||||
|
||||
/** Drop every subscriber. Mostly useful for tests. */
|
||||
clear(): void {
|
||||
this.handlers.clear();
|
||||
this.anyHandlers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch an event in parallel to every subscriber for its kind plus every
|
||||
* onAny handler. Rejections are isolated per-handler — one bad subscriber
|
||||
* never blocks the others, and the returned promise resolves once every
|
||||
* subscriber settles.
|
||||
*/
|
||||
async emit<K extends EventKind>(event: EventOf<K>): Promise<void> {
|
||||
const kindHandlers = this.handlers.get(event.kind);
|
||||
if ((!kindHandlers || kindHandlers.size === 0) && this.anyHandlers.size === 0) {
|
||||
return;
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (kindHandlers) {
|
||||
for (const handler of kindHandlers) {
|
||||
// Single narrowing cast — the only place we re-assert that handlers
|
||||
// stored under `event.kind` accept `EventOf<event.kind>` events.
|
||||
const typed = handler as EventHandler<K>;
|
||||
tasks.push(invoke(this.onError, event.kind, () => typed(event)));
|
||||
}
|
||||
}
|
||||
for (const handler of this.anyHandlers) {
|
||||
tasks.push(invoke(this.onError, '*', () => handler(event)));
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
async function invoke(
|
||||
onError: (kind: EventKind | '*', err: unknown) => void,
|
||||
kind: EventKind | '*',
|
||||
fn: () => unknown,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const ret = fn();
|
||||
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
|
||||
await ret;
|
||||
}
|
||||
} catch (err) {
|
||||
onError(kind, err);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
// Bridge event types and MessageElement.
|
||||
// Port of src/bridge/include/bridge/events.h
|
||||
|
||||
export interface MessageElement {
|
||||
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
|
||||
text?: string;
|
||||
@@ -18,6 +15,7 @@ export interface MessageElement {
|
||||
replyTime?: number; // For reply: original message timestamp
|
||||
replyRandom?: number; // For reply: original message random/msgId
|
||||
url?: string;
|
||||
thumbUrl?: string;
|
||||
subType?: number;
|
||||
duration?: number;
|
||||
width?: number;
|
||||
@@ -26,6 +24,25 @@ export interface MessageElement {
|
||||
flash?: boolean;
|
||||
resId?: string;
|
||||
fileHash?: string;
|
||||
// Preview-bubble metadata for the `forward` element. Drives the XML
|
||||
// template (brief/title/news/summary/tSum) the recipient renders before
|
||||
// they tap to expand. When unset, the element builder falls back to
|
||||
// generic defaults so old call sites keep working.
|
||||
forwardSource?: string;
|
||||
forwardSummary?: string;
|
||||
forwardPrompt?: string;
|
||||
forwardNews?: Array<{ text: string }>;
|
||||
forwardTSum?: number;
|
||||
// Server-side fingerprints carried from receive side so a forward can do a
|
||||
// pure md5/sha1 fast-upload without re-downloading the original bytes.
|
||||
// Set together with `noByteFallback: true` to make the upload modules throw
|
||||
// instead of falling back to fetch(url).
|
||||
md5Hex?: string;
|
||||
sha1Hex?: string;
|
||||
picFormat?: number;
|
||||
videoFormat?: number;
|
||||
voiceFormat?: number;
|
||||
noByteFallback?: boolean;
|
||||
mediaNode?: {
|
||||
fileUuid?: string;
|
||||
storeId?: number;
|
||||
@@ -55,6 +72,26 @@ export interface ForwardNodePayload {
|
||||
userUin: number;
|
||||
nickname: string;
|
||||
elements: MessageElement[];
|
||||
// Optional context preserved when known (download path or upload-via-id),
|
||||
// so `get_forward_msg` can emit OneBot11-compatible OB11Message objects.
|
||||
time?: number;
|
||||
msgId?: number;
|
||||
msgSeq?: number;
|
||||
groupId?: number;
|
||||
senderCard?: string;
|
||||
messageType?: 'group' | 'private';
|
||||
// When set, this node's `content` is a nested forward chain. The
|
||||
// upload pipeline (see `actions/forward.ts::uploadForwardNodes`)
|
||||
// recursively uploads the inner chain and replaces this node's
|
||||
// `elements` with an ARK preview element pointing at the inner
|
||||
// res_id. We also piggyback the inner chain's msgBody onto the
|
||||
// outer long-msg upload as an extra `actionCommand` slot so the
|
||||
// NapCat-compatible receiver can walk the whole tree from one
|
||||
// server fetch without resolving each layer's res_id separately
|
||||
// (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`).
|
||||
// Caller never sets this on top-level OneBot input — `parseForward
|
||||
// Nodes` synthesises it when it detects a nested-node array.
|
||||
innerForward?: ForwardNodePayload[];
|
||||
}
|
||||
|
||||
export interface QQEvent {
|
||||
@@ -97,6 +134,8 @@ export interface GroupMemberJoin extends QQEvent {
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
}
|
||||
|
||||
export interface GroupMemberLeave extends QQEvent {
|
||||
@@ -104,6 +143,8 @@ export interface GroupMemberLeave extends QQEvent {
|
||||
groupId: number;
|
||||
userUin: number;
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
isKick: boolean;
|
||||
}
|
||||
|
||||
@@ -139,6 +180,7 @@ export interface GroupRecallEvent extends QQEvent {
|
||||
export interface FriendRequestEvent extends QQEvent {
|
||||
kind: 'friend_request';
|
||||
fromUin: number;
|
||||
fromUid?: string;
|
||||
message: string;
|
||||
flag: string;
|
||||
}
|
||||
@@ -147,6 +189,7 @@ export interface GroupInviteEvent extends QQEvent {
|
||||
kind: 'group_invite';
|
||||
groupId: number;
|
||||
fromUin: number;
|
||||
fromUid?: string;
|
||||
subType: string;
|
||||
message: string;
|
||||
flag: string;
|
||||
@@ -196,6 +239,22 @@ export interface FriendAddEvent extends QQEvent {
|
||||
userUin: number;
|
||||
}
|
||||
|
||||
export interface GroupMsgEmojiLikeEvent extends QQEvent {
|
||||
kind: 'group_msg_emoji_like';
|
||||
groupId: number;
|
||||
operatorUin: number;
|
||||
operatorUid: string;
|
||||
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
|
||||
msgSeq: number;
|
||||
/** Emoji ID. QQ system faces are short numeric strings; market faces
|
||||
* are alphanumeric. We keep the wire string verbatim. */
|
||||
emojiId: string;
|
||||
/** Multiplicity of the reaction event. Usually 1. */
|
||||
count: number;
|
||||
/** True when the reaction is being added; false when removed. */
|
||||
isAdd: boolean;
|
||||
}
|
||||
|
||||
export type QQEventVariant =
|
||||
| FriendMessage
|
||||
| GroupMessage
|
||||
@@ -212,4 +271,5 @@ export type QQEventVariant =
|
||||
| GroupPokeEvent
|
||||
| GroupEssenceEvent
|
||||
| GroupFileUploadEvent
|
||||
| FriendAddEvent;
|
||||
| FriendAddEvent
|
||||
| GroupMsgEmojiLikeEvent;
|
||||
@@ -0,0 +1,209 @@
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
|
||||
/**
|
||||
* Minimal shape of the OneBot-side `MessageStore` that `formatReply`
|
||||
* needs — just `findEvent(id)`. Defined inline (instead of importing
|
||||
* the full `MessageStore` class from @snowluma/onebot) so this
|
||||
* package doesn't depend on the OneBot layer above it. The OneBot
|
||||
* `MessageStore` is structurally a superset of this interface, so
|
||||
* callers pass it through with zero adaptation.
|
||||
*/
|
||||
export interface ReplyEventLookup {
|
||||
findEvent(messageId: number): JsonObject | null;
|
||||
}
|
||||
|
||||
const MAX_TEXT_PREVIEW = 50;
|
||||
const MAX_REPLY_BODY_PREVIEW = 30;
|
||||
|
||||
/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */
|
||||
export function formatGroup(identity: IdentityService, groupId: number): string {
|
||||
if (!groupId || groupId <= 0) return String(groupId || 0);
|
||||
try {
|
||||
const g = identity.findGroup(groupId);
|
||||
const name = g?.groupName?.trim();
|
||||
return name ? `[${name}(${groupId})]` : String(groupId);
|
||||
} catch {
|
||||
return String(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "[card-or-nick(uin)]" when the uin is in the group-member or friend
|
||||
* roster; falls back to the bare uin string. When only a uid is known
|
||||
* (no uin yet) the uid is returned as-is so the line still references
|
||||
* someone — better than logging "0".
|
||||
*/
|
||||
export function formatUser(
|
||||
identity: IdentityService,
|
||||
groupId: number | undefined,
|
||||
uin: number,
|
||||
uid?: string,
|
||||
): string {
|
||||
try {
|
||||
if (!uin || uin <= 0) return uid ? uid : '0';
|
||||
if (groupId !== undefined && groupId > 0) {
|
||||
const member = identity.findGroupMember(groupId, uin);
|
||||
const name = member?.card?.trim() || member?.nickname?.trim();
|
||||
if (name) return `[${name}(${uin})]`;
|
||||
}
|
||||
const friend = identity.findFriend(uin);
|
||||
const fname = friend?.remark?.trim() || friend?.nickname?.trim();
|
||||
if (fname) return `[${fname}(${uin})]`;
|
||||
return String(uin);
|
||||
} catch {
|
||||
return String(uin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line preview of an OneBot-shape message (array of segments or
|
||||
* raw string). Element rendering matches the existing logReceivedMessage
|
||||
* vocabulary so this is a drop-in replacement, with a few additions
|
||||
* (json / xml / markdown / forward / poke / file).
|
||||
*/
|
||||
export function formatMessageSegments(message: JsonValue): string {
|
||||
try {
|
||||
if (typeof message === 'string') {
|
||||
return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]';
|
||||
}
|
||||
if (!Array.isArray(message)) return '[空消息]';
|
||||
const parts: string[] = [];
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const obj = seg as JsonObject;
|
||||
const type = String(obj.type ?? '');
|
||||
const data = (typeof obj.data === 'object' && obj.data !== null && !Array.isArray(obj.data))
|
||||
? obj.data as Record<string, unknown>
|
||||
: {};
|
||||
parts.push(renderSegment(type, data));
|
||||
}
|
||||
return parts.join(' ').trim() || '[空消息]';
|
||||
} catch {
|
||||
return '[消息渲染异常]';
|
||||
}
|
||||
}
|
||||
|
||||
function renderSegment(type: string, data: Record<string, unknown>): string {
|
||||
switch (type) {
|
||||
case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW);
|
||||
case 'image': return '[图片]';
|
||||
case 'face': return '[表情]';
|
||||
case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]';
|
||||
case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`;
|
||||
case 'reply': return `[回复:${data.id ?? ''}]`;
|
||||
case 'record': return '[语音]';
|
||||
case 'video': return '[视频]';
|
||||
case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]';
|
||||
case 'json': return '[JSON]';
|
||||
case 'xml': return '[XML]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
case 'forward': return '[聊天记录]';
|
||||
case 'poke': return '[戳一戳]';
|
||||
default: return `[${type}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(s: string, max: number): string {
|
||||
return s.length > max ? `${s.slice(0, max)}...` : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a `reply` segment's referenced message and return a short
|
||||
* "[回复 user: body...]" string. On miss (older than store retention,
|
||||
* never seen, lookup throws) falls back to "[回复:<id>]" so the chain
|
||||
* reference is at least preserved.
|
||||
*
|
||||
* Deliberately one level deep — we don't recurse into the reply's own
|
||||
* reply. Long chains aren't worth the runtime cost in the hot path,
|
||||
* and a 1-level peek catches 90% of real-world "what's this referring
|
||||
* to" questions.
|
||||
*/
|
||||
export function formatReply(
|
||||
messageStore: ReplyEventLookup,
|
||||
identity: IdentityService,
|
||||
replyId: number,
|
||||
): string {
|
||||
try {
|
||||
if (!replyId) return '[回复:0]';
|
||||
const event = messageStore.findEvent(replyId);
|
||||
if (!event) return `[回复:${replyId}]`;
|
||||
const isGroup = event.message_type === 'group';
|
||||
const uin = toIntOrZero(event.user_id);
|
||||
const groupId = isGroup ? toIntOrZero(event.group_id) : undefined;
|
||||
|
||||
// Prefer cache; if cache miss, use the sender fields baked into the
|
||||
// stored event itself (those came from the original receive path
|
||||
// when the roster was warm).
|
||||
let userPart = formatUser(identity, groupId, uin);
|
||||
if (userPart === String(uin) && uin > 0) {
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const fallback = ((sender.card as string) || (sender.nickname as string) || '').trim();
|
||||
if (fallback) userPart = `[${fallback}(${uin})]`;
|
||||
}
|
||||
|
||||
const body = truncate(formatMessageSegments(event.message as JsonValue), MAX_REPLY_BODY_PREVIEW);
|
||||
return `[回复 ${userPart}: ${body}]`;
|
||||
} catch {
|
||||
return `[回复:${replyId}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function toIntOrZero(v: unknown): number {
|
||||
if (typeof v === 'number' && Number.isFinite(v)) return v;
|
||||
if (typeof v === 'string') {
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Readable one-line rendering of a notice-class QQEventVariant. Returns
|
||||
* null for kinds the OneBot layer's message log already renders
|
||||
* (group_message / friend_message / temp_message / group_file_upload /
|
||||
* friend_add — those have richer dedicated paths).
|
||||
*/
|
||||
export function formatEvent(identity: IdentityService, event: QQEventVariant): string | null {
|
||||
try {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
case 'group_file_upload':
|
||||
case 'friend_add':
|
||||
return null;
|
||||
case 'group_recall':
|
||||
return `群撤回 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.authorUin)} 被 ${formatUser(identity, event.groupId, event.operatorUin)} 撤回`;
|
||||
case 'friend_recall':
|
||||
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
|
||||
case 'group_member_join':
|
||||
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_member_leave':
|
||||
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_mute':
|
||||
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
|
||||
case 'group_admin':
|
||||
return `管理 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.set ? '+' : '-'}管理员`;
|
||||
case 'friend_poke':
|
||||
return `戳一戳 ${formatUser(identity, undefined, event.userUin)} -> ${formatUser(identity, undefined, event.targetUin)}`;
|
||||
case 'group_poke':
|
||||
return `群戳 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} -> ${formatUser(identity, event.groupId, event.targetUin)}`;
|
||||
case 'friend_request':
|
||||
return `好友请求 ${formatUser(identity, undefined, event.fromUin)}: ${event.message}`;
|
||||
case 'group_invite':
|
||||
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_essence':
|
||||
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
|
||||
case 'group_msg_emoji_like':
|
||||
return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface FFmpegVideoInfo {
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
format: string;
|
||||
videoCodec: string;
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
interface FFmpegNativeAddon {
|
||||
convertFile(inputFile: string, outputFile: string, format: string): Promise<{ success: boolean }>;
|
||||
getVideoInfo(filePath: string, format?: 'bmp' | 'bmp24'): Promise<FFmpegVideoInfo>;
|
||||
getDuration(filePath: string): Promise<number>;
|
||||
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
|
||||
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
|
||||
decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>;
|
||||
}
|
||||
|
||||
let cachedAddon: FFmpegNativeAddon | null = null;
|
||||
let cachedLoadError: string | null = null;
|
||||
|
||||
function addonFileName(): string {
|
||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||
}
|
||||
|
||||
function addonSearchDirs(): string[] {
|
||||
// Mirrors the hook injector's resolution strategy so the addon is found
|
||||
// regardless of whether we're running from:
|
||||
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
|
||||
// the dist root.
|
||||
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
|
||||
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
|
||||
// __dirname is `packages/core/src/bridge/highway` — four levels deep
|
||||
// under `packages/`. Note: the hook injector lives at
|
||||
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
|
||||
return [
|
||||
path.resolve(__dirname, 'native', 'ffmpeg'),
|
||||
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveAddonPath(): string | null {
|
||||
const fileName = addonFileName();
|
||||
for (const dir of addonSearchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
if (fs.existsSync(full)) return full;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the ffmpegAddon once and return a cached instance.
|
||||
* Throws on first-use failure; subsequent calls replay the same error message
|
||||
* so callers don't silently fall back.
|
||||
*/
|
||||
export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
if (cachedAddon) return cachedAddon;
|
||||
if (cachedLoadError) throw new Error(cachedLoadError);
|
||||
|
||||
const addonPath = resolveAddonPath();
|
||||
if (!addonPath) {
|
||||
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
|
||||
return cachedAddon;
|
||||
} catch (error) {
|
||||
cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether `filePath` is already an NT SILK container. The addon can
|
||||
* read any input directly so the only reason we peek at the header is to
|
||||
* skip the conversion (and the temp file) when the caller already fed us
|
||||
* a ready-to-upload silk file.
|
||||
*/
|
||||
export function isSilkFile(filePath: string): boolean {
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(10);
|
||||
fs.readSync(fd, buf, 0, 10, 0);
|
||||
const header = buf.toString();
|
||||
return header.includes('#!SILK') || header.includes('\x02#!SILK');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface EncodeSilkResult {
|
||||
/** Absolute path to the silk file ready for highway upload. */
|
||||
path: string;
|
||||
/** Voice duration in whole seconds (>= 1). */
|
||||
duration: number;
|
||||
/** `true` if we wrote a new silk file and the caller should unlink it. */
|
||||
converted: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert `inputFile` to NT SILK when necessary and return the output path
|
||||
* + duration. The caller is responsible for unlinking the returned path
|
||||
* when `converted === true`.
|
||||
*/
|
||||
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
|
||||
const addon = getFFmpegAddon();
|
||||
|
||||
// Already silk — trust the file, just measure duration via the addon.
|
||||
if (isSilkFile(inputFile)) {
|
||||
let duration = 1;
|
||||
try {
|
||||
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
} catch {
|
||||
// getDuration on a silk file occasionally fails on certain encodings;
|
||||
// the upload path only needs a rough, non-zero value, so fall back
|
||||
// to the size-based heuristic used by NapCat's audio.ts.
|
||||
const stat = fs.statSync(inputFile);
|
||||
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
|
||||
}
|
||||
return { path: inputFile, duration, converted: false };
|
||||
}
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
const outPath = path.join(tempDir, crypto.randomUUID());
|
||||
await addon.convertToNTSilkTct(inputFile, outPath);
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('convertToNTSilkTct produced no output file');
|
||||
}
|
||||
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
return { path: outPath, duration, converted: true };
|
||||
}
|
||||
|
||||
/** Default location for temporary silk files. */
|
||||
export function defaultPttTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-ptt');
|
||||
}
|
||||
+75
-41
@@ -1,18 +1,14 @@
|
||||
// Highway HTTP client: session fetch and chunked binary upload.
|
||||
// Port of src/bridge/src/highway_client.cpp
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import net from 'net';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { protoEncode, protoDecode } from '../../protobuf/decode';
|
||||
import {
|
||||
HttpConn0x6FF501RequestSchema,
|
||||
HttpConn0x6FF501ResponseSchema,
|
||||
ReqDataHighwayHeadSchema,
|
||||
RespDataHighwayHeadSchema,
|
||||
NTV2RichMediaHighwayExtSchema,
|
||||
HighwayMsgInfoBodySchema,
|
||||
} from '../proto/highway';
|
||||
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type {
|
||||
HttpConn0x6FF501Request,
|
||||
HttpConn0x6FF501Response,
|
||||
NTV2RichMediaHighwayExt,
|
||||
ReqDataHighwayHead,
|
||||
RespDataHighwayHead,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
|
||||
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
@@ -31,21 +27,21 @@ function ipv4ToString(value: number): string {
|
||||
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
|
||||
}
|
||||
|
||||
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
|
||||
const request = protoEncode({
|
||||
export async function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
|
||||
const request = protobuf_encode<HttpConn0x6FF501Request>({
|
||||
httpConn: {
|
||||
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||
serviceTypes: [1, 5, 10, 21],
|
||||
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||
},
|
||||
}, HttpConn0x6FF501RequestSchema);
|
||||
});
|
||||
|
||||
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||
}
|
||||
|
||||
const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema);
|
||||
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
|
||||
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||
throw new Error('HttpConn response missing sig_session');
|
||||
@@ -78,7 +74,7 @@ function makeHighwayHead(
|
||||
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||
): Uint8Array {
|
||||
return protoEncode({
|
||||
return protobuf_encode<ReqDataHighwayHead>({
|
||||
msgBaseHead: {
|
||||
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
|
||||
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
|
||||
@@ -90,16 +86,20 @@ function makeHighwayHead(
|
||||
bytesReqExtendInfo: extend,
|
||||
timestamp: 0n,
|
||||
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
|
||||
}, ReqDataHighwayHeadSchema);
|
||||
});
|
||||
}
|
||||
|
||||
export function buildHighwayExtend(
|
||||
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
|
||||
uKey: string,
|
||||
msgInfo: any,
|
||||
ipv4s: any[],
|
||||
sha1: Uint8Array | Uint8Array[],
|
||||
fileIndex = 0,
|
||||
): Uint8Array {
|
||||
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
|
||||
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
|
||||
|
||||
const first = msgInfoBody[0];
|
||||
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
|
||||
const networkIpv4s: any[] = [];
|
||||
for (const ipv4 of ipv4s ?? []) {
|
||||
const ip = ipv4.outIp ?? 0;
|
||||
@@ -109,26 +109,47 @@ export function buildHighwayExtend(
|
||||
}
|
||||
}
|
||||
|
||||
return protoEncode({
|
||||
fileUuid: first?.index?.fileUuid ?? '',
|
||||
return protobuf_encode<NTV2RichMediaHighwayExt>({
|
||||
fileUuid: selected?.index?.fileUuid ?? '',
|
||||
uKey,
|
||||
network: { ipv4s: networkIpv4s },
|
||||
msgInfoBody: msgInfoBody.map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
})),
|
||||
blockSize: HIGHWAY_BLOCK_SIZE,
|
||||
hash: { fileSha1: [sha1] },
|
||||
}, NTV2RichMediaHighwayExtSchema);
|
||||
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
|
||||
});
|
||||
}
|
||||
|
||||
// --- TCP-based HTTP highway upload ---
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection({ host, port }, () => resolve(socket));
|
||||
let settled = false;
|
||||
const onTimeout = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
reject(new Error('TCP connect timeout'));
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(err);
|
||||
};
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
// Drop the connect-only listeners so subsequent IO errors / idle
|
||||
// timeouts don't try to reject this already-resolved promise.
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
resolve(socket);
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
|
||||
socket.on('error', reject);
|
||||
socket.once('timeout', onTimeout);
|
||||
socket.once('error', onError);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,8 +165,21 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
|
||||
const checkComplete = () => {
|
||||
const detach = () => {
|
||||
socket.off('data', onData);
|
||||
socket.off('error', onError);
|
||||
socket.off('close', onClose);
|
||||
};
|
||||
const finish = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
detach();
|
||||
fn();
|
||||
};
|
||||
const onData = (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
@@ -158,19 +192,19 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
socket.removeAllListeners('data');
|
||||
socket.removeAllListeners('error');
|
||||
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
|
||||
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => {
|
||||
const onError = (err: Error) => finish(() => reject(err));
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
socket.on('error', onError);
|
||||
socket.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -184,10 +218,10 @@ async function httpPostFrame(
|
||||
}
|
||||
|
||||
export async function uploadHighwayHttp(
|
||||
bridge: Bridge, session: HighwaySession, commandId: number,
|
||||
bridge: BridgeContext, session: HighwaySession, commandId: number,
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
@@ -197,13 +231,13 @@ export async function uploadHighwayHttp(
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protoDecode(respHead, RespDataHighwayHeadSchema);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`highway upload error_code=${resp.errorCode}`);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
function loggerFor(bridge: BridgeContext) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
interface ImageData {
|
||||
/** Empty when the caller is forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
summary: string;
|
||||
subType: number;
|
||||
width: number;
|
||||
height: number;
|
||||
picFormat: number;
|
||||
/** True when `bytes` is empty; runNtv2Upload throws fastOnlyError if
|
||||
* the server demands the bytes anyway. */
|
||||
fastOnly: boolean;
|
||||
}
|
||||
|
||||
function imageDataFromFingerprint(element: MessageElement): ImageData {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
summary: element.summary || (element.subType === 0 ? '[image]' : '[sticker]'),
|
||||
subType: element.subType ?? 0,
|
||||
width: element.width ?? 0,
|
||||
height: element.height ?? 0,
|
||||
picFormat: element.picFormat ?? 1000,
|
||||
fastOnly: true,
|
||||
};
|
||||
}
|
||||
|
||||
function loadImage(element: MessageElement): Promise<ImageData> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
return Promise.reject(new Error('image fast-upload requires md5Hex + sha1Hex'));
|
||||
}
|
||||
return Promise.resolve(imageDataFromFingerprint(element));
|
||||
}
|
||||
return loadImageFromSource(
|
||||
element.url || element.fileId || '',
|
||||
element.fileName ?? '',
|
||||
element.subType ?? 0,
|
||||
element.summary ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
|
||||
const loaded = await loadBinarySource(source, 'image');
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fmt = detectImageFormat(loaded.bytes);
|
||||
|
||||
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
|
||||
const ext = extMap[fmt.format] ?? '.jpg';
|
||||
|
||||
let finalName = fileName || loaded.fileName;
|
||||
if (!finalName) finalName = hashes.md5Hex + ext;
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: finalName,
|
||||
fileSize: loaded.bytes.length,
|
||||
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
|
||||
subType,
|
||||
width: fmt.width,
|
||||
height: fmt.height,
|
||||
picFormat: fmt.format,
|
||||
fastOnly: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image and return the encoded MsgInfo bytes for the outgoing
|
||||
* commonElem.
|
||||
*/
|
||||
export async function uploadImageMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID,
|
||||
bytes: image.bytes,
|
||||
md5: image.md5,
|
||||
sha1: image.sha1,
|
||||
fastOnlyError: 'image fast-upload not available (server requires bytes)',
|
||||
}];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: image.fileSize,
|
||||
fileHash: image.md5Hex,
|
||||
fileSha1: image.sha1Hex,
|
||||
fileName: image.fileName,
|
||||
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
time: 0,
|
||||
original: 1,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
pic: {
|
||||
bizType: image.subType,
|
||||
textSummary: image.summary,
|
||||
...(isGroup
|
||||
? { reserveTroop: { subType: image.subType } }
|
||||
: { reserveC2c: { subType: image.subType } }),
|
||||
},
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'image',
|
||||
});
|
||||
|
||||
return finalizeMediaMsgInfo(upload, { bizType: image.subType, textSummary: image.summary });
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import crypto from 'crypto';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { makeOidbEnvelope } from '../bridge-oidb';
|
||||
import type {
|
||||
EncodableMediaMsgInfo,
|
||||
NTV2UploadRichMediaReq,
|
||||
NTV2UploadRichMediaResp,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
// ─────────────── public types ───────────────
|
||||
|
||||
/**
|
||||
* Highway upload spec for one sub-file of an NTV2 upload response.
|
||||
* The server returns 0..N sub-files; for each we either fast-path (skip)
|
||||
* or do an HTTP PUT.
|
||||
*/
|
||||
export interface MediaSubFileUpload {
|
||||
/**
|
||||
* Where to read uKey + ipv4s from on the OIDB response:
|
||||
* 'top' -> `upload.uKey` + `upload.ipv4s` (main file)
|
||||
* N (int) -> `upload.subFileInfos[N].uKey` + `.ipv4s` (sub-file)
|
||||
*
|
||||
* Image and PTT use 'top' only. Video uses 'top' (main) and 0 (thumb).
|
||||
*/
|
||||
source: 'top' | number;
|
||||
/** Highway command id for this sub-file. */
|
||||
cmdId: number;
|
||||
/** Bytes to upload. Empty when the caller is forwarding from cached
|
||||
* fingerprints; in that case set fastOnlyError so we throw with a
|
||||
* typed message when the server actually demands the bytes. */
|
||||
bytes: Uint8Array;
|
||||
/** md5 used for the highway request. */
|
||||
md5: Uint8Array;
|
||||
/** sha1 — single buffer or per-1MB block array. Passed verbatim to
|
||||
* buildHighwayExtend. */
|
||||
sha1: Uint8Array | Uint8Array[];
|
||||
/** subFileIndex argument for buildHighwayExtend. Defaults to 0;
|
||||
* video thumb passes 1. */
|
||||
subFileIndex?: number;
|
||||
/** Error message to throw when uKey is present but `bytes.length === 0`.
|
||||
* Omit if the caller guarantees bytes always exist (e.g. video thumb
|
||||
* always has FALLBACK_THUMB bytes). */
|
||||
fastOnlyError?: string;
|
||||
}
|
||||
|
||||
export interface NtV2UploadParams {
|
||||
bridge: BridgeContext;
|
||||
isGroup: boolean;
|
||||
/** Group uin when isGroup, otherwise the recipient's uid string. */
|
||||
targetIdOrUid: string | number;
|
||||
/** OIDB command id (e.g. 0x11C4 / 0x11C5 / 0x126E / 0x126D / 0x11EA / 0x11E9). */
|
||||
oidbCmd: number;
|
||||
/** Service cmd (e.g. 'OidbSvcTrpcTcp.0x11c4_100'). */
|
||||
serviceCmd: string;
|
||||
/** `reqHead.common.requestId`. NTV2 sub-protocols use different values
|
||||
* here (image=1, video=3, ptt = group:1 / c2c:4). */
|
||||
requestId: number;
|
||||
/** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */
|
||||
businessType: number;
|
||||
/** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */
|
||||
uploadInfo: unknown[];
|
||||
/** `upload.compatQmsgSceneType`. */
|
||||
compatQmsgSceneType: number;
|
||||
/** `upload.extBizInfo` — type-specific bytes/flags. */
|
||||
extBizInfo: unknown;
|
||||
/** Sub-file Highway PUTs to perform after the OIDB response. */
|
||||
uploads: MediaSubFileUpload[];
|
||||
/** Used in error messages. Defaults to 'media'. */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
// ─────────────── helpers ───────────────
|
||||
|
||||
/**
|
||||
* 8 random bytes masked into the positive int64 range so the resulting
|
||||
* BigInt survives signed-int64 protobuf encoding without surprises.
|
||||
* Mirrors NapCat.
|
||||
*/
|
||||
export function makeClientRandomId(): bigint {
|
||||
const buf = crypto.randomBytes(8);
|
||||
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
|
||||
}
|
||||
|
||||
/** Hex string -> Uint8Array. Used by every format's fingerprint path. */
|
||||
export function hexToBytes(hex: string): Uint8Array {
|
||||
const clean = hex.length % 2 === 0 ? hex : '0' + hex;
|
||||
const out = new Uint8Array(clean.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─────────────── main entrypoint ───────────────
|
||||
|
||||
/**
|
||||
* Send a NTV2UploadRichMediaReq and run any Highway PUTs the server asks
|
||||
* for. Returns the decoded `upload` object so the caller can pass it to
|
||||
* `finalizeMediaMsgInfo`.
|
||||
*
|
||||
* Sessions are cached across sub-file uploads — video does two PUTs but
|
||||
* only fetches the Highway session once.
|
||||
*/
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
// Build the full body once. Pulling this in here means each format file
|
||||
// only specifies the seven fields that actually vary.
|
||||
const body: any = {
|
||||
reqHead: {
|
||||
common: { requestId: params.requestId, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: params.businessType,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: params.uploadInfo,
|
||||
tryFastUploadCompleted: true,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
compatQmsgSceneType: params.compatQmsgSceneType,
|
||||
extBizInfo: params.extBizInfo,
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
|
||||
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
|
||||
|
||||
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || `${label} upload request failed`);
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
|
||||
if (!resp) throw new Error(`failed to decode ${label} upload response`);
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody: any = resp.body;
|
||||
if (!uploadBody) throw new Error(`${label} upload response body missing`);
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
|
||||
}
|
||||
const upload = uploadBody.upload;
|
||||
if (!upload) throw new Error(`${label} upload response body missing`);
|
||||
|
||||
// Highway PUTs. Session is lazily fetched and cached — video does two
|
||||
// PUTs (main + thumb) and shouldn't pay for two sessions.
|
||||
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
|
||||
const getSession = async () => {
|
||||
session ??= await fetchHighwaySession(bridge);
|
||||
return session;
|
||||
};
|
||||
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
// Either the server fast-pathed this sub-file (no uKey) or msgInfo is
|
||||
// missing entirely; either way nothing to push.
|
||||
if (!uKey || !upload.msgInfo) continue;
|
||||
|
||||
if (sub.bytes.length === 0) {
|
||||
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
|
||||
continue;
|
||||
}
|
||||
|
||||
const extend = buildHighwayExtend(
|
||||
uKey,
|
||||
upload.msgInfo,
|
||||
target.ipv4s ?? [],
|
||||
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
|
||||
return upload;
|
||||
}
|
||||
|
||||
// ─────────────── shared finalize ───────────────
|
||||
|
||||
/**
|
||||
* Build the encoded MsgInfo bytes that go inside the outgoing commonElem.
|
||||
*
|
||||
* `defaultPic` is the image-only fall-back: image uploads inject
|
||||
* `bizType` + `textSummary` defaults when the server response omits the
|
||||
* `pic` ext-biz-info. PTT and video pass `undefined` here — they leave
|
||||
* pic alone unless the server populates it.
|
||||
*/
|
||||
export function finalizeMediaMsgInfo(
|
||||
upload: any,
|
||||
defaultPic?: { bizType: number; textSummary: string },
|
||||
): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
}));
|
||||
|
||||
const extBizInfo: any = {};
|
||||
if (upload.msgInfo.extBizInfo?.pic) {
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
|
||||
if (defaultPic) {
|
||||
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? defaultPic.bizType;
|
||||
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? defaultPic.textSummary;
|
||||
}
|
||||
} else if (defaultPic) {
|
||||
extBizInfo.pic = { bizType: defaultPic.bizType, textSummary: defaultPic.textSummary };
|
||||
}
|
||||
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
|
||||
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
|
||||
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
|
||||
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
|
||||
}
|
||||
|
||||
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
|
||||
function loggerFor(bridge: BridgeContext) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
|
||||
interface PttPayload {
|
||||
/** Silk bytes uploaded to Highway. Empty when forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
/** Whole seconds, >= 1. */
|
||||
duration: number;
|
||||
voiceFormat: number;
|
||||
/** True when bytes is empty; pipeline throws fastOnlyError if the
|
||||
* server demands the bytes anyway. */
|
||||
fastOnly: boolean;
|
||||
/** Cleanup hooks for any temp silk files staged during loadPtt. */
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'record'}.amr`,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
duration: element.duration ?? 1,
|
||||
// Voice format: 1 = silk (NTV2 standard). Honour any fingerprint that
|
||||
// declares a different format; legacy NTQQ paths all use 1.
|
||||
voiceFormat: element.voiceFormat || 1,
|
||||
fastOnly: true,
|
||||
cleanups: [],
|
||||
};
|
||||
}
|
||||
|
||||
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('record fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
return pttPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('record source is empty');
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
// Run all queued cleanups; called both on the success path (via the
|
||||
// returned `cleanups` array) and on the failure path (try/catch below).
|
||||
const runCleanups = () => {
|
||||
while (cleanups.length > 0) {
|
||||
const fn = cleanups.pop();
|
||||
if (!fn) continue;
|
||||
try { fn(); } catch { /* best-effort */ }
|
||||
}
|
||||
};
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
// Resolve the on-disk path the addon should read. Anything that isn't
|
||||
// already a local file (base64, HTTP) gets staged into the temp dir.
|
||||
let inputPath: string;
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
inputPath = local;
|
||||
} else {
|
||||
const loaded = await loadBinarySource(source, 'record');
|
||||
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
|
||||
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
|
||||
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
|
||||
}
|
||||
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
||||
|
||||
const hashes = computeHashes(silkBytes);
|
||||
return {
|
||||
bytes: silkBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: `${hashes.md5Hex}.amr`,
|
||||
fileSize: silkBytes.length,
|
||||
duration: silk.duration,
|
||||
voiceFormat: 1,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
|
||||
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
||||
*/
|
||||
export async function uploadPttMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
|
||||
ptt.fileSize,
|
||||
ptt.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
ptt.duration);
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID,
|
||||
bytes: ptt.bytes,
|
||||
md5: ptt.md5,
|
||||
sha1: ptt.sha1,
|
||||
fastOnlyError: 'record fast-upload not available (server requires bytes)',
|
||||
}];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x126E : 0x126D,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100',
|
||||
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
|
||||
requestId: isGroup ? 1 : 4,
|
||||
businessType: 3,
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: ptt.fileSize,
|
||||
fileHash: ptt.md5Hex,
|
||||
fileSha1: ptt.sha1Hex,
|
||||
fileName: ptt.fileName,
|
||||
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: ptt.voiceFormat },
|
||||
width: 0,
|
||||
height: 0,
|
||||
time: ptt.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
// NapCat fills in a placeholder textSummary so the legacy compat
|
||||
// QMsg path still has something to render. Mirror it.
|
||||
pic: { textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
|
||||
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
|
||||
bytesGeneralFlags: isGroup
|
||||
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
|
||||
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'ptt',
|
||||
});
|
||||
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,27 @@
|
||||
// Highway utilities: binary source loading, hashing, image format detection, frame packing.
|
||||
// Port of src/bridge/src/highway_utils.h/.cpp
|
||||
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default cap on a single binary load issued through this helper. Callers
|
||||
* that route here (image / voice via base64+HTTP, group/private file
|
||||
* uploads, avatar) get bounded reads. Not all callers route through here
|
||||
* — in particular `video-upload.stageVideoSource` reads local-video files
|
||||
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
|
||||
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
|
||||
* file protocol legitimately supports up to 4 GiB.
|
||||
*/
|
||||
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
@@ -25,27 +37,102 @@ export interface ImageFormat {
|
||||
|
||||
// --- Binary source loading ---
|
||||
|
||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
export function resolveLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (/^base64:\/\//i.test(source)) return null;
|
||||
if (/^https?:\/\//i.test(source)) return null;
|
||||
|
||||
if (source.startsWith('base64://')) {
|
||||
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||
let filePath = source;
|
||||
if (/^file:\/\//i.test(source)) {
|
||||
try {
|
||||
filePath = fileURLToPath(source);
|
||||
} catch {
|
||||
filePath = source.replace(/^file:\/+/i, '/');
|
||||
try {
|
||||
filePath = decodeURIComponent(filePath);
|
||||
} catch {
|
||||
// Keep the original fallback path when percent decoding fails.
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform !== 'win32' && filePath.startsWith('//')) {
|
||||
filePath = filePath.replace(/^\/+/, '/');
|
||||
}
|
||||
}
|
||||
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) {
|
||||
const resp = await fetch(source);
|
||||
// Windows-style paths can arrive from file:///C:/... as /C:/...
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
const bytes = Buffer.from(source.slice(9), 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
// Stream the body incrementally so a server that omits or
|
||||
// understates Content-Length can't make us buffer a chunked response
|
||||
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
|
||||
// the entire payload before we get a chance to length-check it.
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
// File path (strip file:// prefix)
|
||||
let filePath = source;
|
||||
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||
// Windows: strip leading / before drive letter
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.size > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
@@ -103,7 +190,7 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
|
||||
// PNG
|
||||
if (bytes.length >= 24 &&
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
width = readBE32(bytes, 16);
|
||||
height = readBE32(bytes, 20);
|
||||
return { format: 1001, width, height };
|
||||
@@ -111,8 +198,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
|
||||
// GIF
|
||||
if (bytes.length >= 10 &&
|
||||
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
|
||||
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
|
||||
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
|
||||
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
|
||||
width = readLE16(bytes, 6);
|
||||
height = readLE16(bytes, 8);
|
||||
return { format: 2000, width, height };
|
||||
@@ -127,8 +214,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
|
||||
// WebP
|
||||
if (bytes.length >= 30 &&
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
|
||||
width = readLE16(bytes, 26);
|
||||
height = readLE16(bytes, 28);
|
||||
@@ -157,7 +244,12 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
if (offset + 4 > bytes.length) break;
|
||||
const segLen = readBE16(bytes, offset + 2);
|
||||
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
|
||||
// Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC
|
||||
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
|
||||
// and friends, then misread Huffman table bytes as image dimensions.
|
||||
const isSof = marker >= 0xC0 && marker <= 0xCF
|
||||
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
|
||||
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
@@ -0,0 +1,541 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { getFFmpegAddon } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import {
|
||||
computeHashes,
|
||||
detectImageFormat,
|
||||
loadBinarySource,
|
||||
resolveLocalFilePath,
|
||||
} from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Video');
|
||||
|
||||
function loggerFor(bridge: BridgeContext) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_VIDEO_CMD_ID = 1001;
|
||||
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
|
||||
export const GROUP_VIDEO_CMD_ID = 1005;
|
||||
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
|
||||
|
||||
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
|
||||
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
const FALLBACK_THUMB = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
|
||||
interface VideoPayload {
|
||||
/** Video bytes. Empty when forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
sha1Blocks: Uint8Array[];
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
videoFormat: number;
|
||||
thumb: ThumbPayload;
|
||||
/** When true, video bytes are empty; pipeline throws fastOnlyError
|
||||
* for the main file if the server demands the bytes. The thumb is
|
||||
* always present (FALLBACK_THUMB at worst) so its sub-file uploads
|
||||
* normally regardless. */
|
||||
fastOnly: boolean;
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
function makeFallbackThumb(): ThumbPayload {
|
||||
const bytes = new Uint8Array(FALLBACK_THUMB);
|
||||
const hashes = computeHashes(bytes);
|
||||
return {
|
||||
bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function videoPayloadFromFingerprint(element: MessageElement): VideoPayload {
|
||||
return {
|
||||
bytes: new Uint8Array(0),
|
||||
md5: hexToBytes(element.md5Hex ?? ''),
|
||||
sha1: hexToBytes(element.sha1Hex ?? ''),
|
||||
sha1Blocks: [],
|
||||
md5Hex: element.md5Hex ?? '',
|
||||
sha1Hex: element.sha1Hex ?? '',
|
||||
fileName: element.fileName || `${element.md5Hex ?? 'video'}.mp4`,
|
||||
filePath: '',
|
||||
fileSize: element.fileSize ?? 0,
|
||||
width: element.width ?? 0,
|
||||
height: element.height ?? 0,
|
||||
duration: element.duration ?? 1,
|
||||
videoFormat: element.videoFormat ?? 0,
|
||||
thumb: makeFallbackThumb(),
|
||||
fastOnly: true,
|
||||
cleanups: [],
|
||||
};
|
||||
}
|
||||
|
||||
interface ThumbPayload {
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
|
||||
|
||||
// Highway expects sha1 computed over each 1 MB block of the file, plus
|
||||
// the final overall sha1. This is a streaming implementation that doesn't
|
||||
// reuse Node's crypto because Node only exposes the final digest.
|
||||
|
||||
class Sha1StreamState {
|
||||
readonly blockSize = 64;
|
||||
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
|
||||
private readonly state = new Uint32Array(5);
|
||||
private readonly count = new Uint32Array(2);
|
||||
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
|
||||
private readonly w = new Uint32Array(80);
|
||||
|
||||
constructor() {
|
||||
this.reset();
|
||||
}
|
||||
|
||||
private reset(): void {
|
||||
this.state[0] = 0x67452301;
|
||||
this.state[1] = 0xEFCDAB89;
|
||||
this.state[2] = 0x98BADCFE;
|
||||
this.state[3] = 0x10325476;
|
||||
this.state[4] = 0xC3D2E1F0;
|
||||
this.count[0] = 0;
|
||||
this.count[1] = 0;
|
||||
this.buffer.fill(0);
|
||||
}
|
||||
|
||||
private rotateLeft(value: number, offset: number): number {
|
||||
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
|
||||
}
|
||||
|
||||
private transform(chunk: Uint8Array, offset: number): void {
|
||||
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
this.w[i] = view.getUint32(i * 4, false);
|
||||
}
|
||||
for (let i = 16; i < 80; i++) {
|
||||
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
|
||||
}
|
||||
|
||||
let a = this.state[0];
|
||||
let b = this.state[1];
|
||||
let c = this.state[2];
|
||||
let d = this.state[3];
|
||||
let e = this.state[4];
|
||||
|
||||
for (let i = 0; i < 80; i++) {
|
||||
let temp: number;
|
||||
if (i < 20) {
|
||||
temp = ((b & c) | (~b & d)) + 0x5A827999;
|
||||
} else if (i < 40) {
|
||||
temp = (b ^ c ^ d) + 0x6ED9EBA1;
|
||||
} else if (i < 60) {
|
||||
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
|
||||
} else {
|
||||
temp = (b ^ c ^ d) + 0xCA62C1D6;
|
||||
}
|
||||
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = this.rotateLeft(b, 30);
|
||||
b = a;
|
||||
a = temp >>> 0;
|
||||
}
|
||||
|
||||
this.state[0] = (this.state[0] + a) >>> 0;
|
||||
this.state[1] = (this.state[1] + b) >>> 0;
|
||||
this.state[2] = (this.state[2] + c) >>> 0;
|
||||
this.state[3] = (this.state[3] + d) >>> 0;
|
||||
this.state[4] = (this.state[4] + e) >>> 0;
|
||||
}
|
||||
|
||||
update(data: Uint8Array): void {
|
||||
let index = (this.count[0] >>> 3) & 0x3F;
|
||||
const dataLen = data.length;
|
||||
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
|
||||
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
|
||||
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
|
||||
|
||||
const partLen = this.blockSize - index;
|
||||
let i = 0;
|
||||
|
||||
if (dataLen >= partLen) {
|
||||
this.buffer.set(data.subarray(0, partLen), index);
|
||||
this.transform(this.buffer, 0);
|
||||
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
|
||||
this.transform(data, i);
|
||||
}
|
||||
index = 0;
|
||||
}
|
||||
|
||||
if (i < dataLen) {
|
||||
this.buffer.set(data.subarray(i, dataLen), index);
|
||||
}
|
||||
}
|
||||
|
||||
hash(bigEndian = true): Uint8Array {
|
||||
const digest = Buffer.allocUnsafe(20);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
|
||||
else digest.writeUInt32LE(this.state[i], i * 4);
|
||||
}
|
||||
return new Uint8Array(digest);
|
||||
}
|
||||
|
||||
final(): Uint8Array {
|
||||
const bits = Buffer.allocUnsafe(8);
|
||||
bits.writeUInt32BE(this.count[1], 0);
|
||||
bits.writeUInt32BE(this.count[0], 4);
|
||||
|
||||
const index = (this.count[0] >>> 3) & 0x3F;
|
||||
const padLen = index < 56 ? 56 - index : 120 - index;
|
||||
this.update(this.padding.subarray(0, padLen));
|
||||
this.update(bits);
|
||||
return this.hash(true);
|
||||
}
|
||||
}
|
||||
|
||||
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
|
||||
const sha1 = new Sha1StreamState();
|
||||
const blocks: Uint8Array[] = [];
|
||||
let bytesRead = 0;
|
||||
let offset = 0;
|
||||
|
||||
while (offset + sha1.blockSize <= bytes.length) {
|
||||
const block = bytes.subarray(offset, offset + sha1.blockSize);
|
||||
sha1.update(block);
|
||||
offset += sha1.blockSize;
|
||||
bytesRead += sha1.blockSize;
|
||||
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
|
||||
blocks.push(sha1.hash(false));
|
||||
}
|
||||
}
|
||||
|
||||
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
|
||||
blocks.push(sha1.final());
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// ─────────────── source staging + thumb extraction ───────────────
|
||||
|
||||
function defaultVideoTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-video');
|
||||
}
|
||||
|
||||
function sourceExtension(fileName: string, source: string): string {
|
||||
const fromName = path.extname(fileName);
|
||||
if (fromName) return fromName;
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
const fromSource = local ? path.extname(local) : '';
|
||||
return fromSource || '.mp4';
|
||||
}
|
||||
|
||||
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
|
||||
bytes: Uint8Array;
|
||||
filePath: string;
|
||||
fileName: string;
|
||||
}> {
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('video source is empty');
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
// Pre-check on disk size BEFORE reading bytes into memory. The later
|
||||
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
|
||||
// run after we'd already allocated the entire file (so a 10 GiB
|
||||
// local path still OOMs us before the check fires).
|
||||
const stat = fs.statSync(local);
|
||||
if (stat.size > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
return {
|
||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||
filePath: local,
|
||||
fileName: element.fileName || path.basename(local),
|
||||
};
|
||||
}
|
||||
|
||||
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
|
||||
const fileName = element.fileName || loaded.fileName || '';
|
||||
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
|
||||
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
|
||||
cleanups.push(() => { try { fs.unlinkSync(stagedPath); } catch { /* ignore */ } });
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
filePath: stagedPath,
|
||||
fileName,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumb: ThumbPayload;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
}> {
|
||||
let width = element.width ?? 0;
|
||||
let height = element.height ?? 0;
|
||||
let duration = element.duration ?? 0;
|
||||
let thumbBytes: Uint8Array | null = null;
|
||||
|
||||
if (element.thumbUrl) {
|
||||
try {
|
||||
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
|
||||
} catch (err) {
|
||||
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbBytes) {
|
||||
try {
|
||||
const info = await getFFmpegAddon().getVideoInfo(videoPath);
|
||||
width = width || info.width || 0;
|
||||
height = height || info.height || 0;
|
||||
duration = duration || Math.max(1, Math.round(info.duration || 0));
|
||||
if (info.image && info.image.length > 0) {
|
||||
thumbBytes = new Uint8Array(info.image);
|
||||
}
|
||||
} catch (err) {
|
||||
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbBytes) {
|
||||
thumbBytes = new Uint8Array(FALLBACK_THUMB);
|
||||
}
|
||||
|
||||
const fmt = detectImageFormat(thumbBytes);
|
||||
width = width || fmt.width || 1;
|
||||
height = height || fmt.height || 1;
|
||||
duration = duration || 1;
|
||||
|
||||
const hashes = computeHashes(thumbBytes);
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb: {
|
||||
bytes: thumbBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
if (element.noByteFallback) {
|
||||
if (!element.md5Hex || !element.sha1Hex) {
|
||||
throw new Error('video fast-upload requires md5Hex + sha1Hex');
|
||||
}
|
||||
return videoPayloadFromFingerprint(element);
|
||||
}
|
||||
|
||||
const tempDir = defaultVideoTempDir();
|
||||
const cleanups: Array<() => void> = [];
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const staged = await stageVideoSource(element, tempDir, cleanups);
|
||||
if (staged.bytes.length === 0) throw new Error('video file is empty');
|
||||
if (staged.bytes.length > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
|
||||
const hashes = computeHashes(staged.bytes);
|
||||
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
|
||||
|
||||
return {
|
||||
bytes: staged.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
sha1Blocks: computeVideoSha1Blocks(staged.bytes),
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
|
||||
filePath: staged.filePath,
|
||||
fileSize: staged.bytes.length,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
videoFormat: 0,
|
||||
thumb,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
for (const fn of cleanups.reverse()) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── exported entry ───────────────
|
||||
|
||||
/**
|
||||
* Upload a video and return the encoded MsgInfo bytes that go inside a
|
||||
* `commonElem { serviceType: 48, businessType: 21 }`.
|
||||
*
|
||||
* Two highway PUTs run when the server doesn't fast-path: the main video
|
||||
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
|
||||
*/
|
||||
export async function uploadVideoMsgInfo(
|
||||
bridge: BridgeContext,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const video = await loadVideo(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
video.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
source: 'top',
|
||||
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
|
||||
bytes: video.bytes,
|
||||
md5: video.md5,
|
||||
sha1: video.sha1Blocks,
|
||||
subFileIndex: 0,
|
||||
fastOnlyError: 'video fast-upload not available (server requires bytes)',
|
||||
},
|
||||
{
|
||||
source: 0, // upload.subFileInfos[0]
|
||||
cmdId: isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID,
|
||||
bytes: video.thumb.bytes,
|
||||
md5: video.thumb.md5,
|
||||
sha1: video.thumb.sha1,
|
||||
subFileIndex: 1,
|
||||
// No fastOnlyError: thumb always has bytes (FALLBACK_THUMB at worst).
|
||||
},
|
||||
];
|
||||
|
||||
const upload = await runNtv2Upload({
|
||||
bridge,
|
||||
isGroup,
|
||||
targetIdOrUid,
|
||||
oidbCmd: isGroup ? 0x11EA : 0x11E9,
|
||||
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100',
|
||||
requestId: 3,
|
||||
businessType: 2,
|
||||
uploadInfo: [
|
||||
{
|
||||
fileInfo: {
|
||||
fileSize: video.fileSize,
|
||||
fileHash: video.md5Hex,
|
||||
fileSha1: video.sha1Hex,
|
||||
fileName: 'nya.mp4',
|
||||
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
// Width/height kept at 0 — NapCat does the same and the QQ-NT
|
||||
// server has been observed to reject non-zero dimensions
|
||||
// here on c2c sends with a schema-mismatch error. acidify
|
||||
// *does* fill them (`payload.videoWidth/Height`) but we
|
||||
// leave that alone until c2c regression coverage exists.
|
||||
height: 0,
|
||||
width: 0,
|
||||
// `time` MUST be the real duration in seconds, otherwise
|
||||
// every receiving client renders "00:00" on the video.
|
||||
// NapCat ships `time: 0` because it sits on top of QQ-NT's
|
||||
// IPC layer, which the desktop client patches up before
|
||||
// the wire message goes out. We're a protocol-direct
|
||||
// client (same position as acidify), so we own this field.
|
||||
// acidify writes `payload.videoDuration` here for the same
|
||||
// reason — verified against `RichMediaUpload.kt::
|
||||
// buildVideoUploadInfoList` (2026-04 refactor).
|
||||
time: video.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
},
|
||||
{
|
||||
fileInfo: {
|
||||
fileSize: video.thumb.bytes.length,
|
||||
fileHash: video.thumb.md5Hex,
|
||||
fileSha1: video.thumb.sha1Hex,
|
||||
fileName: 'nya.jpg',
|
||||
type: { type: 1, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
height: video.thumb.height,
|
||||
width: video.thumb.width,
|
||||
time: 0,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 100,
|
||||
},
|
||||
],
|
||||
// Hardcoded 2 even on c2c (matches NapCat). Image/PTT use
|
||||
// `isGroup ? 2 : 1` because their legacy compat elements differ
|
||||
// per scene (notOnlineImage vs customFace; ptt c2c vs group),
|
||||
// but the legacy `videoFile` element has no scene split — its
|
||||
// fromChatType/toChatType live inside the element itself — so
|
||||
// the server generates a single group-shaped compat payload
|
||||
// regardless. Setting 1 here makes the server emit a c2c-scene
|
||||
// shaped compat blob that old QQ clients fail to resolve,
|
||||
// showing the message as "视频已过期" on those receivers while
|
||||
// new clients (which only read the commonElem) display fine.
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: {
|
||||
pic: { bizType: 0, textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
|
||||
ptt: {
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'video',
|
||||
});
|
||||
|
||||
log.debug('video upload completed: md5=%s scene=%s', video.md5Hex, isGroup ? 'group' : 'c2c');
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of video.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
/**
|
||||
* Hooks Identity uses when its read methods miss every cache layer. Wired in
|
||||
* after construction (Bridge owns these methods, but Bridge can't exist
|
||||
* before Identity does). Each call is expected to invoke the matching
|
||||
* remember* observation on this service as a side effect.
|
||||
*/
|
||||
export interface IdentityFetcher {
|
||||
fetchProfile(uin: number): Promise<UserProfileInfo>;
|
||||
fetchGroupMemberList?(groupId: number): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface UserInput {
|
||||
uid?: string;
|
||||
uin?: number;
|
||||
nickname?: string;
|
||||
remark?: string;
|
||||
isFriend?: boolean;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
interface GroupInput {
|
||||
groupId: number;
|
||||
groupName?: string;
|
||||
remark?: string;
|
||||
memberCount?: number;
|
||||
memberMax?: number;
|
||||
}
|
||||
|
||||
interface MemberInput {
|
||||
groupId: number;
|
||||
uid?: string;
|
||||
uin?: number;
|
||||
nickname?: string;
|
||||
card?: string;
|
||||
role?: string;
|
||||
level?: number;
|
||||
title?: string;
|
||||
joinTime?: number;
|
||||
lastSentTime?: number;
|
||||
shutUpTime?: number;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
interface UserRow {
|
||||
id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
is_friend: number;
|
||||
source: string;
|
||||
}
|
||||
|
||||
interface MemberRow {
|
||||
id: number;
|
||||
group_id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
active: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authoritative store for everything we know about QQ actors observed
|
||||
* during this session: the bot's own identity, friends, groups, group
|
||||
* members, user profiles, plus the bidirectional UID↔UIN index that
|
||||
* powers all OIDB-bound translation.
|
||||
*
|
||||
* Two layers internally:
|
||||
* - In-memory state (this file) — O(1) for find* on the hot path.
|
||||
* - SQLite (optional, opened by openForUin) — survives restarts.
|
||||
*
|
||||
* Both layers are kept in sync by the remember* / refresh paths.
|
||||
* Callers should never reach below the public surface; the cascade and
|
||||
* storage details are intentionally hidden.
|
||||
*/
|
||||
export class IdentityService {
|
||||
// ─── Self identity ───
|
||||
private readonly uin_: string;
|
||||
private nickname_ = '';
|
||||
private selfProfile_: UserProfileInfo | null = null;
|
||||
|
||||
// ─── In-memory domain state ───
|
||||
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
|
||||
private friends_: FriendInfo[] = [];
|
||||
private readonly groups_ = new Map<number, QQGroupInfo>();
|
||||
|
||||
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
|
||||
private readonly uinByUid = new Map<string, number>();
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseType | null;
|
||||
// Prepared-statement cache. Every `.prepare(sql)` call in this
|
||||
// service re-parses the SQL — that's the SQLite anti-pattern
|
||||
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
|
||||
// call sites stay readable (no need to enumerate 20+ named fields
|
||||
// upfront); the Map lookup is O(1) hash + string-eq, which is
|
||||
// negligible next to the SQL parse it replaces.
|
||||
private readonly stmtCache_ = new Map<string, Statement>();
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(uin: string, dbPath: string | null) {
|
||||
this.uin_ = uin;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLogger.child({ uin: uinNum })
|
||||
: moduleLogger;
|
||||
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
return;
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
/** Cached `prepare(sql)`. First call per unique SQL parses; later
|
||||
* calls reuse the same `Statement` object. See `stmtCache_`. */
|
||||
private pstmt(sql: string): Statement {
|
||||
let cached = this.stmtCache_.get(sql);
|
||||
if (cached !== undefined) return cached;
|
||||
cached = this.db!.prepare(sql);
|
||||
this.stmtCache_.set(sql, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
|
||||
}
|
||||
|
||||
static memory(uin: string): IdentityService {
|
||||
return new IdentityService(uin, null);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db?.close();
|
||||
}
|
||||
|
||||
get persistent(): boolean {
|
||||
return this.db !== null;
|
||||
}
|
||||
|
||||
setFetcher(fetcher: IdentityFetcher): void {
|
||||
this.fetcher = fetcher;
|
||||
}
|
||||
|
||||
// ─── Self identity surface ───
|
||||
|
||||
get uin(): string { return this.uin_; }
|
||||
|
||||
get nickname(): string { return this.nickname_; }
|
||||
set nickname(v: string) { this.nickname_ = v; }
|
||||
|
||||
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
|
||||
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
|
||||
|
||||
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
|
||||
|
||||
// ─── Domain object reads ───
|
||||
|
||||
findUserProfile(uin: number): UserProfileInfo | null {
|
||||
return this.userProfiles_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get friends(): FriendInfo[] { return this.friends_; }
|
||||
|
||||
findFriend(uin: number): FriendInfo | null {
|
||||
return this.friends_.find((f) => f.uin === uin) ?? null;
|
||||
}
|
||||
|
||||
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
|
||||
|
||||
findGroup(groupId: number): QQGroupInfo | null {
|
||||
return this.groups_.get(groupId) ?? null;
|
||||
}
|
||||
|
||||
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
|
||||
return this.groups_.get(groupId)?.members.get(uin) ?? null;
|
||||
}
|
||||
|
||||
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.set(member.uin, member);
|
||||
this.rememberUidUin(member.uid, member.uin);
|
||||
}
|
||||
|
||||
// ─── ID translation ───
|
||||
|
||||
/**
|
||||
* UIN → UID with network fallback. Returns cached value on hit; otherwise
|
||||
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
|
||||
* which is expected to write the result back through `rememberUserProfile`
|
||||
* before this method re-queries the cache. Throws if no UID can be
|
||||
* obtained from any layer.
|
||||
*/
|
||||
async resolveUid(uin: number, groupId?: number): Promise<string> {
|
||||
const normalized = normalizeUin(uin);
|
||||
if (normalized === null) throw new Error(`invalid uin: ${uin}`);
|
||||
|
||||
const cached = this.findUidByUin(normalized, groupId);
|
||||
if (cached) return cached;
|
||||
|
||||
if (groupId !== undefined && this.fetcher?.fetchGroupMemberList) {
|
||||
try { await this.fetcher.fetchGroupMemberList(groupId); } catch { /* ignore */ }
|
||||
const afterMembers = this.findUidByUin(normalized, groupId);
|
||||
if (afterMembers) return afterMembers;
|
||||
}
|
||||
|
||||
if (!this.fetcher) throw new Error(`failed to resolve UID for UIN ${normalized}: no fetcher`);
|
||||
|
||||
const profile = await this.fetcher.fetchProfile(normalized);
|
||||
if (profile.uid) return profile.uid;
|
||||
|
||||
throw new Error(`failed to resolve UID for UIN ${normalized}`);
|
||||
}
|
||||
|
||||
findUinByUid(uid: string, groupId?: number): number | null {
|
||||
const normalized = normalizeUid(uid);
|
||||
if (!normalized) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const member = this.findGroupMemberByUid(groupId, normalized);
|
||||
if (member) return member.uin;
|
||||
}
|
||||
const mapped = this.uinByUid.get(normalized);
|
||||
if (mapped !== undefined) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.pstmt(
|
||||
`SELECT uin FROM group_members
|
||||
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uin: number | null } | undefined;
|
||||
const uin = normalizeUin(row?.uin);
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
|
||||
const row = this.pstmt(
|
||||
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uin: number | null } | undefined;
|
||||
return normalizeUin(row?.uin);
|
||||
}
|
||||
|
||||
findUidByUin(uin: number, groupId?: number): string | null {
|
||||
const normalized = normalizeUin(uin);
|
||||
if (normalized === null) return null;
|
||||
|
||||
if (groupId !== undefined) {
|
||||
const member = this.groups_.get(groupId)?.members.get(normalized);
|
||||
if (member?.uid) return member.uid;
|
||||
}
|
||||
const mapped = this.uidByUin.get(normalized);
|
||||
if (mapped) return mapped;
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.pstmt(
|
||||
`SELECT uid FROM group_members
|
||||
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
LIMIT 1`,
|
||||
).get(groupId, normalized) as { uid: string | null } | undefined;
|
||||
const uid = normalizeUid(row?.uid);
|
||||
if (uid) return uid;
|
||||
}
|
||||
|
||||
const row = this.pstmt(
|
||||
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uid: string | null } | undefined;
|
||||
return normalizeUid(row?.uid) || null;
|
||||
}
|
||||
|
||||
// ─── Observation (write side) ───
|
||||
|
||||
rememberFriends(friends: FriendInfo[]): void {
|
||||
this.friends_ = friends;
|
||||
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
|
||||
this.runWrite('friends', () => this.transaction(() => {
|
||||
this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
.run(nowSeconds());
|
||||
for (const friend of friends) {
|
||||
this.upsertUser({
|
||||
uid: friend.uid,
|
||||
uin: friend.uin,
|
||||
nickname: friend.nickname,
|
||||
remark: friend.remark,
|
||||
isFriend: true,
|
||||
source: 'friend',
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberGroups(groups: QQGroupInfo[]): void {
|
||||
this.setGroupsInMemory(groups);
|
||||
this.runWrite('groups', () => this.transaction(() => {
|
||||
this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
.run(nowSeconds());
|
||||
for (const group of groups) {
|
||||
this.upsertGroup({
|
||||
groupId: group.groupId,
|
||||
groupName: group.groupName,
|
||||
remark: group.remark,
|
||||
memberCount: group.memberCount,
|
||||
memberMax: group.memberMax,
|
||||
});
|
||||
}
|
||||
}));
|
||||
this.hydrateActiveMembersForGroups(groups.map((group) => group.groupId));
|
||||
}
|
||||
|
||||
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
for (const member of members) this.rememberUidUin(member.uid, member.uin);
|
||||
this.runWrite('group members', () => this.transaction(() => {
|
||||
this.upsertGroup({ groupId, memberCount: members.length });
|
||||
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
.run(nowSeconds(), groupId);
|
||||
for (const member of members) {
|
||||
this.upsertGroupMember({
|
||||
groupId,
|
||||
uid: member.uid,
|
||||
uin: member.uin,
|
||||
nickname: member.nickname,
|
||||
card: member.card,
|
||||
role: member.role,
|
||||
level: member.level,
|
||||
title: member.title,
|
||||
joinTime: member.joinTime,
|
||||
lastSentTime: member.lastSentTime,
|
||||
shutUpTime: member.shutUpTime,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberUserProfile(info: UserProfileInfo): void {
|
||||
this.userProfiles_.set(info.uin, info);
|
||||
const selfUin = parseInt(this.uin_, 10) || 0;
|
||||
if (info.uin === selfUin) this.selfProfile_ = info;
|
||||
this.rememberUidUin(info.uid, info.uin);
|
||||
this.runWrite('user profile', () => this.transaction(() => this.upsertUser({
|
||||
uid: info.uid,
|
||||
uin: info.uin,
|
||||
nickname: info.nickname,
|
||||
remark: info.remark,
|
||||
source: 'profile',
|
||||
})));
|
||||
}
|
||||
|
||||
rememberGroupRequests(requests: GroupRequestInfo[]): void {
|
||||
for (const request of requests) {
|
||||
this.rememberUidUin(request.targetUid, request.targetUin);
|
||||
this.rememberUidUin(request.invitorUid, request.invitorUin);
|
||||
this.rememberUidUin(request.operatorUid, request.operatorUin);
|
||||
}
|
||||
this.runWrite('group requests', () => this.transaction(() => {
|
||||
for (const request of requests) {
|
||||
this.upsertGroup({ groupId: request.groupId, groupName: request.groupName });
|
||||
this.upsertUser({
|
||||
uid: request.targetUid,
|
||||
uin: request.targetUin,
|
||||
nickname: request.targetName,
|
||||
source: 'group_request',
|
||||
});
|
||||
this.upsertUser({
|
||||
uid: request.invitorUid,
|
||||
uin: request.invitorUin,
|
||||
nickname: request.invitorName,
|
||||
source: 'group_request',
|
||||
});
|
||||
this.upsertUser({
|
||||
uid: request.operatorUid,
|
||||
uin: request.operatorUin,
|
||||
nickname: request.operatorName,
|
||||
source: 'group_request',
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
rememberRequestIdentity(
|
||||
identity: { groupId?: number; uid?: string; uin?: number; nickname?: string; source?: string },
|
||||
): void {
|
||||
this.rememberUidUin(identity.uid, identity.uin);
|
||||
this.runWrite('request identity', () => this.transaction(() => {
|
||||
if (identity.groupId !== undefined) this.upsertGroup({ groupId: identity.groupId });
|
||||
this.upsertUser({
|
||||
uid: identity.uid,
|
||||
uin: identity.uin,
|
||||
nickname: identity.nickname,
|
||||
source: identity.source || 'request',
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
rememberGroupMemberIdentity(
|
||||
groupId: number,
|
||||
identity: { uid?: string; uin?: number; nickname?: string; card?: string },
|
||||
): void {
|
||||
this.rememberUidUin(identity.uid, identity.uin);
|
||||
this.runWrite('group member identity', () => this.transaction(() => this.upsertGroupMember({
|
||||
groupId,
|
||||
uid: identity.uid,
|
||||
uin: identity.uin,
|
||||
nickname: identity.nickname,
|
||||
card: identity.card,
|
||||
active: true,
|
||||
})));
|
||||
}
|
||||
|
||||
markGroupMemberInactive(groupId: number, identity: { uid?: string; uin?: number }): void {
|
||||
this.runWrite('group member inactive', () => {
|
||||
const uid = normalizeUid(identity.uid);
|
||||
const uin = normalizeUin(identity.uin);
|
||||
if (!uid && uin === null) return;
|
||||
const rows = this.findMemberRows(groupId, uid, uin);
|
||||
const updatedAt = nowSeconds();
|
||||
this.transaction(() => {
|
||||
for (const row of rows) {
|
||||
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
.run(updatedAt, row.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Private helpers ───
|
||||
|
||||
private rememberUidUin(uid: unknown, uin: unknown): void {
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
const normalizedUin = normalizeUin(uin);
|
||||
if (!normalizedUid || normalizedUin === null) return;
|
||||
// Drop any stale mapping for the old partner first; otherwise the two
|
||||
// maps disagree (`findUinByUid(oldUid) -> uin` while
|
||||
// `findUidByUin(uin) -> newUid`) after a uid/uin re-binding.
|
||||
const oldUid = this.uidByUin.get(normalizedUin);
|
||||
if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid);
|
||||
const oldUin = this.uinByUid.get(normalizedUid);
|
||||
if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin);
|
||||
this.uinByUid.set(normalizedUid, normalizedUin);
|
||||
this.uidByUin.set(normalizedUin, normalizedUid);
|
||||
}
|
||||
|
||||
private setGroupsInMemory(groups: QQGroupInfo[]): void {
|
||||
// Preserve existing member maps where possible so a roster refresh
|
||||
// doesn't blow away cached members for groups we already track.
|
||||
const previous = new Map(this.groups_);
|
||||
this.groups_.clear();
|
||||
for (const g of groups) {
|
||||
const existing = previous.get(g.groupId);
|
||||
this.groups_.set(g.groupId, {
|
||||
...g,
|
||||
members: existing?.members ?? g.members ?? new Map(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.clear();
|
||||
for (const m of members) {
|
||||
g.members.set(m.uin, m);
|
||||
}
|
||||
}
|
||||
|
||||
private findGroupMemberByUid(groupId: number, uid: string): GroupMemberInfo | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db!.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE,
|
||||
uin INTEGER UNIQUE,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
is_friend INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_users_uid ON users(uid);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_users_uin ON users(uin);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
group_id INTEGER PRIMARY KEY,
|
||||
group_name TEXT NOT NULL DEFAULT '',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
member_count INTEGER NOT NULL DEFAULT 0,
|
||||
member_max INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_members (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id INTEGER NOT NULL,
|
||||
uid TEXT,
|
||||
uin INTEGER,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
card TEXT NOT NULL DEFAULT '',
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
join_time INTEGER NOT NULL DEFAULT 0,
|
||||
last_sent_time INTEGER NOT NULL DEFAULT 0,
|
||||
shut_up_time INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(group_id, uid),
|
||||
UNIQUE(group_id, uin)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_active
|
||||
ON group_members(group_id, active);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uid
|
||||
ON group_members(group_id, uid);
|
||||
CREATE INDEX IF NOT EXISTS idx_identity_group_members_group_uin
|
||||
ON group_members(group_id, uin);
|
||||
`);
|
||||
}
|
||||
|
||||
private loadSnapshot(): void {
|
||||
const friendRows = this.pstmt(
|
||||
`SELECT uid, uin, nickname, remark
|
||||
FROM users
|
||||
WHERE is_friend = 1 AND uin IS NOT NULL`,
|
||||
).all() as Array<{ uid: string | null; uin: number | null; nickname: string; remark: string }>;
|
||||
this.friends_ = friendRows.map((row) => ({
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
remark: row.remark,
|
||||
}));
|
||||
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
|
||||
|
||||
const groups = this.pstmt(
|
||||
`SELECT group_id, group_name, remark, member_count, member_max
|
||||
FROM groups
|
||||
WHERE active = 1`,
|
||||
).all() as Array<{
|
||||
group_id: number;
|
||||
group_name: string;
|
||||
remark: string;
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
}>;
|
||||
this.setGroupsInMemory(groups.map((row) => ({
|
||||
groupId: row.group_id,
|
||||
groupName: row.group_name,
|
||||
remark: row.remark,
|
||||
memberCount: row.member_count,
|
||||
memberMax: row.member_max,
|
||||
members: new Map(),
|
||||
})));
|
||||
this.hydrateActiveMembersForGroups(groups.map((row) => row.group_id));
|
||||
}
|
||||
|
||||
private hydrateActiveMembersForGroups(groupIds: number[]): void {
|
||||
if (!this.db || groupIds.length === 0) return;
|
||||
|
||||
const select = this.pstmt(
|
||||
`SELECT group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND active = 1`,
|
||||
);
|
||||
for (const groupId of groupIds) {
|
||||
const rows = select.all(groupId) as Array<{
|
||||
group_id: number;
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
}>;
|
||||
const members = rows.map(rowToMemberInfo);
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
for (const m of members) this.rememberUidUin(m.uid, m.uin);
|
||||
}
|
||||
}
|
||||
|
||||
private upsertUser(input: UserInput): void {
|
||||
if (!this.db) return;
|
||||
|
||||
const uid = normalizeUid(input.uid);
|
||||
const uin = normalizeUin(input.uin);
|
||||
if (!uid && uin === null) return;
|
||||
|
||||
const rows = this.findUserRows(uid, uin);
|
||||
const primary = rows[0];
|
||||
const merged = {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: normalizeText(input.nickname) || primary?.nickname || '',
|
||||
remark: normalizeText(input.remark) || primary?.remark || '',
|
||||
isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0),
|
||||
source: normalizeText(input.source) || primary?.source || '',
|
||||
updatedAt: nowSeconds(),
|
||||
};
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.pstmt(
|
||||
`UPDATE users
|
||||
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.remark,
|
||||
merged.isFriend,
|
||||
merged.source,
|
||||
merged.updatedAt,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.pstmt(
|
||||
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.remark,
|
||||
merged.isFriend,
|
||||
merged.source,
|
||||
merged.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
private upsertGroup(input: GroupInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const existing = this.pstmt(
|
||||
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
|
||||
).get(input.groupId) as {
|
||||
group_name: string;
|
||||
remark: string;
|
||||
member_count: number;
|
||||
member_max: number;
|
||||
} | undefined;
|
||||
|
||||
this.pstmt(
|
||||
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?)
|
||||
ON CONFLICT(group_id) DO UPDATE SET
|
||||
group_name = excluded.group_name,
|
||||
remark = excluded.remark,
|
||||
member_count = excluded.member_count,
|
||||
member_max = excluded.member_max,
|
||||
active = 1,
|
||||
updated_at = excluded.updated_at`,
|
||||
).run(
|
||||
input.groupId,
|
||||
normalizeText(input.groupName) || existing?.group_name || '',
|
||||
normalizeText(input.remark) || existing?.remark || '',
|
||||
normalizeNonNegative(input.memberCount, existing?.member_count ?? 0),
|
||||
normalizeNonNegative(input.memberMax, existing?.member_max ?? 0),
|
||||
nowSeconds(),
|
||||
);
|
||||
}
|
||||
|
||||
private upsertGroupMember(input: MemberInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const uid = normalizeUid(input.uid);
|
||||
const uin = normalizeUin(input.uin);
|
||||
if (!uid && uin === null) return;
|
||||
|
||||
this.upsertGroup({ groupId: input.groupId });
|
||||
this.upsertUser({
|
||||
uid,
|
||||
uin: uin ?? undefined,
|
||||
nickname: input.nickname,
|
||||
source: 'group_member',
|
||||
});
|
||||
|
||||
const rows = this.findMemberRows(input.groupId, uid, uin);
|
||||
const primary = rows[0];
|
||||
const merged = {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: normalizeText(input.nickname) || primary?.nickname || '',
|
||||
card: normalizeText(input.card) || primary?.card || '',
|
||||
role: normalizeText(input.role) || primary?.role || 'member',
|
||||
level: normalizeNonNegative(input.level, primary?.level ?? 0),
|
||||
title: normalizeText(input.title) || primary?.title || '',
|
||||
joinTime: normalizeNonNegative(input.joinTime, primary?.join_time ?? 0),
|
||||
lastSentTime: normalizeNonNegative(input.lastSentTime, primary?.last_sent_time ?? 0),
|
||||
shutUpTime: normalizeNonNegative(input.shutUpTime, primary?.shut_up_time ?? 0),
|
||||
active: input.active === false ? 0 : input.active === true ? 1 : (primary?.active ?? 1),
|
||||
updatedAt: nowSeconds(),
|
||||
};
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.pstmt(
|
||||
`UPDATE group_members
|
||||
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
merged.joinTime,
|
||||
merged.lastSentTime,
|
||||
merged.shutUpTime,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.pstmt(
|
||||
`INSERT INTO group_members
|
||||
(group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
input.groupId,
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
merged.joinTime,
|
||||
merged.lastSentTime,
|
||||
merged.shutUpTime,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
private findUserRows(uid: string, uin: number | null): UserRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
|
||||
).all(uid, uin) as unknown as UserRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
|
||||
).all(uid) as unknown as UserRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
|
||||
).all(uin) as unknown as UserRow[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND (uid = ? OR uin = ?)
|
||||
ORDER BY id`,
|
||||
).all(groupId, uid, uin) as unknown as MemberRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND uid = ?
|
||||
ORDER BY id`,
|
||||
).all(groupId, uid) as unknown as MemberRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND uin = ?
|
||||
ORDER BY id`,
|
||||
).all(groupId, uin) as unknown as MemberRow[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private transaction<T>(fn: () => T): T {
|
||||
if (!this.db || this.inTransaction) return fn();
|
||||
this.inTransaction = true;
|
||||
this.db.exec('BEGIN');
|
||||
try {
|
||||
const result = fn();
|
||||
this.db.exec('COMMIT');
|
||||
return result;
|
||||
} catch (err) {
|
||||
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
|
||||
throw err;
|
||||
} finally {
|
||||
this.inTransaction = false;
|
||||
}
|
||||
}
|
||||
|
||||
private runWrite(label: string, fn: () => void): void {
|
||||
if (!this.db) return;
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rowToMemberInfo(row: {
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
join_time: number;
|
||||
last_sent_time: number;
|
||||
shut_up_time: number;
|
||||
}): GroupMemberInfo {
|
||||
return {
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
role: row.role || 'member',
|
||||
level: row.level,
|
||||
title: row.title,
|
||||
joinTime: row.join_time,
|
||||
lastSentTime: row.last_sent_time,
|
||||
shutUpTime: row.shut_up_time,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeUid(uid: unknown): string {
|
||||
return typeof uid === 'string' ? uid.trim() : '';
|
||||
}
|
||||
|
||||
function normalizeUin(uin: unknown): number | null {
|
||||
if (typeof uin === 'number' && Number.isFinite(uin)) {
|
||||
const n = Math.trunc(uin);
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
if (typeof uin === 'string' && uin.trim()) {
|
||||
const parsed = Number(uin);
|
||||
if (Number.isFinite(parsed)) {
|
||||
const n = Math.trunc(parsed);
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function normalizeNonNegative(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function nowSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
|
||||
|
||||
export type PushMsgBody = MessageBody;
|
||||
export type PushMsgResponseHead = ResponseHead;
|
||||
export type PushMsgContentHead = ContentHead;
|
||||
|
||||
export interface MsgPushHead {
|
||||
readonly msgType: number;
|
||||
readonly subType: number;
|
||||
readonly sequence: number;
|
||||
readonly timestamp: number;
|
||||
readonly msgId: number;
|
||||
}
|
||||
|
||||
export interface MsgPushContext {
|
||||
readonly head: MsgPushHead;
|
||||
readonly fromUin: number;
|
||||
readonly fromUid: string;
|
||||
readonly selfUin: number;
|
||||
readonly content: Uint8Array;
|
||||
readonly body: PushMsgBody | undefined;
|
||||
readonly responseHead: PushMsgResponseHead | undefined;
|
||||
readonly identity: IdentityService;
|
||||
}
|
||||
|
||||
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
|
||||
if (pkt.body.length === 0) return null;
|
||||
|
||||
// `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
|
||||
// @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
|
||||
// wrap was a no-op copy — Buffer is a Uint8Array subclass and
|
||||
// proton's decoder accepts the parent type directly. Dropping the
|
||||
// wrap saves one allocation per incoming push packet.
|
||||
const push = protobuf_decode<PushMsg>(pkt.body);
|
||||
if (!push?.message) return null;
|
||||
|
||||
const msg = push.message;
|
||||
if (!msg.contentHead) return null;
|
||||
|
||||
const head: MsgPushHead = {
|
||||
msgType: msg.contentHead.msgType ?? 0,
|
||||
subType: msg.contentHead.subType ?? 0,
|
||||
sequence: msg.contentHead.sequence ?? 0,
|
||||
timestamp: msg.contentHead.timestamp ?? 0,
|
||||
msgId: msg.contentHead.msgId ?? 0,
|
||||
};
|
||||
|
||||
let fromUin = 0;
|
||||
let fromUid = '';
|
||||
if (msg.responseHead) {
|
||||
fromUin = msg.responseHead.fromUin ?? 0;
|
||||
fromUid = msg.responseHead.fromUid ?? '';
|
||||
}
|
||||
|
||||
let selfUin = 0;
|
||||
if (pkt.uin) {
|
||||
const n = parseInt(pkt.uin, 10);
|
||||
if (!isNaN(n)) selfUin = n;
|
||||
}
|
||||
|
||||
const content = msg.body?.msgContent ?? new Uint8Array(0);
|
||||
|
||||
return {
|
||||
head,
|
||||
fromUin,
|
||||
fromUid,
|
||||
selfUin,
|
||||
content,
|
||||
body: msg.body,
|
||||
responseHead: msg.responseHead,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
FriendAddEvent,
|
||||
FriendPokeEvent,
|
||||
FriendRequestEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type {
|
||||
FriendRecall,
|
||||
FriendRequest,
|
||||
GeneralGrayTipInfo,
|
||||
NewFriend,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { MsgPushContext } from '../context';
|
||||
import { Event0x210SubType } from '../enums';
|
||||
import {
|
||||
buildTemplateMap, findTemplateValue,
|
||||
parseU64OrZero,
|
||||
resolveUidToUin,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x210SubType) {
|
||||
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
|
||||
// 138 (other-recalled) and 139 (self-recalled) share the same
|
||||
// FriendRecall wire shape; the helper picks the right uid side
|
||||
// based on the subType.
|
||||
case Event0x210SubType.FriendRecallNotice:
|
||||
case Event0x210SubType.FriendRecallSelfNotice:
|
||||
return decodeFriendRecall(ctx);
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
// 179 + 226 both carry the NewFriend payload — see enum comment.
|
||||
case Event0x210SubType.NewFriendNotice:
|
||||
case Event0x210SubType.NewFriendNoticeAlt:
|
||||
return decodeNewFriend(ctx);
|
||||
case Event0x210SubType.GroupAppStatePush:
|
||||
// QQ-client-internal troop shortcut bar / discussion app state
|
||||
// push — no OneBot-level event. See enum comment for the
|
||||
// decompiled-source breakdown of the sub_cmd dispatch.
|
||||
return [];
|
||||
case Event0x210SubType.UnmappedClientState380:
|
||||
// QQ-NT-era subType with no reference handler: the legacy QQ
|
||||
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
|
||||
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
|
||||
// an NT-era addition. None of the NT clients (Lagrange.Core,
|
||||
// LagrangeGo, lagrange-python, mania) handle it either. See the
|
||||
// enum comment for the full investigation; acknowledge silently
|
||||
// until someone maps the schema.
|
||||
return [];
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const request = protobuf_decode<FriendRequest>(ctx.content);
|
||||
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 = protobuf_decode<FriendRecall>(ctx.content);
|
||||
if (!recall?.info) return [];
|
||||
// 138 = friend recalled their own message sent to bot (peer = fromUid).
|
||||
// 139 = bot recalled own message sent to friend (peer = toUid). Same
|
||||
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
|
||||
// split, self-recall events surface `userUin` as the bot itself which
|
||||
// confuses downstream OneBot consumers that key off `user_id`.
|
||||
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
|
||||
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
|
||||
const ev: FriendRecallEvent = {
|
||||
kind: 'friend_recall',
|
||||
time: recall.info.time ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
|
||||
msgSeq: recall.info.clientSequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const nf = protobuf_decode<NewFriend>(ctx.content);
|
||||
if (!nf?.info) return [];
|
||||
const newFriendUid = nf.info.uid ?? '';
|
||||
const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin);
|
||||
if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot
|
||||
const ev: FriendAddEvent = {
|
||||
kind: 'friend_add',
|
||||
// proto field is `fixed32 Time` — already uint32 seconds epoch.
|
||||
// Fall back to head.timestamp if the field is missing (some
|
||||
// captures have it as 0).
|
||||
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: newFriendUin,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
|
||||
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: FriendPokeEvent = {
|
||||
kind: 'friend_poke',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
GroupEssenceEvent,
|
||||
GroupMsgEmojiLikeEvent,
|
||||
GroupMuteEvent,
|
||||
GroupPokeEvent,
|
||||
GroupRecallEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type {
|
||||
GroupMute,
|
||||
GroupReactNotify,
|
||||
NotifyMessageBody,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { MsgPushContext } from '../context';
|
||||
import { Event0x2DCSubType } from '../enums';
|
||||
import {
|
||||
buildTemplateMap, findTemplateValue,
|
||||
parseU64OrZero,
|
||||
resolveUidToUin,
|
||||
unwrapGroupNotifyPayload,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
|
||||
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
|
||||
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const mute = protobuf_decode<GroupMute>(ctx.content);
|
||||
if (!mute?.data?.state) return [];
|
||||
const duration = mute.data.state.duration ?? 0;
|
||||
const ev: GroupMuteEvent = {
|
||||
kind: 'group_mute',
|
||||
time: mute.data.timestamp ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: mute.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? '', ctx.fromUin),
|
||||
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
|
||||
const recalled = notify.recall.recallMessages[0];
|
||||
const ev: GroupRecallEvent = {
|
||||
kind: 'group_recall',
|
||||
time: recalled.time ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0,
|
||||
notify.recall.operatorUid || notify.operatorUid || '', ctx.fromUin),
|
||||
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? '', ctx.fromUin),
|
||||
msgSeq: recalled.sequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: GroupPokeEvent = {
|
||||
kind: 'group_poke',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const payload = unwrapGroupNotifyPayload(ctx.content);
|
||||
if (!payload) return [];
|
||||
const notify = protobuf_decode<NotifyMessageBody>(payload);
|
||||
if (!notify?.essenceMessage) return [];
|
||||
const essence = notify.essenceMessage;
|
||||
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
|
||||
const ev: GroupEssenceEvent = {
|
||||
kind: 'group_essence',
|
||||
time: essence.timestamp ?? ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: essence.groupUin ?? notify.groupUin ?? 0,
|
||||
senderUin: essence.memberUin ?? 0,
|
||||
operatorUin: essence.operatorUin ?? ctx.fromUin,
|
||||
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
|
||||
random: essence.random ?? 0,
|
||||
set: setFlag === 1,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// Magic prefix QQ prepends to the GroupReactNotify payload inside
|
||||
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
|
||||
// (see api/group.ts: `msgContent?.slice(7)`).
|
||||
const GROUP_REACT_PREFIX_BYTES = 7;
|
||||
// Discriminator on GroupReactNotify.field13 — same subType is reused
|
||||
// for other notify variants, only 35 means "emoji react". Anything
|
||||
// else falls through to MsgPush.Unknown for protocol-drift visibility.
|
||||
const GROUP_REACT_DISCRIMINATOR = 35;
|
||||
|
||||
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
|
||||
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
|
||||
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
|
||||
const notify = protobuf_decode<GroupReactNotify>(payload);
|
||||
if (!notify) return [];
|
||||
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
|
||||
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
|
||||
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
|
||||
return [];
|
||||
}
|
||||
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
|
||||
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
|
||||
if (!content) return [];
|
||||
|
||||
const groupId = Number(notify.groupUin ?? 0n);
|
||||
const operatorUid = content.operatorUid ?? '';
|
||||
const emojiId = content.code ?? '';
|
||||
const count = content.count ?? 1;
|
||||
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
|
||||
// removed. Older payloads occasionally omit it; default to "add"
|
||||
// since most clients can only generate add events.
|
||||
const isAdd = (content.type ?? 1) === 1;
|
||||
const msgSeq = Number(target?.seq ?? 0n);
|
||||
|
||||
const ev: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
|
||||
operatorUid,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
count,
|
||||
isAdd,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { FriendMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: FriendMessage = {
|
||||
kind: 'friend_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
senderNick: '',
|
||||
};
|
||||
if (ctx.responseHead?.forward?.friendName) {
|
||||
ev.senderNick = ctx.responseHead.forward.friendName;
|
||||
}
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupAdminEvent } from '../../events';
|
||||
import type { GroupAdmin } from '@snowluma/proto-defs/notify';
|
||||
import { resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
|
||||
const admin = protobuf_decode<GroupAdmin>(ctx.content);
|
||||
if (!admin?.body) return [];
|
||||
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
|
||||
if (!extra) return [];
|
||||
const ev: GroupAdminEvent = {
|
||||
kind: 'group_admin',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: admin.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(ctx.identity, admin.groupUin ?? 0, extra.adminUid ?? '', ctx.fromUin),
|
||||
set: admin.body.extraEnable !== undefined,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupInviteEvent } from '../../events';
|
||||
import type {
|
||||
GroupInvitation, GroupInvite,
|
||||
GroupJoin,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import { resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
|
||||
const join = protobuf_decode<GroupJoin>(ctx.content);
|
||||
if (!join) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: join.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', ctx.fromUin),
|
||||
fromUid: join.targetUid ?? '',
|
||||
subType: 'add',
|
||||
message: '',
|
||||
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
|
||||
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
|
||||
if (!invitation?.info?.inner) return [];
|
||||
const inner = invitation.info.inner;
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: inner.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', ctx.fromUin),
|
||||
fromUid: inner.invitorUid ?? '',
|
||||
subType: 'invite',
|
||||
message: '',
|
||||
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
|
||||
const invite = protobuf_decode<GroupInvite>(ctx.content);
|
||||
if (!invite) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId: invite.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', ctx.fromUin),
|
||||
fromUid: invite.invitorUid ?? '',
|
||||
subType: 'invite',
|
||||
message: '',
|
||||
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
|
||||
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
|
||||
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
|
||||
const change = protobuf_decode<GroupChange>(ctx.content);
|
||||
if (!change) return [];
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
|
||||
const change = protobuf_decode<GroupChange>(ctx.content);
|
||||
if (!change) return [];
|
||||
const dt = change.decreaseType ?? 0;
|
||||
const groupId = change.groupUin ?? 0;
|
||||
const userUid = change.memberUid ?? '';
|
||||
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
|
||||
const ev: GroupMemberLeave = {
|
||||
kind: 'group_member_leave',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0),
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
userUid,
|
||||
operatorUid,
|
||||
isKick: dt !== 0 && dt !== 130,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
|
||||
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
|
||||
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
|
||||
if (!joined) return [];
|
||||
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
|
||||
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
|
||||
// — saturate to 0 on the unlikely overflow rather than letting
|
||||
// BigInt propagate downstream where consumers expect a number.
|
||||
const groupUinBig = joined.groupUin ?? 0n;
|
||||
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
|
||||
const operatorUid = joined.operatorUid ?? '';
|
||||
// We're the one joining — surface the bot's own identity as userUin
|
||||
// so the existing converter's `notice.group_increase` shape works
|
||||
// unchanged.
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
userUin: ctx.selfUin,
|
||||
userUid: ctx.identity.selfUid ?? '',
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
|
||||
operatorUid,
|
||||
};
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { GroupMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: GroupMessage = {
|
||||
kind: 'group_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements: decodeRichBody(ctx.body, true),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
senderCard: '',
|
||||
senderRole: '',
|
||||
};
|
||||
if (ctx.responseHead?.grp) {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
|
||||
if (member) {
|
||||
if (!ev.senderNick) ev.senderNick = member.nickname;
|
||||
ev.senderCard = member.card;
|
||||
ev.senderRole = member.role;
|
||||
}
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { TempMessage } from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
|
||||
const ev: TempMessage = {
|
||||
kind: 'temp_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
};
|
||||
if (ctx.responseHead?.grp) {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
if (!ev.senderNick) {
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend) ev.senderNick = friend.nickname;
|
||||
}
|
||||
return [ev];
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
export enum PkgType {
|
||||
ForwardFakePrivateMessage = 9,
|
||||
PrivateMessage = 166,
|
||||
GroupMessage = 82,
|
||||
TempMessage = 141,
|
||||
Event0x210 = 528,
|
||||
Event0x2DC = 732,
|
||||
PrivateRecordMessage = 208,
|
||||
PrivateFileMessage = 529,
|
||||
GroupRequestInvitationNotice = 525,
|
||||
GroupRequestJoinNotice = 84,
|
||||
/**
|
||||
* Self-join admittance — fires on the bot's session right after an
|
||||
* admin approves its `set_group_add_request` or an invite-accept
|
||||
* goes through. Ported from `lagrange-python`'s
|
||||
* `server_push/msg.py:108 case 85`. Maps to OneBot11
|
||||
* `notice.group_increase` with the bot itself as `user_id` —
|
||||
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
|
||||
* bot's own join, so without this case the bot never knows it
|
||||
* just entered a group until the first message arrives.
|
||||
*/
|
||||
GroupSelfJoinedNotice = 85,
|
||||
GroupInviteNotice = 87,
|
||||
GroupAdminChangedNotice = 44,
|
||||
GroupMemberIncreaseNotice = 33,
|
||||
GroupMemberDecreaseNotice = 34,
|
||||
}
|
||||
|
||||
export enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupMsgEmojiLikeNotice = 16,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
}
|
||||
|
||||
export enum Event0x210SubType {
|
||||
FriendRequestNotice = 35,
|
||||
/**
|
||||
* Outgoing friend-message recall — bot recalled its own message that
|
||||
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
|
||||
* difference is direction (138 = friend recalled their own message
|
||||
* sent to bot, 139 = bot recalled own message sent to friend).
|
||||
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
|
||||
* registered for both 138 and 139) + acidify (`138, 139 ->
|
||||
* parseFriendRecall`). The decoder uses the subType to figure out
|
||||
* which UID side ends up as `userUin` on the emitted event.
|
||||
*/
|
||||
FriendRecallSelfNotice = 139,
|
||||
FriendRecallNotice = 138,
|
||||
FriendPokeNotice = 290,
|
||||
/**
|
||||
* Mutual-accept friend notice — 179 fires when bot sent a friend
|
||||
* request and the other side accepted; 226 fires for the opposite
|
||||
* direction. Both decode through the same `NewFriend` wire shape
|
||||
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
|
||||
* in `client/listener.go:248-258`). Maps to OneBot11
|
||||
* `notice.friend_add`.
|
||||
*/
|
||||
NewFriendNotice = 179,
|
||||
NewFriendNoticeAlt = 226,
|
||||
/**
|
||||
* Group-app state push (troop shortcut bar / discussion app).
|
||||
*
|
||||
* Sourced from the decompiled stock QQ Android client decoder at
|
||||
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
|
||||
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
|
||||
* dispatching on `uint32_sub_cmd`:
|
||||
*
|
||||
* - 0x1 → `UpdateAppUnreadNum`: a list of
|
||||
* `{group_code, app_id, unread_num}` entries the QQ client uses
|
||||
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
|
||||
* / `101896870` for the shortcut bar) in sync.
|
||||
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
|
||||
* for discussion-group app tips, routed to `getGAudioHandler()`.
|
||||
* - 0x4 → delegated to the troop online-push handler.
|
||||
*
|
||||
* None of these have a OneBot event mapping — they're QQ-client-UI
|
||||
* state pushes (unread badges, in-app tips), not user-visible
|
||||
* conversation events. Acknowledge the subType so it doesn't keep
|
||||
* showing up as "unknown" in debug logs and drop it silently.
|
||||
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
|
||||
* fall through on this one because they don't surface the shortcut
|
||||
* bar either.
|
||||
*/
|
||||
GroupAppStatePush = 38,
|
||||
/**
|
||||
* Unmapped QQ-NT-internal subType — first seen as a recurring
|
||||
* "Event0x210 unknown subType=380" debug log in production captures.
|
||||
*
|
||||
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
|
||||
* enumerates SubType0x26 (38) through SubType0x146 (326) under
|
||||
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
|
||||
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
|
||||
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
|
||||
*
|
||||
* The NT-era reference clients also don't handle it: Lagrange.Core
|
||||
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
|
||||
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
|
||||
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
|
||||
*
|
||||
* Most likely a QQ-NT-client-UI state push (similar to 38) that
|
||||
* doesn't map to any OneBot event. Acknowledge silently to keep the
|
||||
* unknown log clean; if a real OneBot event ends up depending on it,
|
||||
* revisit with whichever NT-era project finally maps the schema.
|
||||
*/
|
||||
UnmappedClientState380 = 380,
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { inflateSync } from 'zlib';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
|
||||
|
||||
export function makeImageUrl(origUrl: string): string {
|
||||
if (!origUrl) return '';
|
||||
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
|
||||
return 'http://gchat.qpic.cn' + origUrl;
|
||||
}
|
||||
|
||||
export function decompressData(data: Uint8Array): string {
|
||||
if (!data || data.length === 0) return '';
|
||||
if (data[0] === 0x01 && data.length > 1) {
|
||||
try {
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1)));
|
||||
return inflated.toString('utf8');
|
||||
} catch { return ''; }
|
||||
}
|
||||
if (data[0] === 0x00 && data.length > 1) {
|
||||
return Buffer.from(data.subarray(1)).toString('utf8');
|
||||
}
|
||||
return Buffer.from(data).toString('utf8');
|
||||
}
|
||||
|
||||
export function isNumericUin(value: string): boolean {
|
||||
return value.length > 0 && /^\d+$/.test(value);
|
||||
}
|
||||
|
||||
export function parseU64OrZero(value: string): number {
|
||||
if (!value) return 0;
|
||||
const n = parseInt(value, 10);
|
||||
return isNaN(n) ? 0 : n;
|
||||
}
|
||||
|
||||
// Cascades group-scoped lookup → in-memory map → SQLite.
|
||||
// No network fallback on the parse hot path: missing identities fall back to
|
||||
// `fallback` and downstream events drive a roster refresh asynchronously.
|
||||
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number {
|
||||
if (!uid) return fallback;
|
||||
if (isNumericUin(uid)) {
|
||||
const n = parseInt(uid, 10);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
const uin = identity.findUinByUid(uid, groupId || undefined);
|
||||
if (uin !== null) return uin;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function decodeOperatorUid(bytes: Uint8Array): string {
|
||||
if (!bytes || bytes.length === 0) return '';
|
||||
const info = protobuf_decode<OperatorInfo>(bytes);
|
||||
if (info?.operatorField?.uid) return info.operatorField.uid;
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of params) {
|
||||
if (p.name !== undefined) map.set(p.name, p.value ?? '');
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
|
||||
for (const k of keys) {
|
||||
const v = map.get(k);
|
||||
if (v) return v;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
|
||||
if (content.length <= 7) return null;
|
||||
const lenBe = (content[5] << 8) | content[6];
|
||||
const lenLe = content[5] | (content[6] << 8);
|
||||
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
|
||||
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
|
||||
return content.subarray(7);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import { buildContext } from './context';
|
||||
import { decodeEvent0x210 } from './decoders/event-0x210';
|
||||
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
|
||||
import { decodeFriendMessage } from './decoders/friend-message';
|
||||
import { decodeGroupAdmin } from './decoders/group-admin';
|
||||
import {
|
||||
decodeGroupInvitation, decodeGroupInvite,
|
||||
decodeGroupJoinRequest,
|
||||
} from './decoders/group-join-request';
|
||||
import {
|
||||
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
|
||||
} from './decoders/group-member-change';
|
||||
import { decodeGroupMessage } from './decoders/group-message';
|
||||
import { decodeTempMessage } from './decoders/temp-message';
|
||||
import { PkgType } from './enums';
|
||||
import { MsgPushRegistry } from './registry';
|
||||
|
||||
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
const registry = new MsgPushRegistry();
|
||||
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
|
||||
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
|
||||
registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined);
|
||||
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
|
||||
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
|
||||
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);
|
||||
registry.register(PkgType.GroupInviteNotice, decodeGroupInvite);
|
||||
registry.register(PkgType.Event0x210, decodeEvent0x210);
|
||||
registry.register(PkgType.Event0x2DC, decodeEvent0x2DC);
|
||||
registry.register(PkgType.GroupMessage, decodeGroupMessage);
|
||||
registry.register(PkgType.TempMessage, decodeTempMessage);
|
||||
registry.register([
|
||||
PkgType.PrivateMessage,
|
||||
PkgType.ForwardFakePrivateMessage,
|
||||
PkgType.PrivateRecordMessage,
|
||||
PkgType.PrivateFileMessage,
|
||||
], decodeFriendMessage);
|
||||
|
||||
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
|
||||
const ctx = buildContext(pkt, identity);
|
||||
if (!ctx) return [];
|
||||
return registry.decode(ctx);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { MsgPushContext } from './context';
|
||||
import type { PkgType } from './enums';
|
||||
|
||||
const log = createLogger('MsgPush');
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
|
||||
|
||||
export class MsgPushRegistry {
|
||||
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
|
||||
|
||||
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
|
||||
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
|
||||
for (const t of list) {
|
||||
if (this.decoders_.has(t)) {
|
||||
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
|
||||
}
|
||||
this.decoders_.set(t, decoder);
|
||||
}
|
||||
}
|
||||
|
||||
decode(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
|
||||
if (!decoder) {
|
||||
// Unrecognized PkgType: either we don't care about this notify, or
|
||||
// the QQ NT client added a new variant. Surface at debug so a
|
||||
// protocol change can be spotted without spamming production logs.
|
||||
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return decoder(ctx);
|
||||
} catch (e) {
|
||||
log.error('decoder error for PkgType=%d subType=%d: %s',
|
||||
ctx.head.msgType, ctx.head.subType,
|
||||
e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import type { MessageElement } from '../events';
|
||||
import type {
|
||||
Elem,
|
||||
GroupFileExtra,
|
||||
MentionExtra,
|
||||
MsgInfo,
|
||||
NotOnlineImage,
|
||||
QFaceExtra,
|
||||
QSmallFaceExtra,
|
||||
} from '@snowluma/proto-defs/element';
|
||||
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
|
||||
import { decompressData, makeImageUrl } from './helpers';
|
||||
|
||||
type ElemDecoded = Elem;
|
||||
type RichTextDecoded = RichText;
|
||||
export type PushMsgBody = MessageBody;
|
||||
|
||||
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
|
||||
const elements: MessageElement[] = [];
|
||||
if (body?.richText) {
|
||||
const rt = body.richText;
|
||||
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
|
||||
extractRichtextExtras(rt, elements, isGroup);
|
||||
}
|
||||
if (body?.msgContent && body.msgContent.length > 0) {
|
||||
extractMsgContent(body.msgContent, elements);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const result: MessageElement[] = [];
|
||||
let skipNext = false;
|
||||
|
||||
for (const elem of elems) {
|
||||
if (skipNext) { skipNext = false; continue; }
|
||||
|
||||
// Reply / quote
|
||||
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
|
||||
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
|
||||
}
|
||||
|
||||
// Text (with possible @ detection)
|
||||
if (elem.text) {
|
||||
const t = elem.text;
|
||||
let mention: MentionExtra | null = null;
|
||||
if (t.pbReserve && t.pbReserve.length > 0) {
|
||||
mention = protobuf_decode<MentionExtra>(t.pbReserve);
|
||||
}
|
||||
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
|
||||
const hasMention = mention && (mention.type === 1 || mention.type === 2);
|
||||
|
||||
if (hasAttr6 || hasMention) {
|
||||
const me: MessageElement = { type: 'at', text: t.str ?? '' };
|
||||
if (hasAttr6) {
|
||||
const buf = t.attr6Buf!;
|
||||
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
|
||||
}
|
||||
if (hasMention && mention) {
|
||||
me.uid = mention.uid ?? '';
|
||||
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
|
||||
}
|
||||
result.push(me);
|
||||
} else {
|
||||
const text = t.str ?? '';
|
||||
if (text) result.push({ type: 'text', text });
|
||||
}
|
||||
}
|
||||
|
||||
// Face
|
||||
if (elem.face) {
|
||||
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
|
||||
}
|
||||
|
||||
// MarketFace
|
||||
if (elem.marketFace) {
|
||||
result.push({
|
||||
type: 'mface',
|
||||
text: elem.marketFace.faceName ?? '',
|
||||
faceId: elem.marketFace.tabId ?? 0,
|
||||
subType: elem.marketFace.subType ?? 0,
|
||||
});
|
||||
}
|
||||
|
||||
// NotOnlineImage (C2C image)
|
||||
if (elem.notOnlineImage) {
|
||||
const img = elem.notOnlineImage;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
const urlPath = img.origUrl || img.bigUrl || '';
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(urlPath),
|
||||
fileId: img.filePath ?? '',
|
||||
fileSize: img.fileLen ?? 0,
|
||||
width: img.picWidth ?? 0,
|
||||
height: img.picHeight ?? 0,
|
||||
subType: img.pbRes?.subType ?? 0,
|
||||
summary: img.pbRes?.summary ?? '[image]',
|
||||
md5Hex: toHexUpper(img.picMd5),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// CustomFace (group image)
|
||||
if (elem.customFace) {
|
||||
const img = elem.customFace;
|
||||
if (img.md5 && img.md5.length > 0) {
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(img.origUrl ?? ''),
|
||||
fileId: img.filePath ?? '',
|
||||
fileSize: img.size ?? 0,
|
||||
width: img.width ?? 0,
|
||||
height: img.height ?? 0,
|
||||
subType: img.pbRes?.subType ?? 0,
|
||||
summary: img.pbRes?.summary ?? '[image]',
|
||||
md5Hex: toHexUpper(img.md5),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// VideoFile
|
||||
if (elem.videoFile) {
|
||||
const v = elem.videoFile;
|
||||
result.push({
|
||||
type: 'video',
|
||||
fileId: v.fileUuid ?? '',
|
||||
fileName: v.fileName ?? '',
|
||||
fileSize: v.fileSize ?? 0,
|
||||
duration: v.fileTime ?? 0,
|
||||
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
|
||||
mediaNode: {
|
||||
fileUuid: v.fileUuid ?? '',
|
||||
info: {
|
||||
fileSize: v.fileSize ?? 0,
|
||||
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? toHexUpper(v.fileMd5) : '',
|
||||
fileName: v.fileName ?? '',
|
||||
width: v.fileWidth ?? 0,
|
||||
height: v.fileHeight ?? 0,
|
||||
time: v.fileTime ?? 0,
|
||||
type: {
|
||||
type: 2,
|
||||
videoFormat: v.fileFormat ?? 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// GroupFile
|
||||
if (elem.groupFile) {
|
||||
const f = elem.groupFile;
|
||||
result.push({
|
||||
type: 'file',
|
||||
fileId: f.fileId ?? '',
|
||||
fileName: f.filename ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
});
|
||||
}
|
||||
|
||||
// TransElem type=24 (group file via transport)
|
||||
if (elem.transElem) {
|
||||
const te = elem.transElem;
|
||||
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
|
||||
const val = te.elemValue;
|
||||
const len = (val[1] << 8) | val[2];
|
||||
if (val.length >= 3 + len) {
|
||||
const extra = protobuf_decode<GroupFileExtra>(val.subarray(3, 3 + len));
|
||||
if (extra?.inner?.info) {
|
||||
const info = extra.inner.info;
|
||||
result.push({
|
||||
type: 'file',
|
||||
fileName: info.fileName ?? '',
|
||||
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
|
||||
fileId: info.fileId ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RichMsg
|
||||
if (elem.richMsg) {
|
||||
const rm = elem.richMsg;
|
||||
if (rm.template1 && rm.template1.length > 0) {
|
||||
const content = decompressData(rm.template1);
|
||||
if (content) {
|
||||
const svcId = rm.serviceId ?? 0;
|
||||
if (svcId === 35) {
|
||||
const pos = content.indexOf('m_resid="');
|
||||
if (pos !== -1) {
|
||||
const start = pos + 9;
|
||||
const end = content.indexOf('"', start);
|
||||
if (end !== -1) {
|
||||
result.push({ type: 'forward', resId: content.substring(start, end) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
} else if (svcId === 1) {
|
||||
result.push({ type: 'json', text: content });
|
||||
} else {
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LightApp
|
||||
if (elem.lightApp) {
|
||||
const la = elem.lightApp;
|
||||
if (la.data && la.data.length > 0) {
|
||||
const content = decompressData(la.data);
|
||||
if (content) result.push({ type: 'json', text: content });
|
||||
}
|
||||
}
|
||||
|
||||
// CommonElem
|
||||
if (elem.commonElem) {
|
||||
const ce = elem.commonElem;
|
||||
const svcType = ce.serviceType ?? 0;
|
||||
const bizType = ce.businessType ?? 0;
|
||||
|
||||
if (svcType === 2) {
|
||||
// Poke
|
||||
result.push({ type: 'poke', subType: bizType });
|
||||
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
|
||||
// Flash image
|
||||
const pb = ce.pbElem;
|
||||
let pos = 1;
|
||||
let length = 0, shift = 0;
|
||||
while (pos < pb.length) {
|
||||
const b = pb[pos++];
|
||||
length |= (b & 0x7f) << shift;
|
||||
shift += 7;
|
||||
if ((b & 0x80) === 0) break;
|
||||
}
|
||||
if (pos + length <= pb.length) {
|
||||
const img = protobuf_decode<NotOnlineImage>(pb.subarray(pos, pos + length));
|
||||
if (img) {
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: img.filePath ?? '',
|
||||
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
|
||||
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
|
||||
};
|
||||
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + toHexUpper(img.picMd5) + '/0';
|
||||
}
|
||||
result.push(me);
|
||||
}
|
||||
}
|
||||
skipNext = true;
|
||||
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
|
||||
// NTQQ new protocol image/record/video
|
||||
const info = protobuf_decode<MsgInfo>(ce.pbElem);
|
||||
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
|
||||
const body = info.msgInfoBody[0];
|
||||
if (body.index?.info) {
|
||||
const idx = body.index;
|
||||
const fi = idx.info!;
|
||||
|
||||
if (bizType === 10 || bizType === 20) {
|
||||
// Image
|
||||
let url = '';
|
||||
if (body.picture) {
|
||||
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
|
||||
const path = body.picture.urlPath ?? '';
|
||||
if (path) {
|
||||
url = 'https://' + domain + path;
|
||||
if (body.picture.ext?.originalParameter) {
|
||||
url += body.picture.ext.originalParameter;
|
||||
}
|
||||
}
|
||||
}
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: fi.fileName ?? '',
|
||||
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
|
||||
height: fi.height ?? 0, imageUrl: url,
|
||||
};
|
||||
if (fi.fileHash) me.md5Hex = fi.fileHash;
|
||||
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
|
||||
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
|
||||
if (info.extBizInfo?.pic) {
|
||||
me.subType = info.extBizInfo.pic.bizType ?? 0;
|
||||
me.summary = info.extBizInfo.pic.textSummary || '[image]';
|
||||
}
|
||||
result.push(me);
|
||||
} else if (bizType === 12 || bizType === 22) {
|
||||
// Record
|
||||
result.push({
|
||||
type: 'record', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
fileSize: fi.fileSize ?? 0,
|
||||
md5Hex: fi.fileHash ?? '',
|
||||
sha1Hex: fi.fileSha1 ?? '',
|
||||
voiceFormat: fi.type?.voiceFormat ?? 0,
|
||||
mediaNode: {
|
||||
fileUuid: idx.fileUuid,
|
||||
storeId: idx.storeId,
|
||||
uploadTime: idx.uploadTime,
|
||||
ttl: idx.ttl,
|
||||
subType: idx.subType,
|
||||
info: {
|
||||
fileSize: fi.fileSize,
|
||||
fileHash: fi.fileHash,
|
||||
fileSha1: fi.fileSha1,
|
||||
fileName: fi.fileName,
|
||||
width: fi.width,
|
||||
height: fi.height,
|
||||
time: fi.time,
|
||||
original: fi.original,
|
||||
type: {
|
||||
type: fi.type?.type,
|
||||
picFormat: fi.type?.picFormat,
|
||||
videoFormat: fi.type?.videoFormat,
|
||||
voiceFormat: fi.type?.voiceFormat,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (bizType === 11 || bizType === 21) {
|
||||
// Video
|
||||
result.push({
|
||||
type: 'video', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
|
||||
duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
width: fi.width ?? 0,
|
||||
height: fi.height ?? 0,
|
||||
md5Hex: fi.fileHash ?? '',
|
||||
sha1Hex: fi.fileSha1 ?? '',
|
||||
videoFormat: fi.type?.videoFormat ?? 0,
|
||||
mediaNode: {
|
||||
fileUuid: idx.fileUuid,
|
||||
storeId: idx.storeId,
|
||||
uploadTime: idx.uploadTime,
|
||||
ttl: idx.ttl,
|
||||
subType: idx.subType,
|
||||
info: {
|
||||
fileSize: fi.fileSize,
|
||||
fileHash: fi.fileHash,
|
||||
fileSha1: fi.fileSha1,
|
||||
fileName: fi.fileName,
|
||||
width: fi.width,
|
||||
height: fi.height,
|
||||
time: fi.time,
|
||||
original: fi.original,
|
||||
type: {
|
||||
type: fi.type?.type,
|
||||
picFormat: fi.type?.picFormat,
|
||||
videoFormat: fi.type?.videoFormat,
|
||||
voiceFormat: fi.type?.voiceFormat,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (svcType === 33 && ce.pbElem) {
|
||||
// Small face
|
||||
const extra = protobuf_decode<QSmallFaceExtra>(ce.pbElem);
|
||||
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
|
||||
} else if (svcType === 37 && ce.pbElem) {
|
||||
// Big face
|
||||
const extra = protobuf_decode<QFaceExtra>(ce.pbElem);
|
||||
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
|
||||
skipNext = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function extractRichtextExtras(
|
||||
rt: RichTextDecoded,
|
||||
elements: MessageElement[],
|
||||
isGroup = false
|
||||
): void {
|
||||
// Ptt (voice)
|
||||
if (rt.ptt) {
|
||||
const p = rt.ptt;
|
||||
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '';
|
||||
const me: MessageElement = {
|
||||
type: 'record', fileName: p.fileName ?? '',
|
||||
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
|
||||
fileHash: md5Hex,
|
||||
md5Hex,
|
||||
voiceFormat: p.format ?? 0,
|
||||
};
|
||||
if (isGroup && (p.fileId ?? 0n) !== 0n) {
|
||||
me.fileId = p.groupFileKey ?? '';
|
||||
} else {
|
||||
if (p.fileUuid && p.fileUuid.length > 0) {
|
||||
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
|
||||
}
|
||||
}
|
||||
me.mediaNode = {
|
||||
fileUuid: me.fileId ?? '',
|
||||
info: {
|
||||
fileSize: p.fileSize ?? 0,
|
||||
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '',
|
||||
fileName: p.fileName ?? '',
|
||||
time: p.time ?? 0,
|
||||
type: {
|
||||
type: 3,
|
||||
voiceFormat: p.format ?? 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
elements.push(me);
|
||||
}
|
||||
|
||||
// NotOnlineFile (C2C file)
|
||||
if (rt.notOnlineFile) {
|
||||
const f = rt.notOnlineFile;
|
||||
elements.push({
|
||||
type: 'file', fileId: f.fileUuid ?? '',
|
||||
fileName: f.fileName ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
fileHash: f.fileHash ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
|
||||
// `MessageBody.msgContent` is where the QQ-NT server actually puts
|
||||
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
|
||||
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
|
||||
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
|
||||
// shape — every field landed at the wrong tag, so the four-field
|
||||
// truthiness check below filtered out every real c2c file push as
|
||||
// "incomplete metadata". After consolidating FileExtra to wrap
|
||||
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
|
||||
// this reads the right tags.
|
||||
const extra = protobuf_decode<FileExtra>(msgContent);
|
||||
if (!extra?.file) return;
|
||||
const f = extra.file;
|
||||
if (!f.fileUuid) return;
|
||||
elements.push({
|
||||
type: 'file',
|
||||
fileId: f.fileUuid,
|
||||
fileName: f.fileName ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
fileHash: f.fileHash ?? '',
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { formatEvent } from './format';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { IdentityService } from './identity-service';
|
||||
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
|
||||
// Notice kinds that get logged as a warning (operationally important
|
||||
// state changes that an operator probably wants to see at default
|
||||
// info level). Everything else falls through to info.
|
||||
const WARN_EVENT_KINDS = new Set([
|
||||
'group_recall',
|
||||
'friend_recall',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
]);
|
||||
|
||||
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
|
||||
|
||||
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
|
||||
|
||||
export interface PacketPipelineDeps {
|
||||
identity: IdentityService;
|
||||
events: BridgeEventBus;
|
||||
/**
|
||||
* Refresh group + member roster as a side-effect. Resolves with
|
||||
* whether any refresh actually ran (false when the group is unknown
|
||||
* and `refreshGroupList` was false).
|
||||
*/
|
||||
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
|
||||
}
|
||||
|
||||
export class IncomingPacketPipeline {
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
private readonly log: Logger;
|
||||
private readonly eventLog: Logger;
|
||||
|
||||
constructor(private readonly deps: PacketPipelineDeps) {
|
||||
// Tag every line we emit with this Bridge's UIN so per-account file
|
||||
// routing works. Unparseable uin (shouldn't happen) falls back to
|
||||
// the module-level logger so we still log, just without the slot.
|
||||
const uinNum = Number.parseInt(deps.identity.uin, 10);
|
||||
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
|
||||
this.log = bind ? moduleLog.child(bind) : moduleLog;
|
||||
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||
arr.push(parser);
|
||||
this.cmdHandlers_.set(cmd, arr);
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.cmdHandlers_.has(cmd);
|
||||
}
|
||||
|
||||
process(pkt: PacketInfo): void {
|
||||
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
|
||||
if (!handlers) return;
|
||||
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
const events = handler(pkt, this.deps.identity);
|
||||
for (const event of events) {
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
|
||||
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
} else {
|
||||
this.handleSideEffects(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private emit(event: QQEventVariant): void {
|
||||
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
|
||||
// own onError hook so one bad listener never blocks the others.
|
||||
void this.deps.events.emit(event);
|
||||
}
|
||||
|
||||
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
|
||||
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
|
||||
}
|
||||
|
||||
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
|
||||
let refreshed = false;
|
||||
try {
|
||||
refreshed = await this.prepareGroupMemberJoinIdentity(event);
|
||||
} catch (e) {
|
||||
this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
this.handleSideEffects(event, refreshed);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
|
||||
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
|
||||
|
||||
const refreshed = await this.deps.refreshMemberCache(
|
||||
event.groupId,
|
||||
!this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
|
||||
true,
|
||||
);
|
||||
this.resolveMemberIdentityFromCache(event);
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
|
||||
if (event.groupId <= 0) return;
|
||||
if (event.userUin <= 0 && event.userUid) {
|
||||
const uin = this.deps.identity.findUinByUid(event.userUid, event.groupId);
|
||||
if (uin !== null) event.userUin = uin;
|
||||
}
|
||||
if (event.operatorUin <= 0 && event.operatorUid) {
|
||||
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
|
||||
if (uin !== null) event.operatorUin = uin;
|
||||
}
|
||||
}
|
||||
|
||||
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
|
||||
const selfUin = Number(this.deps.identity.uin);
|
||||
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
|
||||
}
|
||||
|
||||
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
|
||||
this.rememberEventIdentity(event);
|
||||
if (alreadyRefreshed) return;
|
||||
|
||||
let groupId = 0;
|
||||
let reason = '';
|
||||
let refreshGroupList = false;
|
||||
switch (event.kind) {
|
||||
case 'group_member_join':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_join';
|
||||
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_leave';
|
||||
break;
|
||||
case 'group_admin':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_admin';
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
if (groupId <= 0) return;
|
||||
if (this.memberRefreshTasks_.has(groupId)) return;
|
||||
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
|
||||
refreshGroupList = true;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
|
||||
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
} catch (e) {
|
||||
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
this.memberRefreshTasks_.delete(groupId);
|
||||
}
|
||||
})();
|
||||
|
||||
this.memberRefreshTasks_.set(groupId, task);
|
||||
}
|
||||
|
||||
private rememberEventIdentity(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_member_join':
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.userUid,
|
||||
uin: event.userUin,
|
||||
});
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.operatorUid,
|
||||
uin: event.operatorUin,
|
||||
});
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
this.deps.identity.markGroupMemberInactive(event.groupId, {
|
||||
uid: event.userUid,
|
||||
uin: event.userUin,
|
||||
});
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uid: event.operatorUid,
|
||||
uin: event.operatorUin,
|
||||
});
|
||||
break;
|
||||
case 'group_admin':
|
||||
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
|
||||
uin: event.userUin,
|
||||
});
|
||||
break;
|
||||
case 'friend_request':
|
||||
this.deps.identity.rememberRequestIdentity({
|
||||
uid: event.fromUid,
|
||||
uin: event.fromUin,
|
||||
source: 'friend_request',
|
||||
});
|
||||
break;
|
||||
case 'group_invite':
|
||||
this.deps.identity.rememberRequestIdentity({
|
||||
groupId: event.groupId,
|
||||
uid: event.fromUid,
|
||||
uin: event.fromUin,
|
||||
source: 'group_request',
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void {
|
||||
// Message-class events (group/friend/temp message) get rendered by the
|
||||
// OneBot layer's logReceivedMessage — its output already includes the
|
||||
// assigned message ID, which the raw packet doesn't have. Returning
|
||||
// null here is the formatter's signal to skip.
|
||||
const message = formatEvent(identity, event);
|
||||
if (!message) return;
|
||||
if (WARN_EVENT_KINDS.has(event.kind)) {
|
||||
log.warn('%s', message);
|
||||
} else {
|
||||
log.info('%s', message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
export interface UserProfileInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
qid: string;
|
||||
sex: string;
|
||||
age: number;
|
||||
sign: string;
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
export interface FriendInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface GroupMemberInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string; // 'owner' | 'admin' | 'member'
|
||||
level: number;
|
||||
title: string;
|
||||
joinTime: number;
|
||||
lastSentTime: number;
|
||||
shutUpTime: number;
|
||||
}
|
||||
|
||||
export interface QQGroupInfo {
|
||||
groupId: number;
|
||||
groupName: string;
|
||||
remark: string;
|
||||
memberCount: number;
|
||||
memberMax: number;
|
||||
members: Map<number, GroupMemberInfo>;
|
||||
}
|
||||
|
||||
export interface GroupRequestInfo {
|
||||
groupId: number;
|
||||
groupName: string;
|
||||
targetUid: string;
|
||||
targetUin: number;
|
||||
targetName: string;
|
||||
invitorUid: string;
|
||||
invitorUin: number;
|
||||
invitorName: string;
|
||||
operatorUid: string;
|
||||
operatorUin: number;
|
||||
operatorName: string;
|
||||
sequence: number;
|
||||
state: number;
|
||||
eventType: number;
|
||||
comment: string;
|
||||
filtered: boolean;
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createHash } from 'crypto';
|
||||
import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
|
||||
import { basename, join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
// 群相册信息
|
||||
export interface GroupAlbumInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
picNum: number;
|
||||
createTime: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 获取群相册列表返回
|
||||
export interface GroupAlbumListRet {
|
||||
album: GroupAlbumInfo[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 相册媒体信息
|
||||
export interface AlbumMediaInfo {
|
||||
photoId: string;
|
||||
url: string;
|
||||
uploadTime: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取群相册列表
|
||||
*/
|
||||
export async function getGroupAlbumList(
|
||||
cookieObject: Record<string, string>,
|
||||
groupId: string,
|
||||
uin: string
|
||||
): Promise<GroupAlbumListRet | undefined> {
|
||||
if (!cookieObject || typeof cookieObject !== 'object') {
|
||||
throw new Error('cookieObject is required');
|
||||
}
|
||||
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?${new URLSearchParams({
|
||||
random: '7570',
|
||||
g_tk: bkn,
|
||||
format: 'json',
|
||||
inCharset: 'utf-8',
|
||||
outCharset: 'utf-8',
|
||||
qua: 'V1_IPH_SQ_6.2.0_0_HDBM_T',
|
||||
cmd: 'qunGetAlbumList',
|
||||
qunId: groupId,
|
||||
qunid: groupId,
|
||||
start: '0',
|
||||
num: '1000',
|
||||
uin,
|
||||
getMemberRole: '0',
|
||||
}).toString()}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<{ data: GroupAlbumListRet }>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
|
||||
if (!ret || typeof ret !== 'object') {
|
||||
throw new Error('invalid response from qzone api');
|
||||
}
|
||||
|
||||
return ret.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建群相册上传会话
|
||||
*/
|
||||
async function createAlbumUploadSession(
|
||||
groupId: string,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
imgMd5: string,
|
||||
uin: string
|
||||
): Promise<string> {
|
||||
const imgSize = statSync(filePath).size;
|
||||
const imgName = basename(filePath);
|
||||
const bkn = getBknFromCookie({ skey });
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
|
||||
const body = {
|
||||
control_req: [{
|
||||
uin,
|
||||
token: { type: 4, data: pskey, appid: 5 },
|
||||
appid: 'qun',
|
||||
checksum: imgMd5,
|
||||
check_type: 0,
|
||||
file_len: imgSize,
|
||||
env: { refer: 'qzone', deviceInfo: 'h5' },
|
||||
model: 0,
|
||||
biz_req: {
|
||||
sPicTitle: imgName,
|
||||
sPicDesc: '',
|
||||
sAlbumName: albumName,
|
||||
sAlbumID: albumId,
|
||||
iAlbumTypeID: 0,
|
||||
iBitmap: 0,
|
||||
iUploadType: 0,
|
||||
iUpPicType: 0,
|
||||
iBatchID: timestamp,
|
||||
sPicPath: '',
|
||||
iPicWidth: 0,
|
||||
iPicHight: 0,
|
||||
iWaterType: 0,
|
||||
iDistinctUse: 0,
|
||||
iNeedFeeds: 1,
|
||||
iUploadTime: timestamp,
|
||||
mapExt: { appid: 'qun', userid: groupId },
|
||||
stExtendInfo: { mapParams: { photo_num: '1', video_num: '0', batch_num: '1' } },
|
||||
},
|
||||
session: '',
|
||||
asy_upload: 0,
|
||||
cmd: 'FileUpload',
|
||||
}],
|
||||
};
|
||||
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`;
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
|
||||
const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>(
|
||||
api,
|
||||
'POST',
|
||||
body,
|
||||
{ Cookie: cookie, 'Content-Type': 'application/json' }
|
||||
);
|
||||
|
||||
if (response.ret !== 0 || !response.data?.session) {
|
||||
throw new Error(`创建上传会话失败: ${response.msg}`);
|
||||
}
|
||||
|
||||
return response.data.session;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 修复后的上传图片分片方法
|
||||
*/
|
||||
async function uploadAlbumSlice(
|
||||
session: string,
|
||||
filePath: string,
|
||||
// 移除 offset 和 chunkSize 参数,改为在内部控制
|
||||
imgMd5: string,
|
||||
skey: string,
|
||||
pskey: string,
|
||||
uin: string
|
||||
): Promise<void> {
|
||||
const img_size = statSync(filePath).size;
|
||||
const slice_size = 16384; // 严格使用 16KB
|
||||
const bkn = getBknFromCookie({ skey });
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
|
||||
const stream = createReadStream(filePath, { highWaterMark: slice_size });
|
||||
let seq = 0;
|
||||
let offset = 0;
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const end = Math.min(offset + chunk.length, img_size);
|
||||
|
||||
// 使用原生的 FormData 构建安全的 multipart 请求
|
||||
const form = new FormData();
|
||||
form.append('uin', uin);
|
||||
form.append('appid', 'qun');
|
||||
form.append('session', session);
|
||||
form.append('offset', offset.toString());
|
||||
form.append('data', new Blob([chunk as Buffer], { type: 'application/octet-stream' }), 'blob');
|
||||
form.append('checksum', '');
|
||||
form.append('check_type', '0');
|
||||
form.append('retry', '0');
|
||||
form.append('seq', seq.toString());
|
||||
form.append('end', end.toString());
|
||||
form.append('cmd', 'FileUpload');
|
||||
form.append('slice_size', slice_size.toString());
|
||||
form.append('biz_req.iUploadType', '0');
|
||||
|
||||
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${bkn}`;
|
||||
|
||||
// 放弃使用 HttpGetJson,改用原生 fetch,它能完美处理 FormData 和边界
|
||||
const response = await fetch(api, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Cookie: cookie,
|
||||
// 注意:不要手动设置 Content-Type,fetch 会自动加上带有正确 boundary 的 multipart/form-data
|
||||
},
|
||||
body: form,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const post = await response.json() as { ret: number, msg: string };
|
||||
if (post.ret !== 0) {
|
||||
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
|
||||
}
|
||||
|
||||
offset += chunk.length;
|
||||
seq++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片到群相册
|
||||
*/
|
||||
export async function uploadImageToGroupAlbum(
|
||||
cookieObject: Record<string, string>,
|
||||
groupId: string,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
uin: string
|
||||
): Promise<void> {
|
||||
const { loadBinarySource } = await import('../highway/utils');
|
||||
const loaded = await loadBinarySource(filePath, 'album image');
|
||||
|
||||
let tempFile: string | null = null;
|
||||
let actualPath = filePath;
|
||||
|
||||
if (/^(https?:\/\/|base64:\/\/)/i.test(filePath)) {
|
||||
tempFile = join(tmpdir(), `album_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`);
|
||||
writeFileSync(tempFile, loaded.bytes);
|
||||
actualPath = tempFile;
|
||||
}
|
||||
|
||||
try {
|
||||
const imgMd5 = createHash('md5').update(loaded.bytes).digest('hex');
|
||||
// const imgSize = loaded.bytes.length;
|
||||
const skey = cookieObject.skey || '';
|
||||
const pskey = cookieObject.p_skey || '';
|
||||
|
||||
const session = await createAlbumUploadSession(groupId, albumId, albumName, actualPath, skey, pskey, imgMd5, uin);
|
||||
|
||||
await uploadAlbumSlice(session, actualPath, imgMd5, skey, pskey, uin);
|
||||
|
||||
} finally {
|
||||
if (tempFile) {
|
||||
try { unlinkSync(tempFile); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createLogger } from '@snowluma/common/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;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import { createLogger } from '@snowluma/common/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 [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import https from 'node:https';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
em?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface UploadImageRetSuccess {
|
||||
ec?: number;
|
||||
id?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeFeed {
|
||||
fid: string;
|
||||
u: number;
|
||||
pubt: number;
|
||||
msg: {
|
||||
text: string;
|
||||
pics?: Array<{ id: string; w: number; h: number }>;
|
||||
};
|
||||
settings: any;
|
||||
read_num: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeRet {
|
||||
ec: number;
|
||||
em?: string;
|
||||
feeds?: Record<string, WebApiGroupNoticeFeed>;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export function calculateBkn(key: string): string {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
const code = key.charCodeAt(i);
|
||||
hash = hash + (hash << 5) + code;
|
||||
}
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送群公告 Web API
|
||||
*/
|
||||
export async function setGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
content: string,
|
||||
pinned: number = 0,
|
||||
type: number = 1,
|
||||
isShowEditCard: number = 1,
|
||||
tipWindowType: number = 1,
|
||||
confirmRequired: number = 1,
|
||||
picId: string = '',
|
||||
imgWidth: number = 540,
|
||||
imgHeight: number = 300
|
||||
): Promise<SetNoticeRetSuccess | undefined> {
|
||||
try {
|
||||
// 分别获取 skey 和 p_skey
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey);
|
||||
const urlBkn = calculateBkn(pskey);
|
||||
//
|
||||
// console.log(skey)
|
||||
// console.log(pskey)
|
||||
//
|
||||
// console.log(urlBkn);
|
||||
// console.log(bodyBkn)
|
||||
|
||||
const settings = JSON.stringify({
|
||||
is_show_edit_card: isShowEditCard,
|
||||
tip_window_type: tipWindowType,
|
||||
confirm_required: confirmRequired,
|
||||
});
|
||||
|
||||
const bodyParams: Record<string, string> = {
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn,
|
||||
text: content,
|
||||
pinned: pinned.toString(),
|
||||
type: type.toString(),
|
||||
settings,
|
||||
};
|
||||
|
||||
if (picId !== '') {
|
||||
bodyParams.pic = picId;
|
||||
bodyParams.imgWidth = imgWidth.toString();
|
||||
bodyParams.imgHeight = imgHeight.toString();
|
||||
}
|
||||
|
||||
// 注意这里:URL 必须使用 skey 算出来的 bkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
|
||||
const body = new URLSearchParams(bodyParams).toString();
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
body,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取群公告列表 Web API
|
||||
*/
|
||||
export async function getGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
start: number = -1, // -1 表示第一页
|
||||
count: number = 20 // 抓包中是 10,你可以根据需要调整
|
||||
): Promise<WebApiGroupNoticeRet | undefined> {
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
|
||||
|
||||
const bodyParams = new URLSearchParams({
|
||||
qid: groupCode,
|
||||
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
|
||||
ft: '23',
|
||||
s: start.toString(), // 分页游标
|
||||
n: count.toString(), // 获取数量
|
||||
i: '1',
|
||||
ni: '1'
|
||||
}).toString();
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||
url,
|
||||
'POST',
|
||||
bodyParams,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 上传群公告图片 Web API
|
||||
*/
|
||||
export async function uploadGroupNoticeImage(
|
||||
cookieObject: Record<string, string>,
|
||||
imageBuffer: Buffer
|
||||
): Promise<{ id: string; width: number; height: number } | undefined> {
|
||||
try {
|
||||
const bkn = calculateBkn(cookieObject['skey']);
|
||||
const boundary = `-----------------------------${Date.now()}`;
|
||||
|
||||
const parts: Buffer[] = [];
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
|
||||
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
|
||||
parts.push(imageBuffer);
|
||||
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
|
||||
|
||||
const body = Buffer.concat(parts);
|
||||
|
||||
const options = {
|
||||
hostname: 'web.qun.qq.com',
|
||||
path: '/cgi-bin/announce/upload_img',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
||||
'Content-Length': body.length,
|
||||
'Cookie': cookieToString(cookieObject),
|
||||
},
|
||||
};
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const req = https.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const result = JSON.parse(data) as UploadImageRetSuccess;
|
||||
if (result.ec === 0 && result.id) {
|
||||
const unescapedIdStr = result.id.replace(/"/g, '"');
|
||||
|
||||
const idObj = JSON.parse(unescapedIdStr);
|
||||
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
|
||||
} else {
|
||||
resolve(undefined);
|
||||
}
|
||||
} catch {
|
||||
resolve(undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除群公告 Web API
|
||||
*/
|
||||
export async function deleteGroupNotice(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
fid: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || skey;
|
||||
|
||||
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
|
||||
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
|
||||
|
||||
const params = new URLSearchParams({
|
||||
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
|
||||
fid: fid,
|
||||
qid: groupCode,
|
||||
}).toString();
|
||||
|
||||
// 注意这里:URL 拼接 urlBkn
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST',
|
||||
params,
|
||||
{
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
true,
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import https from 'node:https';
|
||||
import http from 'node:http';
|
||||
|
||||
export class RequestUtil {
|
||||
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
|
||||
const client = url.startsWith('https') ? https : http;
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = client.get(url, (res) => {
|
||||
const cookies: { [key: string]: string; } = {};
|
||||
|
||||
res.on('data', () => { }); // 必须消耗流
|
||||
res.on('end', () => {
|
||||
this.handleRedirect(res, url, cookies)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
|
||||
if (res.headers['set-cookie']) {
|
||||
this.extractCookies(res.headers['set-cookie'], cookies);
|
||||
}
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
|
||||
if (res.statusCode === 301 || res.statusCode === 302) {
|
||||
if (res.headers.location) {
|
||||
const redirectUrl = new URL(res.headers.location, url);
|
||||
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
|
||||
return { ...cookies, ...redirectCookies };
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
|
||||
setCookieHeaders.forEach((cookie) => {
|
||||
const parts = cookie.split(';')[0]?.split('=');
|
||||
if (parts) {
|
||||
const key = parts[0];
|
||||
const value = parts[1];
|
||||
if (key && value && key.length > 0 && value.length > 0) {
|
||||
cookies[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
|
||||
[key: string]: string;
|
||||
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
|
||||
const option = new URL(url);
|
||||
const protocol = url.startsWith('https://') ? https : http;
|
||||
const options = {
|
||||
hostname: option.hostname,
|
||||
port: option.port,
|
||||
path: option.pathname + option.search,
|
||||
method,
|
||||
headers,
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(options, (res: http.IncomingMessage) => {
|
||||
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
|
||||
if (maxRedirects <= 0) {
|
||||
reject(new Error('Too many redirects'));
|
||||
return;
|
||||
}
|
||||
const redirectUrl = new URL(res.headers.location, url).href;
|
||||
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
let responseBody = '';
|
||||
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
|
||||
|
||||
res.on('end', () => {
|
||||
try {
|
||||
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
||||
if (isJsonRet) {
|
||||
resolve(JSON.parse(responseBody) as T);
|
||||
} else {
|
||||
resolve(responseBody as T);
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`Unexpected status code: ${res.statusCode}`));
|
||||
}
|
||||
} catch (parseError: any) {
|
||||
reject(new Error(parseError.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => reject(error));
|
||||
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
|
||||
req.write(isArgJson ? JSON.stringify(data) : data);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
|
||||
return this.HttpGetJson<string>(url, method, data, headers, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
export function cookieToString(cookieObject: Record<string, string>): string {
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
|
||||
export function getBknFromCookie(cookieObject: Record<string, string>): string {
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return (hash & 2147483647).toString();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Vitest config — only used by `pnpm bench` to drive the perf
|
||||
// micro-benchmarks under `bench/`. There are no `*.test.ts` files in
|
||||
// this package (bridge tests live in @snowluma/core's test suite by
|
||||
// historical accident); if/when they migrate over, point
|
||||
// `test.include` at them here.
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
// proton's vite plugin inlines `protobuf_encode<T>` / `protobuf_decode<T>`
|
||||
// call sites at build time. Required for tinybench-driven benches to
|
||||
// hit the production code path rather than proton's runtime-fallback
|
||||
// (which throws unless a runtime-map JSON is loaded).
|
||||
plugins: [protobufVitePlugin()],
|
||||
test: {
|
||||
benchmark: {
|
||||
include: ['bench/**/*.bench.ts'],
|
||||
},
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.1",
|
||||
"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/bridge, @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:"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
const HEX_CHARS = '0123456789abcdef';
|
||||
const HEX_CHARS_UPPER = '0123456789ABCDEF';
|
||||
|
||||
export function toHex(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
@@ -9,6 +10,15 @@ export function toHex(data: Uint8Array | Buffer): string {
|
||||
return h;
|
||||
}
|
||||
|
||||
export function toHexUpper(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
@@ -0,0 +1,16 @@
|
||||
// Plain JSON value types — defined here (not in @snowluma/onebot/types
|
||||
// where they used to live) so @snowluma/bridge can talk about JSON-shaped
|
||||
// payloads without importing OneBot. The OneBot types module keeps the
|
||||
// names exported via re-export, so existing call sites that say
|
||||
// `import type { JsonValue } from '<…>/onebot/types'` continue to work
|
||||
// unchanged after Phase 3.
|
||||
//
|
||||
// Anything actually OneBot-specific (ApiResponse, OneBotRequest, …)
|
||||
// stays in @snowluma/onebot — only the plain JSON quartet moves here.
|
||||
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
export type JsonArray = JsonValue[];
|
||||
@@ -0,0 +1,274 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const DEFAULT_DIR = 'logs';
|
||||
const DEFAULT_MAX_MB = 50;
|
||||
const DEFAULT_RETAIN_DAYS = 7;
|
||||
const FILE_PREFIX = 'snowluma-';
|
||||
const FILE_SUFFIX = '.log';
|
||||
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
|
||||
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
||||
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
|
||||
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
|
||||
|
||||
function parsePositiveInt(v: string | undefined, dflt: number): number {
|
||||
if (!v) return dflt;
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : dflt;
|
||||
}
|
||||
|
||||
function todayString(d: Date = new Date()): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function dateOf(s: string): Date {
|
||||
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
|
||||
return new Date(y!, m! - 1, d!);
|
||||
}
|
||||
|
||||
function stripAnsi(line: string): string {
|
||||
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
|
||||
}
|
||||
|
||||
interface OpenFile {
|
||||
stream: fs.WriteStream;
|
||||
bytes: number;
|
||||
date: string;
|
||||
splitIndex: number;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one output directory: keeps at most one open WriteStream, handles
|
||||
* daily rollover, per-file size cap, and retention cleanup. The shared
|
||||
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
|
||||
*/
|
||||
class FileWriter {
|
||||
private disabled = false;
|
||||
private file: OpenFile | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
private readonly maxBytes: number,
|
||||
private readonly retainDays: number,
|
||||
) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
console.error(
|
||||
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
get isDisabled(): boolean {
|
||||
return this.disabled;
|
||||
}
|
||||
|
||||
get currentPath(): string | null {
|
||||
return this.file?.path ?? null;
|
||||
}
|
||||
|
||||
write(data: string, bytes: number): void {
|
||||
if (this.disabled) return;
|
||||
const today = todayString();
|
||||
this.ensureForToday(today);
|
||||
if (!this.file) return;
|
||||
|
||||
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
|
||||
this.rotateBySize();
|
||||
if (!this.file) return;
|
||||
}
|
||||
|
||||
this.file.stream.write(data);
|
||||
this.file.bytes += bytes;
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
const f = this.file;
|
||||
this.file = null;
|
||||
if (!f) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
f.stream.end(() => resolve());
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureForToday(today: string): void {
|
||||
if (this.file && this.file.date === today) return;
|
||||
|
||||
if (this.file) {
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
this.file = null;
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
// Resume from the highest existing split index for today (so two
|
||||
// process starts on the same day share files / don't clobber).
|
||||
let idx = 0;
|
||||
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
|
||||
this.file = this.openFile(today, idx);
|
||||
}
|
||||
|
||||
private rotateBySize(): void {
|
||||
if (!this.file) return;
|
||||
const date = this.file.date;
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
let next = this.file.splitIndex + 1;
|
||||
while (fs.existsSync(this.pathFor(date, next))) next++;
|
||||
this.file = this.openFile(date, next);
|
||||
}
|
||||
|
||||
private openFile(date: string, splitIndex: number): OpenFile | null {
|
||||
const p = this.pathFor(date, splitIndex);
|
||||
try {
|
||||
let bytes = 0;
|
||||
try {
|
||||
bytes = fs.statSync(p).size;
|
||||
} catch {
|
||||
/* file doesn't exist yet */
|
||||
}
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
console.error(`[logger] file write error on ${p}: ${err.message}`);
|
||||
});
|
||||
return { stream, bytes, date, splitIndex, path: p };
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private pathFor(date: string, splitIndex: number): string {
|
||||
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
|
||||
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(this.dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
|
||||
const cutoff = Date.now() - retainMs;
|
||||
for (const name of entries) {
|
||||
const m = FILE_RE.exec(name);
|
||||
if (!m) continue;
|
||||
const dateStr = m[1]!;
|
||||
if (dateOf(dateStr).getTime() < cutoff) {
|
||||
try {
|
||||
fs.unlinkSync(path.join(this.dir, name));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class FileTransport {
|
||||
private readonly dir: string;
|
||||
private readonly maxBytes: number;
|
||||
private readonly retainDays: number;
|
||||
private readonly enabled: boolean;
|
||||
private readonly perUinEnabled: boolean;
|
||||
private shared: FileWriter | null = null;
|
||||
private perUin = new Map<number, FileWriter>();
|
||||
|
||||
constructor() {
|
||||
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
|
||||
this.maxBytes =
|
||||
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
|
||||
this.retainDays = parsePositiveInt(
|
||||
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
DEFAULT_RETAIN_DAYS,
|
||||
);
|
||||
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
|
||||
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
|
||||
|
||||
if (this.enabled) {
|
||||
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
|
||||
this.shared = w.isDisabled ? null : w;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when no file output will happen (env disable or init failure). */
|
||||
get isDisabled(): boolean {
|
||||
return !this.shared;
|
||||
}
|
||||
|
||||
/** Current shared-file path (or null if disabled / not yet opened). */
|
||||
get currentPath(): string | null {
|
||||
return this.shared?.currentPath ?? null;
|
||||
}
|
||||
|
||||
/** Path of the per-UIN file for the given UIN, if open. */
|
||||
perUinPath(uin: number): string | null {
|
||||
return this.perUin.get(uin)?.currentPath ?? null;
|
||||
}
|
||||
|
||||
write(line: string, uin?: number): void {
|
||||
if (!this.shared) return;
|
||||
const data = stripAnsi(line) + '\n';
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
|
||||
this.shared.write(data, bytes);
|
||||
|
||||
if (uin !== undefined && this.perUinEnabled) {
|
||||
let w = this.perUin.get(uin);
|
||||
if (!w) {
|
||||
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
|
||||
if (w.isDisabled) return;
|
||||
this.perUin.set(uin, w);
|
||||
}
|
||||
w.write(data, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const closes: Promise<void>[] = [];
|
||||
if (this.shared) closes.push(this.shared.close());
|
||||
for (const w of this.perUin.values()) closes.push(w.close());
|
||||
this.shared = null;
|
||||
this.perUin.clear();
|
||||
await Promise.all(closes);
|
||||
}
|
||||
}
|
||||
|
||||
let singleton: FileTransport | null = null;
|
||||
|
||||
export function getFileTransport(): FileTransport {
|
||||
if (!singleton) singleton = new FileTransport();
|
||||
return singleton;
|
||||
}
|
||||
|
||||
/** Reset state between tests. Closes all active file handles. */
|
||||
export async function _resetFileTransportForTesting(): Promise<void> {
|
||||
if (singleton) await singleton.close();
|
||||
singleton = null;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
|
||||
function valueRepr(v: unknown): string {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a params object as a single line for logging. Skips deep
|
||||
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
|
||||
* Strings are quoted; long ones are truncated with an ellipsis.
|
||||
*
|
||||
* Output is capped at MAX_TOTAL chars; on overflow the tail is
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v)}`;
|
||||
// +1 accounts for the separating space we'd insert when joining.
|
||||
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
|
||||
out.push('...');
|
||||
break;
|
||||
}
|
||||
out.push(entry);
|
||||
total += entry.length + (out.length > 1 ? 1 : 0);
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
};
|
||||
|
||||
const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
}
|
||||
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
|
||||
// Only governs console + ring buffer + subscribers; the file
|
||||
// transport always sees debug-and-up regardless.
|
||||
let currentLevel: LogLevel = resolveMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the console / subscriber level at runtime. Invalid input is
|
||||
* a no-op (returns false). File transport is unaffected — it always
|
||||
* sees every level so post-mortems remain useful.
|
||||
*/
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
if (process.env.NO_COLOR === '1') return false;
|
||||
return Boolean(process.stdout.isTTY);
|
||||
}
|
||||
|
||||
function ansi(code: number, text: string): string {
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
}
|
||||
|
||||
function currentTime(): string {
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
}
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
message,
|
||||
line,
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush and close the underlying log file. Call from shutdown hooks
|
||||
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
|
||||
* buffer makes it to disk. Returns a promise that resolves once the OS
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* 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;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
File renamed without changes.
@@ -8,3 +8,4 @@ export interface PacketInfo {
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
@@ -0,0 +1,113 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
if (n > 0 && n <= 65535) return n;
|
||||
return fallback;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
if (port > 0 && port <= 65535) return port;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -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": "0.1.0",
|
||||
"version": "1.9.1",
|
||||
"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"
|
||||
},
|
||||
"./bridge": {
|
||||
"types": "./src/bridge/bridge.ts",
|
||||
"default": "./src/bridge/bridge.ts"
|
||||
},
|
||||
"./bridge-interface": {
|
||||
"types": "./src/bridge/bridge-interface.ts",
|
||||
"default": "./src/bridge/bridge-interface.ts"
|
||||
},
|
||||
"./bridge-context": {
|
||||
"types": "./src/bridge/bridge-context.ts",
|
||||
"default": "./src/bridge/bridge-context.ts"
|
||||
},
|
||||
"./manager": {
|
||||
"types": "./src/bridge/manager.ts",
|
||||
"default": "./src/bridge/manager.ts"
|
||||
},
|
||||
"./apis": {
|
||||
"types": "./src/bridge/apis/index.ts",
|
||||
"default": "./src/bridge/apis/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"build:all": "cross-env BUILD_WEBUI=true vite build",
|
||||
@@ -14,6 +40,12 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/bridge": "workspace:*",
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -21,7 +53,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:",
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
// ContactsApi — friend / group / member roster + user-profile +
|
||||
// group-request-list + download-rkey OIDB calls.
|
||||
//
|
||||
// All implementations inlined from the previous `bridge-contacts.ts`
|
||||
// (which gets removed alongside the rest of the actions/* facade
|
||||
// shim in commit 13). The single non-trivial piece carried over is
|
||||
// the per-group inflight + TTL cache for `fetchGroupMemberList`:
|
||||
// without it a busy OneBot client (e.g. MaiBot calling
|
||||
// `get_group_member_info` once per inbound message) would trigger
|
||||
// one OIDB 0xfe7_3 per chat message, sustained >1k/h, which trips
|
||||
// Tencent risk-control and gets the account banned for 7 days.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbSvcTrpcTcp0x10C0Response,
|
||||
OidbSvcTrpcTcp0xFD4_1Response,
|
||||
OidbSvcTrpcTcp0xFE5_2Response,
|
||||
OidbSvcTrpcTcp0xFE7_3Response,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
AvatarInfo,
|
||||
OidbFriendListRequest,
|
||||
OidbGroupListRequest,
|
||||
OidbGroupMemberListRequest,
|
||||
OidbGroupRequestList,
|
||||
OidbUserInfoRequest,
|
||||
OidbUserInfoResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
NTV2RichMediaReq,
|
||||
NTV2RichMediaResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/bridge/qq-info';
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
// `runOidb` and the proto-defs helpers take `Bridge` (deep dependency
|
||||
// inside the highway / sendRawPacket plumbing). At runtime `ctx` IS
|
||||
// the Bridge that constructed this Api, so narrowing back via
|
||||
// `ctx as Bridge` is safe — see the same pattern in `MessageApi`
|
||||
// where buildSendElems also expects a Bridge.
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
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 (so the
|
||||
* cache resets per account, as you'd expect for multi-account
|
||||
* runtimes — `BridgeManager` builds one Bridge per uin and each
|
||||
* gets its own ContactsApi).
|
||||
*/
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
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 env = makeOidbEnvelope<OidbFriendListRequest>(0xFD4, 1, body);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode<OidbBase<OidbFriendListRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>(respBytes).body;
|
||||
|
||||
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);
|
||||
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
// The config flags ask QQ which per-group fields to include in
|
||||
// the response. Asking for everything looks innocent on small
|
||||
// accounts but on ~200+ groups it makes the QQ NT process write
|
||||
// a payload large enough to blow the named-pipe write buffer —
|
||||
// we then read EPIPE and the whole session dies. See issue #42.
|
||||
// Keep `config1.*` mostly on but turn off the costly groups of
|
||||
// bools that never map back to a decoded field.
|
||||
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: false, field5003: false,
|
||||
},
|
||||
config2: {
|
||||
field1: false, field2: false, field3: false, field4: false,
|
||||
field5: false, field6: false, field7: false, field8: false,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
};
|
||||
const env = makeOidbEnvelope<OidbGroupListRequest>(0xFE5, 2, body, true);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode<OidbBase<OidbGroupListRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(respBytes).body;
|
||||
|
||||
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(),
|
||||
});
|
||||
}
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
async fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
// Coalesce in-flight calls + serve a 60s-cached result. Without
|
||||
// this, a busy OneBot client gets the bot 7-day banned within
|
||||
// hours via Tencent risk-control.
|
||||
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 bridge = asBridge(this.ctx);
|
||||
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 env = makeOidbEnvelope<OidbGroupMemberListRequest>(0xFE7, 3, body);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode<OidbBase<OidbGroupMemberListRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(respBytes).body;
|
||||
|
||||
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);
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
|
||||
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
|
||||
// sending field 2 makes the server reject the request.
|
||||
const body = {
|
||||
uin,
|
||||
keys: keys.map(k => ({ key: k })),
|
||||
};
|
||||
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
|
||||
// name is historical, the wire semantic is "this is the UIN-form
|
||||
// variant of the call"). Without it newer QQ NT versions take the
|
||||
// UID-form validation path, find neither uid nor openid in the
|
||||
// body and bounce the request with
|
||||
// `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's
|
||||
// FetchStrangerByUin (Reserved = 1).
|
||||
const env = makeOidbEnvelope<OidbUserInfoRequest>(0xFE1, 2, body, true);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode<OidbBase<OidbUserInfoRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbUserInfoResponse>>(respBytes).body;
|
||||
|
||||
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 = protobuf_decode<AvatarInfo>(avatarBytes);
|
||||
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;
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const subCmd = filtered ? 2 : 1;
|
||||
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
|
||||
const env = makeOidbEnvelope<OidbGroupRequestList>(0x10C0, subCmd, { count: 20, field2: 0 });
|
||||
const respBytes = await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupRequestList>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(respBytes).body;
|
||||
|
||||
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 bridge = asBridge(this.ctx);
|
||||
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 env = makeOidbEnvelope<NTV2RichMediaReq>(0x9067, 202, body, true);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode<OidbBase<NTV2RichMediaReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<NTV2RichMediaResp>>(respBytes).body;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// ExtrasApi — Tier-2 napcat-parity surfaces that don't fit anywhere
|
||||
// else: group todo CRUD, stranger online/ext status decode, AI voice
|
||||
// list + synthesis. Inlined from `actions/extras.ts` (deleted alongside
|
||||
// actions/* in commit 13).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbGroupTodo,
|
||||
OidbStrangerStatusReq,
|
||||
OidbStrangerStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
OidbAiVoiceListReq,
|
||||
OidbAiVoiceListResp,
|
||||
OidbAiVoiceReq,
|
||||
OidbAiVoiceResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export interface StrangerStatus {
|
||||
status: number;
|
||||
ext_status: number;
|
||||
}
|
||||
|
||||
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 class ExtrasApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
|
||||
async setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 1, { groupUin: groupId, msgSeq });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
|
||||
}
|
||||
|
||||
async completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 2, { groupUin: groupId, msgSeq });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
|
||||
}
|
||||
|
||||
async cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 3, { groupUin: groupId, msgSeq });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
try {
|
||||
const env = makeOidbEnvelope<OidbStrangerStatusReq>(
|
||||
0xFE1, 2,
|
||||
{ uin, key: [{ key: 27372 }] } as any,
|
||||
// Same UIN-form flag fetchUserProfile sets — without it newer
|
||||
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
|
||||
true,
|
||||
);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode<OidbBase<OidbStrangerStatusReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbStrangerStatusResp>>(respBytes).body;
|
||||
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) ───────────────
|
||||
|
||||
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbAiVoiceListReq>(0x929D, 0, { groupUin: groupId, chatType });
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode<OidbBase<OidbAiVoiceListReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbAiVoiceListResp>>(respBytes).body;
|
||||
return (resp?.content as AiVoiceCategory[] | undefined) ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
// 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 env = makeOidbEnvelope<OidbAiVoiceReq>(
|
||||
0x929B, 0,
|
||||
{ groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
|
||||
);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode<OidbBase<OidbAiVoiceReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbAiVoiceResp>>(respBytes).body;
|
||||
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined;
|
||||
if (node) return node;
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
// ForwardApi — long-message (聊天记录 / forward) upload + retrieval.
|
||||
// Inlined from `actions/forward.ts` (deleted alongside actions/* in
|
||||
// commit 13).
|
||||
//
|
||||
// The module-scoped `forwardResCache` stays at file scope (not on the
|
||||
// class instance) because forward res_ids are globally unique, and an
|
||||
// outbound upload often gets queried back through `fetch` on a
|
||||
// different Bridge instance (e.g. a different OneBot connection
|
||||
// hitting the same account). Keeping the cache shared across the
|
||||
// process matches NapCat's behaviour.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { gunzipSync, gzipSync } from 'zlib';
|
||||
import type {
|
||||
LongMsgResult,
|
||||
RecvLongMsgReq,
|
||||
RecvLongMsgResp,
|
||||
SendLongMsgReq,
|
||||
SendLongMsgResp,
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { buildSendElems } from '@snowluma/bridge/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events';
|
||||
import { parseMsgPush } from '@snowluma/bridge/msg-push';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
// 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: Bridge,
|
||||
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: BridgeContext) {}
|
||||
|
||||
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 = asBridge(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`.
|
||||
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. The wire-side element builder
|
||||
// turns this into the same XML m_resid blob it already produced
|
||||
// for top-level forwards — see `makeForwardElem` in
|
||||
// element-builder.ts:153.
|
||||
const previewElement: MessageElement = {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
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: randomUUID(),
|
||||
innerActions: myInnerActions,
|
||||
};
|
||||
}
|
||||
|
||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||
const bridge = asBridge(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 action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
|
||||
const nodes: 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') {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// FriendApi — friend roster mutations (handle add request /
|
||||
// delete / set remark). Inlined from `actions/friend.ts` (deleted
|
||||
// alongside actions/* in commit 13). The READ side of friends
|
||||
// (fetchFriendList) lives on ContactsApi because friends/groups
|
||||
// share the same roster pipeline.
|
||||
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbDeleteFriend,
|
||||
OidbFriendRequestAction,
|
||||
OidbSetFriendRemark,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
* pre-resolved UID string or a numeric uin (then resolved on the fly).
|
||||
*/
|
||||
async handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
let targetUid = uidOrFlag;
|
||||
if (/^\d+$/.test(uidOrFlag)) {
|
||||
targetUid = await this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
const env = makeOidbEnvelope<OidbFriendRequestAction>(0xB5D, 44, { accept: approve ? 3 : 5, targetUid });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', protobuf_encode<OidbBase<OidbFriendRequestAction>>(env));
|
||||
}
|
||||
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
const env = makeOidbEnvelope<OidbDeleteFriend>(0x126B, 0, {
|
||||
field1: {
|
||||
targetUid,
|
||||
field2: {
|
||||
field1: 130,
|
||||
field2: 109,
|
||||
field3: {
|
||||
field1: 8,
|
||||
field2: 8,
|
||||
field3: 50,
|
||||
},
|
||||
},
|
||||
block,
|
||||
field4: false,
|
||||
},
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', protobuf_encode<OidbBase<OidbDeleteFriend>>(env));
|
||||
|
||||
// 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 */ }
|
||||
}
|
||||
|
||||
async setRemark(userId: number, remark: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uid = await this.ctx.resolveUserUid(userId);
|
||||
const env = makeOidbEnvelope<OidbSetFriendRemark>(0xB6E, 2, { targetUid: uid, remark });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', protobuf_encode<OidbBase<OidbSetFriendRemark>>(env));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// GroupAdminApi — mute/kick/admin/card/name/title/leave + join-policy
|
||||
// + add-request handling. Inlined from the previous
|
||||
// `actions/group-admin.ts` (deleted alongside the rest of the
|
||||
// actions/* facade in commit 13).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
Oidb0x89a_0AddOption,
|
||||
Oidb0x89a_0Search,
|
||||
Oidb0x8a0Req,
|
||||
Oidb0x8a7Req,
|
||||
Oidb0x8a7Resp,
|
||||
Oidb0xf16Req,
|
||||
OidbGroupRequestAction,
|
||||
OidbKickMember,
|
||||
OidbLeaveGroup,
|
||||
OidbMuteAll,
|
||||
OidbMuteMember,
|
||||
OidbRenameGroup,
|
||||
OidbRenameMember,
|
||||
OidbSetAdmin,
|
||||
OidbSpecialTitle,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uid = await this.ctx.resolveUserUid(userId, groupId);
|
||||
const env = makeOidbEnvelope<OidbMuteMember>(0x1253, 1, {
|
||||
groupUin: groupId, type: 1, body: { targetUid: uid, duration },
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', protobuf_encode<OidbBase<OidbMuteMember>>(env));
|
||||
}
|
||||
|
||||
async muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbMuteAll>(0x89A, 0, {
|
||||
groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 },
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode<OidbBase<OidbMuteAll>>(env));
|
||||
}
|
||||
|
||||
async setAddOption(groupId: number, addType: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<Oidb0x89a_0AddOption>(0x89A, 0, {
|
||||
groupUin: BigInt(groupId), settings: { addType }, field12: 0,
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode<OidbBase<Oidb0x89a_0AddOption>>(env));
|
||||
}
|
||||
|
||||
async setSearch(groupId: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<Oidb0x89a_0Search>(0x89A, 0, {
|
||||
groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0,
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode<OidbBase<Oidb0x89a_0Search>>(env));
|
||||
}
|
||||
|
||||
async setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const subCmd = filtered ? 2 : 1;
|
||||
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
|
||||
const env = makeOidbEnvelope<OidbGroupRequestAction>(
|
||||
0x10C8, subCmd,
|
||||
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
|
||||
true,
|
||||
);
|
||||
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupRequestAction>>(env));
|
||||
}
|
||||
|
||||
async kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uid = await this.ctx.resolveUserUid(userId, groupId);
|
||||
const env = makeOidbEnvelope<OidbKickMember>(0x8A0, 1, {
|
||||
groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason,
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode<OidbBase<OidbKickMember>>(env));
|
||||
}
|
||||
|
||||
async kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const targetUids = await Promise.all(userIds.map(userId => this.ctx.resolveUserUid(userId, groupId)));
|
||||
const env = makeOidbEnvelope<Oidb0x8a0Req>(0x8A0, 1, {
|
||||
groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0,
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode<OidbBase<Oidb0x8a0Req>>(env));
|
||||
}
|
||||
|
||||
async leave(groupId: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbLeaveGroup>(0x1097, 1, { groupUin: groupId });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', protobuf_encode<OidbBase<OidbLeaveGroup>>(env));
|
||||
}
|
||||
|
||||
async setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uid = await this.ctx.resolveUserUid(userId, groupId);
|
||||
const env = makeOidbEnvelope<OidbSetAdmin>(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', protobuf_encode<OidbBase<OidbSetAdmin>>(env));
|
||||
}
|
||||
|
||||
async setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uid = await this.ctx.resolveUserUid(userId, groupId);
|
||||
const env = makeOidbEnvelope<OidbRenameMember>(0x8FC, 3, {
|
||||
groupUin: groupId, body: { targetUid: uid, targetName: card },
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', protobuf_encode<OidbBase<OidbRenameMember>>(env));
|
||||
}
|
||||
|
||||
async setName(groupId: number, name: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbRenameGroup>(0x89A, 15, { groupUin: groupId, body: { targetName: name } });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', protobuf_encode<OidbBase<OidbRenameGroup>>(env));
|
||||
}
|
||||
|
||||
async setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uid = await this.ctx.resolveUserUid(userId, groupId);
|
||||
const env = makeOidbEnvelope<OidbSpecialTitle>(0x8FC, 2, {
|
||||
groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 },
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', protobuf_encode<OidbBase<OidbSpecialTitle>>(env));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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".
|
||||
*/
|
||||
async setRemark(groupId: number, remark: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<Oidb0xf16Req>(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', protobuf_encode<OidbBase<Oidb0xf16Req>>(env));
|
||||
}
|
||||
|
||||
async getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req = {
|
||||
basic1: 1,
|
||||
basic2: 2,
|
||||
basic3: 1,
|
||||
uin: BigInt(this.ctx.identity.uin),
|
||||
groupId: BigInt(groupId),
|
||||
type: 0,
|
||||
};
|
||||
const env = makeOidbEnvelope<Oidb0x8a7Req>(0x8A7, 0, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', protobuf_encode<OidbBase<Oidb0x8a7Req>>(env));
|
||||
const result = protobuf_decode<OidbBase<Oidb0x8a7Resp>>(respBytes).body;
|
||||
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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
// GroupAlbumApi — group photo album operations (list/upload/comment/
|
||||
// like/delete + media listing). Inlined from `actions/group-album.ts`
|
||||
// and `web-actions/group-album.ts` (both deleted alongside actions/*
|
||||
// in commit 13). The pure-HTTP helpers in `web/group-album.ts` stay
|
||||
// where they are — they're transport-layer code, not Bridge actions.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
DeleteMediasRequest,
|
||||
DeleteMediasResponse,
|
||||
DoQunCommentRequest,
|
||||
DoQunCommentResponse,
|
||||
DoQunLikeRequest,
|
||||
DoQunLikeResponse,
|
||||
GetMediaListRequest,
|
||||
GetMediaListResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/bridge/web/group-album';
|
||||
// `getCookies` is part of WebApi — go through the hub so we don't
|
||||
// duplicate the cookie acquisition flow.
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export interface GroupAlbumMediaResult {
|
||||
mediaList: any[];
|
||||
nextAttachInfo: string;
|
||||
}
|
||||
|
||||
export interface GroupAlbumCommentResult {
|
||||
id: string;
|
||||
user: { uin: string };
|
||||
content: Array<{ type: number; content: string }>;
|
||||
time: string;
|
||||
clientKey: string;
|
||||
}
|
||||
|
||||
function convertBigIntToString(obj: any): any {
|
||||
if (obj === null || obj === undefined) return obj;
|
||||
if (typeof obj === 'bigint') return obj.toString();
|
||||
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
|
||||
if (typeof obj === 'object') {
|
||||
const result: any = {};
|
||||
for (const key in obj) {
|
||||
result[key] = convertBigIntToString(obj[key]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
export class GroupAlbumApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/** List a group's albums (HTTP-cookie-based, qzone.qq.com). */
|
||||
async list(groupId: number): Promise<any> {
|
||||
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 || [];
|
||||
}
|
||||
|
||||
/** Upload an image into an existing album (HTTP slice-upload). */
|
||||
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 });
|
||||
}
|
||||
|
||||
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 ?? '',
|
||||
});
|
||||
}
|
||||
|
||||
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any> {
|
||||
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<any> {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,101 @@
|
||||
// ApiHub — the per-instance bag of typed Api classes hanging off
|
||||
// `bridge.apis`. Mirrors NapCat's `NapCatCore.apis = { MsgApi, …}`
|
||||
// pattern but uses camelCase keys (`apis.message.sendGroup`) to match
|
||||
// the rest of the SnowLuma TypeScript style.
|
||||
//
|
||||
// Each Api class is constructed once when the parent `Bridge` is
|
||||
// constructed (eager — every account that connects gets its own
|
||||
// `apis.*` set immediately). Api classes receive a `BridgeContext`
|
||||
// reference, NOT the concrete `Bridge`, so they remain easy to mock
|
||||
// without standing up a full Bridge instance.
|
||||
//
|
||||
// Adding a new Api:
|
||||
// 1. Create `bridge/apis/<name>.ts` exporting a `class XxxApi`.
|
||||
// 2. Add a property here.
|
||||
// 3. Construct it inside `buildApiHub(ctx)` below.
|
||||
// 4. Move the relevant methods OFF Bridge and onto the new Api.
|
||||
//
|
||||
// All 12 Api hubs are now live (#6 commits 1-12). The interface lists
|
||||
// every typed area an OneBot caller can reach via `bridge.apis.*`.
|
||||
|
||||
import type { BridgeContext } from '../bridge-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: BridgeContext): 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 } from './contacts';
|
||||
export { ExtrasApi } 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 } from './message';
|
||||
export { MiscApi } from './misc';
|
||||
export { ProfileApi } from './profile';
|
||||
export { WebApi } from './web';
|
||||
@@ -0,0 +1,95 @@
|
||||
// InteractionApi — interactive engagement primitives (poke / like /
|
||||
// reaction / essence / emoji-like-list). Inlined from
|
||||
// `actions/interaction.ts` + the lone-survivor `setGroupEssence` from
|
||||
// `actions/group-message.ts` (both deleted alongside actions/* in
|
||||
// commit 13). The recall+markRead halves of `group-message.ts` were
|
||||
// already absorbed into `MessageApi` back in commit 1.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
Oidb0x9083Req,
|
||||
Oidb0x9083Resp,
|
||||
OidbEssence,
|
||||
OidbGroupReaction,
|
||||
OidbLike,
|
||||
OidbPoke,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export class InteractionApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbPoke>(0xED3, 1, {
|
||||
uin: targetUin ?? peerUin,
|
||||
groupUin: isGroup ? peerUin : 0,
|
||||
friendUin: isGroup ? 0 : peerUin,
|
||||
ext: 0,
|
||||
});
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', protobuf_encode<OidbBase<OidbPoke>>(env));
|
||||
}
|
||||
|
||||
async sendLike(userId: number, count: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const env = makeOidbEnvelope<OidbLike>(0x7E5, 104, { targetUin: userId, count });
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', protobuf_encode<OidbBase<OidbLike>>(env));
|
||||
}
|
||||
|
||||
async setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const subCmd = isSet ? 1 : 2;
|
||||
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
|
||||
// Same heuristic Lagrange.Core V2 uses (`GroupAddReactionEvent.IsEmoji`):
|
||||
// QQ face ids are 1–3 digits ("76") → type=1, unicode codepoints are
|
||||
// longer ("128516") → type=2. Server reads the type at field 5; sending
|
||||
// it at the wrong field number triggers
|
||||
// "invalid ReqBody.EmojiType: value must be greater than 0".
|
||||
const type = code.length > 3 ? 2 : 1;
|
||||
const env = makeOidbEnvelope<OidbGroupReaction>(0x9082, subCmd, {
|
||||
groupUin: groupId, sequence, code, type, field6: false, field7: false,
|
||||
});
|
||||
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupReaction>>(env));
|
||||
}
|
||||
|
||||
async setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const subCmd = enable ? 1 : 2;
|
||||
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
|
||||
const env = makeOidbEnvelope<OidbEssence>(0xEAC, subCmd, { groupUin: groupId, sequence, random });
|
||||
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbEssence>>(env));
|
||||
}
|
||||
|
||||
async getEmojiLikes(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType = 1,
|
||||
count = 10,
|
||||
cookie = '',
|
||||
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req: any = {
|
||||
groupId: BigInt(groupId),
|
||||
sequence,
|
||||
emojiType,
|
||||
emojiId,
|
||||
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
|
||||
field7: 0,
|
||||
count,
|
||||
field12: 1,
|
||||
};
|
||||
const env = makeOidbEnvelope<Oidb0x9083Req>(0x9083, 1, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', protobuf_encode<OidbBase<Oidb0x9083Req>>(env));
|
||||
const resp = protobuf_decode<OidbBase<Oidb0x9083Resp>>(respBytes).body;
|
||||
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 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
// MessageApi — send / recall / mark-read operations.
|
||||
//
|
||||
// Folds together the previous shapes:
|
||||
// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage`
|
||||
// (formerly inline on the Bridge class).
|
||||
// - `actions/group-message.ts` (recallGroup / recallPrivate /
|
||||
// markGroupRead / markPrivateRead).
|
||||
//
|
||||
// All implementations are inlined here — the previous indirection
|
||||
// through `actions/group-message.ts` exported functions was just
|
||||
// `(bridge, args) → method body`; once methods live on a typed Api
|
||||
// class the wrapper layer doesn't earn its keep.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
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 type { MessageElement } from '@snowluma/bridge/events';
|
||||
import { buildSendElems } from '@snowluma/bridge/element-builder';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// `Bridge` is imported as a type only so we can narrow `ctx` back to
|
||||
// the concrete Bridge instance when passing it to `buildSendElems`
|
||||
// (which still takes `Bridge` because the highway upload helpers it
|
||||
// transitively calls each take `Bridge` — refactoring those is a
|
||||
// separate concern that doesn't need to land alongside the Api split).
|
||||
//
|
||||
// At runtime `ctx` IS the Bridge instance that constructed this
|
||||
// MessageApi — `buildApiHub(ctx)` passes the Bridge itself.
|
||||
import type { Bridge, SendMessageReceipt } from '../bridge';
|
||||
|
||||
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
export class MessageApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/**
|
||||
* 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 as unknown as Bridge, groupId });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
grp: { groupCode: BigInt(groupId) },
|
||||
},
|
||||
contentHead: {
|
||||
type: 1,
|
||||
},
|
||||
messageBody: {
|
||||
richText: {
|
||||
elems: protoElems,
|
||||
},
|
||||
} as any,
|
||||
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 as unknown as Bridge, 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,
|
||||
},
|
||||
} as any,
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// MiscApi — odds & ends that don't fit the other Apis: translation,
|
||||
// mini-app ARK build, inline-keyboard button click, group sign-in.
|
||||
// Inlined from `actions/misc.ts` (deleted alongside actions/* in
|
||||
// commit 13).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
MiniAppShareReq,
|
||||
MiniAppShareResp,
|
||||
Oidb0x112eReq,
|
||||
Oidb0x112eResp,
|
||||
Oidb0x990Req,
|
||||
Oidb0x990Resp,
|
||||
Oidb0xeb7Req,
|
||||
Oidb0xeb7Resp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async translateEn2Zh(words: string[]): Promise<string[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req = {
|
||||
translateReq: {
|
||||
srcLang: 'en',
|
||||
dstLang: 'zh',
|
||||
words,
|
||||
},
|
||||
tag10: 1,
|
||||
tag12: 1,
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<Oidb0x990Req>(0x990, 2, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', protobuf_encode<OidbBase<Oidb0x990Req>>(env));
|
||||
const result = protobuf_decode<OidbBase<Oidb0x990Resp>>(respBytes).body;
|
||||
|
||||
const resp = result?.translateResp;
|
||||
if (!resp) {
|
||||
throw new Error('translate response empty');
|
||||
}
|
||||
|
||||
return resp.dstWords || [];
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any> {
|
||||
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);
|
||||
|
||||
return {
|
||||
data: {
|
||||
ver: parsed.ver,
|
||||
prompt: parsed.prompt,
|
||||
config: parsed.config,
|
||||
app: parsed.appName,
|
||||
view: parsed.appView,
|
||||
meta: parsed.metaData,
|
||||
miniappShareOrigin: 3,
|
||||
miniappOpenRefer: '10002',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async clickInlineKeyboardButton(
|
||||
groupId: number,
|
||||
botAppid: number,
|
||||
buttonId: string,
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
): Promise<any> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req = {
|
||||
botAppid: BigInt(botAppid),
|
||||
msgSeq: BigInt(msgSeq),
|
||||
buttonId: String(buttonId),
|
||||
callbackData: String(callbackData || ''),
|
||||
unknown7: 0,
|
||||
groupId: BigInt(groupId),
|
||||
unknown9: 1,
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<Oidb0x112eReq>(0x112E, 1, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', protobuf_encode<OidbBase<Oidb0x112eReq>>(env));
|
||||
const result = protobuf_decode<OidbBase<Oidb0x112eResp>>(respBytes).body;
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
async sendGroupSign(groupId: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req = {
|
||||
signInInfo: {
|
||||
uin: String(this.ctx.identity.uin),
|
||||
groupId: String(groupId),
|
||||
version: '9.0.90',
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<Oidb0xeb7Req>(0xEB7, 1, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', protobuf_encode<OidbBase<Oidb0xeb7Req>>(env));
|
||||
protobuf_decode<OidbBase<Oidb0xeb7Resp>>(respBytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// ProfileApi — personal profile + status + avatar + likes + custom
|
||||
// faces + unidirectional friend list. Inlined from
|
||||
// `actions/profile.ts` (deleted alongside actions/* in commit 13).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
FaceroamOpReq,
|
||||
FaceroamOpResp,
|
||||
GroupAvatarExtra,
|
||||
Oidb0x112aReq,
|
||||
Oidb0x112aResp,
|
||||
Oidb0x7edReq,
|
||||
Oidb0x7edResp,
|
||||
Oidb0xcd4Req,
|
||||
Oidb0xcd4Resp,
|
||||
Oidb0xe17Req,
|
||||
Oidb0xe17Resp,
|
||||
OidbSetProfile,
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/bridge/highway/utils';
|
||||
import { resolveSelfUid } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export class ProfileApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
// ─────────────── 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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const uin = BigInt(this.ctx.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 };
|
||||
const env = makeOidbEnvelope<OidbSetProfile>(0x112A, 2, req);
|
||||
await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode<OidbBase<OidbSetProfile>>(env));
|
||||
}
|
||||
|
||||
async setSelfLongNick(longNick: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req = {
|
||||
uin: BigInt(this.ctx.identity.uin),
|
||||
profile: {
|
||||
tag: 102,
|
||||
value: String(longNick),
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<Oidb0x112aReq>(0x112A, 2, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode<OidbBase<Oidb0x112aReq>>(env));
|
||||
// Decode just to maintain the original behaviour of "consume the response".
|
||||
protobuf_decode<OidbBase<Oidb0x112aResp>>(respBytes);
|
||||
}
|
||||
|
||||
async setInputStatus(userId: number, eventType: number): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
|
||||
if (!targetUid) {
|
||||
throw new Error('target uid not found');
|
||||
}
|
||||
|
||||
const req = {
|
||||
reqBody: {
|
||||
uid: targetUid,
|
||||
chatType: 0,
|
||||
eventType,
|
||||
},
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<Oidb0xcd4Req>(0xCD4, 1, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode<OidbBase<Oidb0xcd4Req>>(env));
|
||||
protobuf_decode<OidbBase<Oidb0xcd4Resp>>(respBytes);
|
||||
}
|
||||
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = asBridge(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 = asBridge(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 ───────────────
|
||||
|
||||
async getLike(userId?: number, start = 0, limit = 10): Promise<any> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const isSelf = !userId;
|
||||
const targetUid = isSelf
|
||||
? await resolveSelfUid(bridge)
|
||||
: await this.ctx.resolveUserUid(userId);
|
||||
|
||||
if (!targetUid) {
|
||||
throw new Error('target uid not found');
|
||||
}
|
||||
|
||||
const req = {
|
||||
targetUid,
|
||||
basic: 1,
|
||||
vote: 1,
|
||||
favorite: 1,
|
||||
start,
|
||||
limit,
|
||||
};
|
||||
|
||||
const env = makeOidbEnvelope<Oidb0x7edReq>(0x7ED, 12, req);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode<OidbBase<Oidb0x7edReq>>(env));
|
||||
const result = protobuf_decode<OidbBase<Oidb0x7edResp>>(respBytes).body;
|
||||
|
||||
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: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getUnidirectionalFriendList(): Promise<any> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const reqObj = {
|
||||
uint64_uin: String(this.ctx.identity.uin),
|
||||
uint64_top: 0,
|
||||
uint32_req_num: 99,
|
||||
bytes_cookies: '',
|
||||
};
|
||||
|
||||
const req = { jsonBody: JSON.stringify(reqObj) };
|
||||
const env = makeOidbEnvelope<Oidb0xe17Req>(0xE17, 0, req);
|
||||
const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode<OidbBase<Oidb0xe17Req>>(env));
|
||||
const result = protobuf_decode<OidbBase<Oidb0xe17Resp>>(respBytes).body;
|
||||
|
||||
if (!result || !result.jsonBody) {
|
||||
throw new Error('get unidirectional friend list empty');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(result.jsonBody);
|
||||
return parsed.rpt_block_list || [];
|
||||
}
|
||||
|
||||
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 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/${this.ctx.identity.uin}/${id}/0`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { Bridge } from '../bridge';
|
||||
|
||||
/**
|
||||
* 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') {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard OIDB response check: throw a typed Error if retCode != 0.
|
||||
* Prefers `wording` over `msg` for the human-facing message, falling
|
||||
* back to a generic string. All themed action modules use this for
|
||||
* their OIDB error-path uniformity.
|
||||
*/
|
||||
export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void {
|
||||
const retCode = toInt(code);
|
||||
if (retCode === 0) return;
|
||||
const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error';
|
||||
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the bot's own UID. Cached on Identity once warmup populates
|
||||
* `selfProfile`; forward/profile actions need this fast path before
|
||||
* warmup completes.
|
||||
*/
|
||||
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (selfUid) return selfUid;
|
||||
|
||||
const selfUin = toInt(bridge.identity.uin);
|
||||
if (selfUin <= 0) {
|
||||
throw new Error('self uid is unavailable');
|
||||
}
|
||||
selfUid = await bridge.resolveUserUid(selfUin);
|
||||
return selfUid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index describing a server-side rich-media object (image / video /
|
||||
* voice). Returned by message parsers, consumed by the media-URL
|
||||
* fetchers in group-file.ts.
|
||||
*/
|
||||
export interface MediaIndexNode {
|
||||
info?: {
|
||||
fileSize?: number;
|
||||
fileHash?: string;
|
||||
fileSha1?: string;
|
||||
fileName?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
time?: number;
|
||||
original?: number;
|
||||
type?: {
|
||||
type?: number;
|
||||
picFormat?: number;
|
||||
videoFormat?: number;
|
||||
voiceFormat?: number;
|
||||
};
|
||||
};
|
||||
fileUuid?: string;
|
||||
storeId?: number;
|
||||
uploadTime?: number;
|
||||
ttl?: number;
|
||||
subType?: number;
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
// WebApi — cookie-backed HTTP wrappers (group essence / honor / notice /
|
||||
// client-key / pskey / csrf-token / credentials). Inlined from the
|
||||
// per-feature files in `web-actions/` (all deleted in commit 13).
|
||||
// The pure HTTP transport stays in `web/*.ts` and stays unchanged —
|
||||
// only the Bridge-binding helpers move here.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbClientKeyReq,
|
||||
OidbClientKeyResp,
|
||||
OidbGetPskeyReq,
|
||||
OidbGetPskeyResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '@snowluma/bridge/web/group-essence';
|
||||
import { getHonorListWebAPI, WebHonorType } from '@snowluma/bridge/web/group-honor';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
getGroupNoticeWebAPI,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
} from '@snowluma/bridge/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/bridge/web/request-util';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
keyIndex: string;
|
||||
expireTime: string;
|
||||
}
|
||||
|
||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||
|
||||
async function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
|
||||
const env = makeOidbEnvelope<OidbClientKeyReq>(0x102A, 1, {});
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', protobuf_encode<OidbBase<OidbClientKeyReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbClientKeyResp>>(respBytes).body;
|
||||
|
||||
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'),
|
||||
};
|
||||
}
|
||||
|
||||
async function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
const env = makeOidbEnvelope<OidbGetPskeyReq>(0x102A, 0, { domainList });
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', protobuf_encode<OidbBase<OidbGetPskeyReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbGetPskeyResp>>(respBytes).body;
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
async function getCookies(bridge: Bridge, 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: Bridge): 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: BridgeContext) {}
|
||||
|
||||
// ─────────────── cookie / token primitives ───────────────
|
||||
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> {
|
||||
return forceFetchClientKeyInner(asBridge(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(asBridge(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(asBridge(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(asBridge(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(asBridge(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<any> {
|
||||
const bridge = asBridge(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<any> {
|
||||
const bridge = asBridge(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<any> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
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;
|
||||
}
|
||||
|
||||
// ─────────────── 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<any> {
|
||||
const bridge = asBridge(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<any[]> {
|
||||
const bridge = asBridge(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: 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,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
}
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,335 +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 { sendOidbAndDecode } 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 sendOidbAndDecode<any>(
|
||||
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body,
|
||||
OidbFriendListRequestSchema, 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.qqInfo.setFriends(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 sendOidbAndDecode<any>(
|
||||
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body,
|
||||
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true);
|
||||
|
||||
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.qqInfo.setGroups(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 sendOidbAndDecode<any>(
|
||||
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body,
|
||||
OidbGroupMemberListRequestSchema, 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.qqInfo.setGroupMembers(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 sendOidbAndDecode<any>(
|
||||
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body,
|
||||
OidbUserInfoRequestSchema, 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.qqInfo.setUserProfile(info);
|
||||
const selfUin = parseInt(bridge.qqInfo.uin, 10) || 0;
|
||||
if (info.uin === selfUin) bridge.qqInfo.setSelfProfile(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 sendOidbAndDecode<any>(
|
||||
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 },
|
||||
OidbGroupRequestListSchema, 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,
|
||||
});
|
||||
}
|
||||
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 sendOidbAndDecode<any>(
|
||||
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body,
|
||||
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true);
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Api-layer extension of @snowluma/bridge's slim BridgeContext.
|
||||
//
|
||||
// The slim interface in @snowluma/bridge has the protocol-layer
|
||||
// surface (identity / events / sendRawPacket / resolveUserUid / next*
|
||||
// sequence helpers / upload-metadata cache). This file extends it
|
||||
// with `apis: ApiHub` — the typed bag of Api classes that lives ONLY
|
||||
// in @snowluma/core, so the bridge package never sees it (avoiding
|
||||
// a bridge → core cycle).
|
||||
//
|
||||
// The 13 Api classes (apis/<area>.ts) import `BridgeContext` from
|
||||
// here, which gives them `this.ctx.apis.message.sendGroup(...)` type-
|
||||
// safety alongside the protocol-layer fields. Highway uploaders,
|
||||
// element-builder, msg-push parsers (all in @snowluma/bridge) import
|
||||
// the slim version directly from `@snowluma/bridge/bridge-context`.
|
||||
|
||||
import type { BridgeContext as BaseBridgeContext } from '@snowluma/bridge/bridge-context';
|
||||
import type { ApiHub } from './apis';
|
||||
|
||||
export interface BridgeContext extends BaseBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
}
|
||||
|
||||
// Re-export `UploadedFileMeta` from the slim package so existing
|
||||
// `import type { UploadedFileMeta } from '<…>/bridge-context'` (or
|
||||
// from bridge.ts via re-export) keeps working without callers having
|
||||
// to learn the new package path.
|
||||
export type { UploadedFileMeta } from '@snowluma/bridge/bridge-context';
|
||||
@@ -0,0 +1,22 @@
|
||||
// BridgeInterface — the public Bridge surface for OneBot-side
|
||||
// consumers. Slimmed down to BridgeContext + the few extra fields
|
||||
// OneBot reaches into directly (most notably `activePid`).
|
||||
//
|
||||
// Most OneBot code paths reach business methods through
|
||||
// `bridge.apis.<area>.method()` — those types come from `ApiHub`
|
||||
// inside `bridge-context.ts`. The remaining members below are the
|
||||
// non-Api state that doesn't fit into a typed Api hub.
|
||||
//
|
||||
// Internal Api implementations should depend on `BridgeContext`
|
||||
// instead (the narrower contract). `BridgeInterface` is for callers
|
||||
// that need the activePid hook or for backwards compatibility with
|
||||
// pre-#6 code that imported `BridgeInterface` as the bridge type.
|
||||
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
/** Last-active process id — used by `OneBotManager` to thread
|
||||
* per-process state into the right instance. `null` when no
|
||||
* process has bound yet. */
|
||||
readonly activePid: number | null;
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution.
|
||||
|
||||
import type { Bridge } from './bridge';
|
||||
import type { ProtoSchema } from '../protobuf/decode';
|
||||
import { protoEncode, protoDecode } from '../protobuf/decode';
|
||||
import { makeOidbBaseSchema } from './proto/oidb';
|
||||
|
||||
/**
|
||||
* Build a raw OIDB request buffer (base envelope wrapping a typed body).
|
||||
*/
|
||||
export function makeOidbRequest(
|
||||
command: number, subCommand: number,
|
||||
body: any, bodySchema: ProtoSchema, isUid = false,
|
||||
): Uint8Array {
|
||||
const baseSchema = makeOidbBaseSchema(bodySchema);
|
||||
return protoEncode({
|
||||
command,
|
||||
subCommand,
|
||||
errorCode: 0,
|
||||
body,
|
||||
errorMsg: '',
|
||||
reserved: isUid ? 1 : 0,
|
||||
}, baseSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an OIDB packet and verify it succeeded (no decode of body).
|
||||
*/
|
||||
export async function sendOidbAndCheck(
|
||||
bridge: Bridge,
|
||||
serviceCmd: string, command: number, subCommand: number,
|
||||
body: any, bodySchema: ProtoSchema, isUid = false,
|
||||
): Promise<void> {
|
||||
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
|
||||
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
// Check OIDB error code if response present
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
|
||||
const resp = protoDecode(result.responseData, emptyBase);
|
||||
if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an OIDB packet and decode the response body with the given schema.
|
||||
*/
|
||||
export async function sendOidbAndDecode<T>(
|
||||
bridge: Bridge,
|
||||
serviceCmd: string, command: number, subCommand: number,
|
||||
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false,
|
||||
): Promise<T> {
|
||||
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
|
||||
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
const baseSchema = makeOidbBaseSchema(responseSchema);
|
||||
const resp = protoDecode(result.responseData, baseSchema);
|
||||
if (!resp) throw new Error('failed to decode OIDB response');
|
||||
if ((resp as any).errorCode && (resp as any).errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
|
||||
}
|
||||
return (resp as any).body as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a UIN to a UID string, using cache or fetching as needed.
|
||||
* Mirrors C++ resolve_user_uid_for_action.
|
||||
*/
|
||||
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
|
||||
// Try group member first
|
||||
if (groupId !== undefined) {
|
||||
const uid = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
|
||||
if (uid) return uid;
|
||||
// Try fetching member list
|
||||
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
|
||||
const uid2 = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
|
||||
if (uid2) return uid2;
|
||||
}
|
||||
// Try cached
|
||||
const uid = bridge.qqInfo.findUidByUin(uin);
|
||||
if (uid) return uid;
|
||||
// Fetch profile
|
||||
const profile = await bridge.fetchUserProfile(uin);
|
||||
if (profile.uid) return profile.uid;
|
||||
throw new Error(`failed to resolve UID for UIN ${uin}`);
|
||||
}
|
||||
+202
-469
@@ -1,90 +1,44 @@
|
||||
// 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 { QQInfo } from './qq-info';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler';
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||
import { protoEncode, protoDecode } from '../protobuf/decode';
|
||||
import { buildSendElems } from './builders/element-builder';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import {
|
||||
SendMessageRequestSchema,
|
||||
SendMessageResponseSchema,
|
||||
} from './proto/action';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
import { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/bridge/msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/bridge/packet-pipeline';
|
||||
// qq-info types are no longer used directly in this file — they live
|
||||
// inside the Api classes that own those fetches (apis/contacts.ts).
|
||||
import { type ApiHub, buildApiHub } from './apis';
|
||||
|
||||
// Delegated modules
|
||||
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
|
||||
// Group-todo / stranger-status / AI-voice moved to apis/extras.ts.
|
||||
// Public types stay re-exported through this file for backwards
|
||||
// compatibility — the OneBot side imports them via `@snowluma/core`.
|
||||
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_,
|
||||
kickGroupMember as kickGroupMember_,
|
||||
leaveGroup as leaveGroup_,
|
||||
setGroupAdmin as setGroupAdmin_,
|
||||
setGroupCard as setGroupCard_,
|
||||
setGroupName as setGroupName_,
|
||||
setGroupSpecialTitle as setGroupSpecialTitle_,
|
||||
setFriendAddRequest as setFriendAddRequest_,
|
||||
deleteFriend as deleteFriend_,
|
||||
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_,
|
||||
uploadForwardNodes as uploadForwardNodes_,
|
||||
fetchForwardNodes as fetchForwardNodes_,
|
||||
deleteGroupFile as deleteGroupFile_,
|
||||
moveGroupFile as moveGroupFile_,
|
||||
createGroupFileFolder as createGroupFileFolder_,
|
||||
deleteGroupFileFolder as deleteGroupFileFolder_,
|
||||
renameGroupFileFolder as renameGroupFileFolder_,
|
||||
setGroupAddRequest as setGroupAddRequest_,
|
||||
sendPoke as sendPoke_,
|
||||
sendLike as sendLike_,
|
||||
setGroupEssence as setGroupEssence_,
|
||||
setGroupReaction as setGroupReaction_,
|
||||
recallGroupMessage as recallGroupMessage_,
|
||||
recallPrivateMessage as recallPrivateMessage_,
|
||||
markPrivateMessageRead as markGroupMsgAsRead_,
|
||||
markGroupMessageRead as markPrivateMsgAsRead_,
|
||||
setFriendRemark as setFriendRemark_,
|
||||
fetchGroupFileCount as fetchGroupFileCount_,
|
||||
setOnlineStatus as setOnlineStatus_,
|
||||
setProfile as setProfile_,
|
||||
} from './bridge-actions';
|
||||
import {
|
||||
getGroupHonorInfo as getGroupHonorInfo_,
|
||||
forceFetchClientKey as forceFetchClientKey_,
|
||||
getGroupEssence as getGroupEssence_,
|
||||
getGroupEssenceAll as getGroupEssenceAll_,
|
||||
sendGroupNotice as sendGroupNotice_,
|
||||
getGroupNotice as getGroupNotice_,
|
||||
getCookiesStr as getCookiesStr_,
|
||||
getCsrfToken as getCsrfToken_,
|
||||
getCredentials as getCredentials_,
|
||||
} from './web-actions';
|
||||
import type { GroupFilesResult } from './bridge-actions';
|
||||
import type { MediaIndexNode } from './bridge-actions';
|
||||
|
||||
export type BridgeEventCallback = (event: QQEventVariant) => void;
|
||||
|
||||
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
|
||||
AiVoiceChatType,
|
||||
type AiVoiceCategory,
|
||||
type StrangerStatus,
|
||||
} from './apis/extras';
|
||||
// actions/forward.ts removed — moved to apis/forward.ts::ForwardApi.
|
||||
// actions/friend.ts removed — moved to apis/friend.ts::FriendApi.
|
||||
// actions/group-admin.ts removed — moved to `apis/group-admin.ts::GroupAdminApi`.
|
||||
// actions/group-album.ts removed — moved to `apis/group-album.ts::GroupAlbumApi`.
|
||||
// Group file CRUD + private c2c upload + media URL resolvers moved to
|
||||
// `apis.groupFile` (see `apis/group-file.ts::GroupFileApi`). The shared
|
||||
// result type still lives here because the OneBot side imports it
|
||||
// through bridge.ts.
|
||||
import type { GroupFilesResult } from './apis/group-file';
|
||||
// actions/group-message.ts removed — `setGroupEssence` moved to
|
||||
// apis/interaction.ts::InteractionApi. The recall/markRead helpers
|
||||
// were absorbed into MessageApi back in commit 1.
|
||||
// actions/interaction.ts removed — sendPoke/sendLike/setReaction/
|
||||
// getEmojiLikes moved to apis/interaction.ts::InteractionApi.
|
||||
// actions/misc.ts removed — moved to apis/misc.ts::MiscApi.
|
||||
// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi.
|
||||
// `bridge-contacts.ts` removed — its 6 functions are now methods on
|
||||
// `apis.contacts` (see `apis/contacts.ts::ContactsApi`).
|
||||
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
|
||||
// web-actions/* removed — moved to apis/web.ts::WebApi.
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
@@ -94,6 +48,29 @@ export interface SendMessageReceipt {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata remembered after `upload_group_file` / `upload_private_file`
|
||||
* succeeds. Lets the OneBot send-message path reconstruct the full
|
||||
* payload when the caller only echoes the `file_id` back later. See
|
||||
* `Bridge.rememberUploadedFile` / `recallUploadedFile`.
|
||||
*/
|
||||
export interface UploadedFileMeta {
|
||||
fileId: string;
|
||||
scope: 'group' | 'private';
|
||||
/** Group id if scope='group', else `undefined`. */
|
||||
groupId?: number;
|
||||
/** Friend uin if scope='private', else `undefined`. */
|
||||
userId?: number;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
fileMd5: Uint8Array;
|
||||
fileSha1: Uint8Array;
|
||||
/** Server-issued hash returned alongside the upload (private only). */
|
||||
fileHash?: string;
|
||||
/** Insert time — used to evict the oldest entry when the cache fills. */
|
||||
rememberedAt: number;
|
||||
}
|
||||
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
@@ -108,59 +85,87 @@ export interface ClientKeyInfo {
|
||||
keyIndex: string
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
|
||||
export class Bridge {
|
||||
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
private qqInfo_: QQInfo;
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
private eventCallback_: BridgeEventCallback | null = null;
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
/**
|
||||
* 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();
|
||||
/**
|
||||
* Typed Api hub. Each entry is a class encapsulating one logical
|
||||
* area of the QQ protocol (sending messages, group admin, file
|
||||
* uploads, etc.). Built eagerly in the constructor — every Bridge
|
||||
* instance gets its own `apis.*` set with `this` (typed as
|
||||
* `BridgeContext`) injected. See `apis/index.ts`.
|
||||
*/
|
||||
readonly apis: ApiHub;
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
private packetClient_: PacketSender | null = null;
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
|
||||
// and serves a fresh result for `kMemberListTtlMs` to all callers.
|
||||
// Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
// 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[] }>();
|
||||
// (fetchGroupMemberList throttle cache moved to ContactsApi — same
|
||||
// 60s TTL + inflight coalesce semantics, just owned by the Api class
|
||||
// that exposes the method.)
|
||||
|
||||
// ── Uploaded-file metadata cache ────────────────────────────────────
|
||||
//
|
||||
// After a file goes through `upload_group_file` / `upload_private_file`
|
||||
// we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed
|
||||
// by the returned file_id. The OneBot send-message paths consult this
|
||||
// when the caller later passes `{type:'file', file_id:'xxx'}` without
|
||||
// the rest of the metadata — c2c file send needs the size/md5/name
|
||||
// for the wire packet (server-side rejection / "0 byte file" otherwise),
|
||||
// and the group send path falls back to the name for the log line.
|
||||
//
|
||||
// Bounded at ~1024 entries with simple FIFO eviction. Files older
|
||||
// than 7 days expire on QQ's side anyway, so this isn't load-bearing
|
||||
// for correctness — just a UX convenience cache so the OneBot caller
|
||||
// doesn't have to thread the metadata themselves between upload and
|
||||
// send_msg.
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
|
||||
// Sequence and random generators for outgoing messages
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
|
||||
constructor(qqInfo: QQInfo) {
|
||||
this.qqInfo_ = qqInfo;
|
||||
this.registerDefaultHandlers();
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
// Build Api hub FIRST — `setFetcher` below installs callbacks
|
||||
// that reach into `this.apis.contacts.*`, so the hub must exist
|
||||
// by the time those callbacks could fire. The Bridge instance IS
|
||||
// the BridgeContext (Bridge implements BridgeInterface which
|
||||
// includes the BridgeContext surface).
|
||||
this.apis = buildApiHub(this);
|
||||
this.identity.setFetcher({
|
||||
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
|
||||
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
|
||||
});
|
||||
this.pipeline = new IncomingPacketPipeline({
|
||||
identity: this.identity,
|
||||
events: this.events,
|
||||
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
|
||||
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
|
||||
});
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
}
|
||||
|
||||
get qqInfo(): QQInfo { return this.qqInfo_; }
|
||||
dispose(): void {
|
||||
this.identity.close();
|
||||
this.events.clear();
|
||||
}
|
||||
|
||||
setPacketClient(client: PacketSender): void {
|
||||
this.packetClient_ = client;
|
||||
}
|
||||
|
||||
private registerDefaultHandlers(): void {
|
||||
this.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||
arr.push(parser);
|
||||
this.cmdHandlers_.set(cmd, arr);
|
||||
}
|
||||
|
||||
setEventCallback(cb: BridgeEventCallback): void {
|
||||
this.eventCallback_ = cb;
|
||||
this.pipeline.registerCmd(cmd, parser);
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.cmdHandlers_.has(cmd);
|
||||
return this.pipeline.handlesCmd(cmd);
|
||||
}
|
||||
|
||||
// --- PID management ---
|
||||
@@ -181,79 +186,62 @@ export class Bridge {
|
||||
// --- Packet dispatch ---
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
|
||||
if (!handlers) return;
|
||||
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
const events = handler(pkt, this.qqInfo_);
|
||||
for (const event of events) {
|
||||
this.triggerMemberCacheRefresh(event);
|
||||
printEvent(event);
|
||||
this.emitEvent(event);
|
||||
}
|
||||
} catch (e) {
|
||||
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
this.pipeline.process(pkt);
|
||||
}
|
||||
|
||||
private emitEvent(event: QQEventVariant): void {
|
||||
if (this.eventCallback_) {
|
||||
try { this.eventCallback_(event); } catch (e) {
|
||||
log.error('event callback error: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
|
||||
if (refreshGroupList) {
|
||||
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (!this.identity.findGroup(groupId)) return false;
|
||||
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
|
||||
private triggerMemberCacheRefresh(event: QQEventVariant): void {
|
||||
let groupId = 0;
|
||||
let reason = '';
|
||||
switch (event.kind) {
|
||||
case 'group_member_join':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_join';
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_member_leave';
|
||||
break;
|
||||
case 'group_admin':
|
||||
groupId = event.groupId;
|
||||
reason = 'group_admin';
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
// --- Uploaded-file metadata cache ---
|
||||
|
||||
/**
|
||||
* Remember a freshly-uploaded file so a later `send_*_msg` carrying
|
||||
* just the file_id can reconstruct the full c2c-file packet (fileName
|
||||
* / fileSize / fileMd5 are required by the QQ NT server's c2c file
|
||||
* intake, even if only the uuid is needed for the OIDB lookup
|
||||
* internally — without them the file shows as 0 B in the recipient's
|
||||
* chat or is silently rejected). Insertion is FIFO; oldest entry is
|
||||
* evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`.
|
||||
*/
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void {
|
||||
if (!meta.fileId) return;
|
||||
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
|
||||
// Map iteration order is insertion order — drop the oldest.
|
||||
const oldest = this.uploadedFileMeta_.keys().next().value;
|
||||
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
|
||||
}
|
||||
this.uploadedFileMeta_.set(meta.fileId, meta);
|
||||
}
|
||||
|
||||
if (groupId <= 0) return;
|
||||
if (this.memberRefreshTasks_.has(groupId)) return;
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
if (!this.qqInfo_.findGroup(groupId)) {
|
||||
try { await this.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
await this.fetchGroupMemberList(groupId);
|
||||
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
} catch (e) {
|
||||
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
this.memberRefreshTasks_.delete(groupId);
|
||||
}
|
||||
})();
|
||||
|
||||
this.memberRefreshTasks_.set(groupId, task);
|
||||
/**
|
||||
* Recall metadata for a previously-uploaded file. Returns `undefined`
|
||||
* if the file_id was never uploaded through this bridge instance, or
|
||||
* if it's been evicted from the cache.
|
||||
*/
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
|
||||
if (!fileId) return undefined;
|
||||
return this.uploadedFileMeta_.get(fileId);
|
||||
}
|
||||
|
||||
// --- Sequence / random generators ---
|
||||
//
|
||||
// `public` (formerly `private`) because the Api classes in
|
||||
// `apis/*.ts` need them to build `SendMessageRequest` packets. Part
|
||||
// of the `BridgeContext` surface, so a third party that only sees
|
||||
// `BridgeContext` can still synthesise wire packets without reaching
|
||||
// into the concrete Bridge class.
|
||||
|
||||
private nextClientSequence(): number {
|
||||
nextClientSequence(): number {
|
||||
return ++this.clientSeq_;
|
||||
}
|
||||
|
||||
private nextMessageRandom(): number {
|
||||
nextMessageRandom(): number {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
@@ -270,304 +258,49 @@ export class Bridge {
|
||||
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 image upload (C++ resolves UID before building elems)
|
||||
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,
|
||||
},
|
||||
} 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,
|
||||
};
|
||||
}
|
||||
// `Bridge.SEND_MSG_CMD` and the inline `sendGroupMessage` /
|
||||
// `sendPrivateMessage` / `sendC2cFileMessage` implementations were
|
||||
// moved to `apis/message.ts::MessageApi` as part of the #6
|
||||
// Api-on-ctx refactor. Callers route through `bridge.apis.message.*`.
|
||||
|
||||
// --- Delegated: OIDB helpers ---
|
||||
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return resolveUserUid_(this, uin, groupId);
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
|
||||
// --- Delegated: Contact / info queries ---
|
||||
// fetchFriendList / fetchGroupList / fetchGroupMemberList /
|
||||
// fetchUserProfile / fetchGroupRequests / fetchDownloadRKeys
|
||||
// moved to apis.contacts (see apis/contacts.ts::ContactsApi).
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
|
||||
async fetchGroupMemberList(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const kMemberListTtlMs = 60_000;
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch_.get(groupId);
|
||||
if (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 kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
|
||||
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): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
|
||||
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 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 fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||
|
||||
// extend
|
||||
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
|
||||
return setOnlineStatus_(this, status, extStatus, batteryStatus);
|
||||
}
|
||||
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); }
|
||||
// --- Delegated: action methods ---
|
||||
//
|
||||
// GroupAdmin methods (mute/kick/admin/card/name/title/leave/
|
||||
// add-option/search/add-request/remark/at-all-remain) moved to
|
||||
// apis.groupAdmin (apis/group-admin.ts::GroupAdminApi).
|
||||
// Friend methods (handleRequest/delete/setRemark) moved to
|
||||
// apis.friend.
|
||||
// GroupFile methods (upload/uploadPrivate/publish/list/getUrl/
|
||||
// getPrivateUrl/{Ptt,Video}Url/getPrivate{Ptt,Video}Url/delete/move/
|
||||
// createFolder/deleteFolder/renameFolder/getCount) moved to
|
||||
// apis.groupFile (apis/group-file.ts::GroupFileApi).
|
||||
// Forward methods (upload / fetch) moved to apis.forward.
|
||||
// Interaction methods (sendPoke/sendLike/setReaction/setEssence/
|
||||
// getEmojiLikes) moved to apis.interaction.
|
||||
// recall* / markRead* moved to apis/message.ts::MessageApi.
|
||||
// GroupAlbum methods (list/upload/getMediaList/comment/like/delete)
|
||||
// moved to apis.groupAlbum (apis/group-album.ts::GroupAlbumApi).
|
||||
// Web methods (getHonorInfo / forceFetchClientKey / getEssence /
|
||||
// getEssenceAll / sendNotice / getNotice / deleteNotice /
|
||||
// getCookiesStr / getCsrfToken / getCredentials) moved to apis.web.
|
||||
// Profile methods (setOnlineStatus / setDiyOnlineStatus / setProfile /
|
||||
// setSelfLongNick / setInputStatus / setAvatar / setGroupAvatar /
|
||||
// fetchCustomFace / getLike / getUnidirectionalFriendList) moved to
|
||||
// apis.profile.
|
||||
// Misc methods (translateEn2Zh / getMiniAppArk /
|
||||
// clickInlineKeyboardButton / sendGroupSign) moved to apis.misc.
|
||||
|
||||
// --- Tier-2 napcat-parity extras (group todo / stranger status /
|
||||
// AI voice) moved to apis.extras. ---
|
||||
}
|
||||
|
||||
// --- Module-level helper functions ---
|
||||
|
||||
function elementsToText(elements: MessageElement[]): string {
|
||||
return elements.map(e => {
|
||||
switch (e.type) {
|
||||
case 'text': return e.text ?? '';
|
||||
case 'at': return `@${e.targetUin ?? 'all'}`;
|
||||
case 'face': return `[表情:${e.faceId}]`;
|
||||
case 'mface': return `[${e.summary ?? '表情'}]`;
|
||||
case 'image': return '[图片]';
|
||||
case 'video': return '[视频]';
|
||||
case 'record': return '[语音]';
|
||||
case 'file': return `[文件:${e.fileName ?? ''}]`;
|
||||
case 'json': return '[JSON卡片]';
|
||||
case 'xml': return '[XML卡片]';
|
||||
case 'reply': return `[回复:${e.replySeq}]`;
|
||||
case 'poke': return '[戳一戳]';
|
||||
case 'forward': return '[合并转发]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
default: return `[${e.type}]`;
|
||||
}
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function printEvent(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
// Message logging is handled by OneBot layer with message ID
|
||||
break;
|
||||
case 'group_recall':
|
||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||
break;
|
||||
case 'friend_recall':
|
||||
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
|
||||
break;
|
||||
case 'group_member_join':
|
||||
eventLog.info('入群 %d 加入 %d', event.userUin, event.groupId);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
eventLog.warn('退群 %d %s %d', event.userUin, event.isKick ? '被踢出' : '退出', event.groupId);
|
||||
break;
|
||||
case 'group_mute':
|
||||
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
|
||||
break;
|
||||
case 'group_admin':
|
||||
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
|
||||
break;
|
||||
case 'friend_poke':
|
||||
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'group_poke':
|
||||
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'friend_request':
|
||||
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
|
||||
break;
|
||||
case 'group_invite':
|
||||
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
|
||||
break;
|
||||
case 'group_essence':
|
||||
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
// Element Builder — converts internal MessageElement[] into proto Elem objects
|
||||
// for encoding with protoEncode(SendMessageRequestSchema).
|
||||
// Port of src/bridge/src/bridge_messages.cpp build_send_elems()
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import type { ProtoDecoded } from '../../protobuf/decode';
|
||||
import { protoEncode } from '../../protobuf/decode';
|
||||
import {
|
||||
ElemSchema,
|
||||
} from '../proto/element';
|
||||
import {
|
||||
MentionExtraSendSchema,
|
||||
MarkdownDataSchema,
|
||||
} from '../proto/action';
|
||||
import { uploadImageMsgInfo } from '../highway/image-upload';
|
||||
|
||||
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
|
||||
|
||||
export interface SendContext {
|
||||
bridge: Bridge;
|
||||
groupId?: number;
|
||||
userUid?: string;
|
||||
}
|
||||
|
||||
function makeTextElem(text: string): ProtoElem {
|
||||
return {
|
||||
text: { str: text } as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFaceElem(faceId: number): ProtoElem {
|
||||
return {
|
||||
face: { index: faceId } as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement): ProtoElem {
|
||||
const mentionAll = element.uid === 'all' || element.targetUin === 0;
|
||||
|
||||
const extra = protoEncode({
|
||||
type: mentionAll ? 1 : 2,
|
||||
uin: mentionAll ? 0 : (element.targetUin ?? 0),
|
||||
field5: 0,
|
||||
uid: mentionAll ? 'all' : (element.uid ?? ''),
|
||||
}, MentionExtraSendSchema);
|
||||
|
||||
return {
|
||||
text: {
|
||||
str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `),
|
||||
pbReserve: extra,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
const seq = element.replySeq! & 0xFFFFFFFF;
|
||||
|
||||
const srcMsg: any = {
|
||||
origSeqs: [seq],
|
||||
};
|
||||
|
||||
// Add additional fields if available for better reply display
|
||||
if (element.replySenderUin) {
|
||||
srcMsg.senderUin = BigInt(element.replySenderUin);
|
||||
}
|
||||
if (element.replyTime) {
|
||||
srcMsg.time = element.replyTime;
|
||||
}
|
||||
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 1,
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeXmlElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||
const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema);
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 45,
|
||||
pbElem: data,
|
||||
businessType: 1,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
const resId = (element.resId ?? '').trim();
|
||||
if (!resId) {
|
||||
throw new Error('forward resId is required');
|
||||
}
|
||||
|
||||
const xml = `<?xml version="1.0" encoding="utf-8"?><msg templateID="1" action="viewMultiMsg" serviceID="35" brief="[聊天记录]" m_resid="${resId}" m_fileName="${resId}" actionData="${resId}" tSum="2" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0"><item layout="1"><title size="34" color="#000000">聊天记录</title><title size="26" color="#777777">查看转发消息</title><summary size="26" color="#808080">查看转发消息</summary></item><source name="" icon="" action="" appid="-1"/></msg>`;
|
||||
const encodedXml = new TextEncoder().encode(xml);
|
||||
const payload = new Uint8Array(encodedXml.length + 1);
|
||||
payload[0] = 0x00;
|
||||
payload.set(encodedXml, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 35,
|
||||
template1: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||
const isGroup = ctx.groupId !== undefined;
|
||||
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||
if (!isGroup && !targetIdOrUid) {
|
||||
throw new Error('private image target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: isGroup ? 20 : 10,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build proto Elem objects from an array of MessageElements.
|
||||
* Supports: text, face, at, reply, json, xml, markdown, image.
|
||||
* Image elements trigger highway upload via the SendContext.
|
||||
*/
|
||||
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
|
||||
const result: ProtoElem[] = [];
|
||||
|
||||
for (const elem of elements) {
|
||||
switch (elem.type) {
|
||||
case 'text':
|
||||
if (elem.text) result.push(makeTextElem(elem.text));
|
||||
break;
|
||||
|
||||
case 'face':
|
||||
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
|
||||
break;
|
||||
|
||||
case 'at':
|
||||
result.push(makeMentionElem(elem));
|
||||
break;
|
||||
|
||||
case 'reply':
|
||||
if (elem.replySeq) result.push(makeReplyElem(elem));
|
||||
break;
|
||||
|
||||
case 'json':
|
||||
if (elem.text) result.push(makeJsonElem(elem));
|
||||
break;
|
||||
|
||||
case 'xml':
|
||||
if (elem.text) result.push(makeXmlElem(elem));
|
||||
break;
|
||||
|
||||
case 'markdown':
|
||||
if (elem.text) result.push(makeMarkdownElem(elem));
|
||||
break;
|
||||
|
||||
case 'image':
|
||||
if (ctx) {
|
||||
result.push(await makeImageElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] image send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'forward':
|
||||
if (elem.resId) result.push(makeForwardElem(elem));
|
||||
break;
|
||||
|
||||
case 'record':
|
||||
case 'video':
|
||||
console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,857 +0,0 @@
|
||||
// MsgPush packet handler — parses trpc.msg.olpush.OlPushService.MsgPush
|
||||
// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp
|
||||
|
||||
import { inflateSync } from 'zlib';
|
||||
import { protoDecode } from '../../protobuf/decode';
|
||||
import { WireMessage } from '../../protobuf/wire';
|
||||
import { PushMsgSchema } from '../proto/message';
|
||||
import {
|
||||
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
|
||||
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
|
||||
} from '../proto/element';
|
||||
import { FileExtraSchema } from '../proto/message';
|
||||
import {
|
||||
GroupChangeSchema, GroupAdminSchema, GroupJoinSchema,
|
||||
GroupInvitationSchema, GroupInviteSchema,
|
||||
FriendRequestSchema, FriendRecallSchema,
|
||||
GroupMuteSchema, NotifyMessageBodySchema,
|
||||
GeneralGrayTipInfoSchema, OperatorInfoSchema,
|
||||
} from '../proto/notify';
|
||||
import type { QQInfo } from '../qq-info';
|
||||
import type { PacketInfo } from '../../protocol/types';
|
||||
import type {
|
||||
QQEventVariant, MessageElement,
|
||||
FriendMessage, GroupMessage, TempMessage,
|
||||
GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent,
|
||||
FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent,
|
||||
FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent,
|
||||
} from '../events';
|
||||
import type { ProtoDecoded, ProtoSchema } from '../../protobuf/decode';
|
||||
|
||||
// --- PkgType enum ---
|
||||
const enum PkgType {
|
||||
ForwardFakePrivateMessage = 9,
|
||||
PrivateMessage = 166,
|
||||
GroupMessage = 82,
|
||||
TempMessage = 141,
|
||||
Event0x210 = 528,
|
||||
Event0x2DC = 732,
|
||||
PrivateRecordMessage = 208,
|
||||
PrivateFileMessage = 529,
|
||||
GroupRequestInvitationNotice = 525,
|
||||
GroupRequestJoinNotice = 84,
|
||||
GroupInviteNotice = 87,
|
||||
GroupAdminChangedNotice = 44,
|
||||
GroupMemberIncreaseNotice = 33,
|
||||
GroupMemberDecreaseNotice = 34,
|
||||
}
|
||||
|
||||
const enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
}
|
||||
|
||||
const enum Event0x210SubType {
|
||||
FriendRequestNotice = 35,
|
||||
FriendRecallNotice = 138,
|
||||
FriendPokeNotice = 290,
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
function makeImageUrl(origUrl: string): string {
|
||||
if (!origUrl) return '';
|
||||
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
|
||||
return 'http://gchat.qpic.cn' + origUrl;
|
||||
}
|
||||
|
||||
const HEX_CHARS = '0123456789ABCDEF';
|
||||
function bytesToHex(data: Uint8Array): string {
|
||||
let r = '';
|
||||
for (const b of data) { r += HEX_CHARS[b >> 4]; r += HEX_CHARS[b & 0x0f]; }
|
||||
return r;
|
||||
}
|
||||
|
||||
function decompressData(data: Uint8Array): string {
|
||||
if (!data || data.length === 0) return '';
|
||||
if (data[0] === 0x01 && data.length > 1) {
|
||||
try {
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1)));
|
||||
return inflated.toString('utf8');
|
||||
} catch { return ''; }
|
||||
}
|
||||
if (data[0] === 0x00 && data.length > 1) {
|
||||
return Buffer.from(data.subarray(1)).toString('utf8');
|
||||
}
|
||||
return Buffer.from(data).toString('utf8');
|
||||
}
|
||||
|
||||
function isNumericUin(value: string): boolean {
|
||||
return value.length > 0 && /^\d+$/.test(value);
|
||||
}
|
||||
|
||||
function parseU64OrZero(value: string): number {
|
||||
if (!value) return 0;
|
||||
const n = parseInt(value, 10);
|
||||
return isNaN(n) ? 0 : n;
|
||||
}
|
||||
|
||||
function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number {
|
||||
if (!uid) return fallback;
|
||||
if (isNumericUin(uid)) {
|
||||
const n = parseInt(uid, 10);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
if (groupId) {
|
||||
const uin = qqInfo.resolveGroupMemberUid(groupId, uid);
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
const uin = qqInfo.resolveUid(uid);
|
||||
if (uin !== null) return uin;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function decodeOperatorUid(bytes: Uint8Array): string {
|
||||
if (!bytes || bytes.length === 0) return '';
|
||||
const info = protoDecode(bytes, OperatorInfoSchema);
|
||||
if (info?.operatorField?.uid) return info.operatorField.uid;
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of params) {
|
||||
if (p.name !== undefined) map.set(p.name, p.value ?? '');
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
|
||||
for (const k of keys) {
|
||||
const v = map.get(k);
|
||||
if (v) return v;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
|
||||
if (content.length <= 7) return null;
|
||||
const lenBe = (content[5] << 8) | content[6];
|
||||
const lenLe = content[5] | (content[6] << 8);
|
||||
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
|
||||
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
|
||||
return content.subarray(7);
|
||||
}
|
||||
|
||||
// --- Element conversion ---
|
||||
|
||||
type ElemDecoded = ProtoDecoded<typeof import('../proto/element').ElemSchema>;
|
||||
|
||||
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const result: MessageElement[] = [];
|
||||
let skipNext = false;
|
||||
|
||||
for (const elem of elems) {
|
||||
if (skipNext) { skipNext = false; continue; }
|
||||
|
||||
// Reply / quote
|
||||
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
|
||||
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
|
||||
}
|
||||
|
||||
// Text (with possible @ detection)
|
||||
if (elem.text) {
|
||||
const t = elem.text;
|
||||
let mention: ProtoDecoded<typeof MentionExtraSchema> | null = null;
|
||||
if (t.pbReserve && t.pbReserve.length > 0) {
|
||||
mention = protoDecode(t.pbReserve, MentionExtraSchema);
|
||||
}
|
||||
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
|
||||
const hasMention = mention && (mention.type === 1 || mention.type === 2);
|
||||
|
||||
if (hasAttr6 || hasMention) {
|
||||
const me: MessageElement = { type: 'at', text: t.str ?? '' };
|
||||
if (hasAttr6) {
|
||||
const buf = t.attr6Buf!;
|
||||
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
|
||||
}
|
||||
if (hasMention && mention) {
|
||||
me.uid = mention.uid ?? '';
|
||||
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
|
||||
}
|
||||
result.push(me);
|
||||
} else {
|
||||
const text = t.str ?? '';
|
||||
if (text) result.push({ type: 'text', text });
|
||||
}
|
||||
}
|
||||
|
||||
// Face
|
||||
if (elem.face) {
|
||||
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
|
||||
}
|
||||
|
||||
// MarketFace
|
||||
if (elem.marketFace) {
|
||||
result.push({
|
||||
type: 'mface',
|
||||
text: elem.marketFace.faceName ?? '',
|
||||
faceId: elem.marketFace.tabId ?? 0,
|
||||
subType: elem.marketFace.subType ?? 0,
|
||||
});
|
||||
}
|
||||
|
||||
// NotOnlineImage (C2C image)
|
||||
if (elem.notOnlineImage) {
|
||||
const img = elem.notOnlineImage;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
const urlPath = img.origUrl || img.bigUrl || '';
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(urlPath),
|
||||
fileId: img.filePath ?? '',
|
||||
fileSize: img.fileLen ?? 0,
|
||||
width: img.picWidth ?? 0,
|
||||
height: img.picHeight ?? 0,
|
||||
subType: img.pbRes?.subType ?? 0,
|
||||
summary: img.pbRes?.summary ?? '[image]',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// CustomFace (group image)
|
||||
if (elem.customFace) {
|
||||
const img = elem.customFace;
|
||||
if (img.md5 && img.md5.length > 0) {
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(img.origUrl ?? ''),
|
||||
fileId: img.filePath ?? '',
|
||||
fileSize: img.size ?? 0,
|
||||
width: img.width ?? 0,
|
||||
height: img.height ?? 0,
|
||||
subType: img.pbRes?.subType ?? 0,
|
||||
summary: img.pbRes?.summary ?? '[image]',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// VideoFile
|
||||
if (elem.videoFile) {
|
||||
const v = elem.videoFile;
|
||||
result.push({
|
||||
type: 'video',
|
||||
fileId: v.fileUuid ?? '',
|
||||
fileName: v.fileName ?? '',
|
||||
fileSize: v.fileSize ?? 0,
|
||||
duration: v.fileTime ?? 0,
|
||||
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
|
||||
mediaNode: {
|
||||
fileUuid: v.fileUuid ?? '',
|
||||
info: {
|
||||
fileSize: v.fileSize ?? 0,
|
||||
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
|
||||
fileName: v.fileName ?? '',
|
||||
width: v.fileWidth ?? 0,
|
||||
height: v.fileHeight ?? 0,
|
||||
time: v.fileTime ?? 0,
|
||||
type: {
|
||||
type: 2,
|
||||
videoFormat: v.fileFormat ?? 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// GroupFile
|
||||
if (elem.groupFile) {
|
||||
const f = elem.groupFile;
|
||||
result.push({
|
||||
type: 'file',
|
||||
fileId: f.fileId ?? '',
|
||||
fileName: f.filename ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
});
|
||||
}
|
||||
|
||||
// TransElem type=24 (group file via transport)
|
||||
if (elem.transElem) {
|
||||
const te = elem.transElem;
|
||||
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
|
||||
const val = te.elemValue;
|
||||
const len = (val[1] << 8) | val[2];
|
||||
if (val.length >= 3 + len) {
|
||||
const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
|
||||
if (extra?.inner?.info) {
|
||||
const info = extra.inner.info;
|
||||
result.push({
|
||||
type: 'file',
|
||||
fileName: info.fileName ?? '',
|
||||
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
|
||||
fileId: info.fileId ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RichMsg
|
||||
if (elem.richMsg) {
|
||||
const rm = elem.richMsg;
|
||||
if (rm.template1 && rm.template1.length > 0) {
|
||||
const content = decompressData(rm.template1);
|
||||
if (content) {
|
||||
const svcId = rm.serviceId ?? 0;
|
||||
if (svcId === 35) {
|
||||
const pos = content.indexOf('m_resid="');
|
||||
if (pos !== -1) {
|
||||
const start = pos + 9;
|
||||
const end = content.indexOf('"', start);
|
||||
if (end !== -1) {
|
||||
result.push({ type: 'forward', resId: content.substring(start, end) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
} else if (svcId === 1) {
|
||||
result.push({ type: 'json', text: content });
|
||||
} else {
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LightApp
|
||||
if (elem.lightApp) {
|
||||
const la = elem.lightApp;
|
||||
if (la.data && la.data.length > 0) {
|
||||
const content = decompressData(la.data);
|
||||
if (content) result.push({ type: 'json', text: content });
|
||||
}
|
||||
}
|
||||
|
||||
// CommonElem
|
||||
if (elem.commonElem) {
|
||||
const ce = elem.commonElem;
|
||||
const svcType = ce.serviceType ?? 0;
|
||||
const bizType = ce.businessType ?? 0;
|
||||
|
||||
if (svcType === 2) {
|
||||
// Poke
|
||||
result.push({ type: 'poke', subType: bizType });
|
||||
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
|
||||
// Flash image
|
||||
const pb = ce.pbElem;
|
||||
let pos = 1;
|
||||
let length = 0, shift = 0;
|
||||
while (pos < pb.length) {
|
||||
const b = pb[pos++];
|
||||
length |= (b & 0x7f) << shift;
|
||||
shift += 7;
|
||||
if ((b & 0x80) === 0) break;
|
||||
}
|
||||
if (pos + length <= pb.length) {
|
||||
const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
|
||||
if (img) {
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: img.filePath ?? '',
|
||||
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
|
||||
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
|
||||
};
|
||||
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + bytesToHex(img.picMd5) + '/0';
|
||||
}
|
||||
result.push(me);
|
||||
}
|
||||
}
|
||||
skipNext = true;
|
||||
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
|
||||
// NTQQ new protocol image/record/video
|
||||
const info = protoDecode(ce.pbElem, MsgInfoSchema);
|
||||
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
|
||||
const body = info.msgInfoBody[0];
|
||||
if (body.index?.info) {
|
||||
const idx = body.index;
|
||||
const fi = idx.info!;
|
||||
|
||||
if (bizType === 10 || bizType === 20) {
|
||||
// Image
|
||||
let url = '';
|
||||
if (body.picture) {
|
||||
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
|
||||
const path = body.picture.urlPath ?? '';
|
||||
if (path) {
|
||||
url = 'https://' + domain + path;
|
||||
if (body.picture.ext?.originalParameter) {
|
||||
url += body.picture.ext.originalParameter;
|
||||
}
|
||||
}
|
||||
}
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: fi.fileName ?? '',
|
||||
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
|
||||
height: fi.height ?? 0, imageUrl: url,
|
||||
};
|
||||
if (info.extBizInfo?.pic) {
|
||||
me.subType = info.extBizInfo.pic.bizType ?? 0;
|
||||
me.summary = info.extBizInfo.pic.textSummary || '[image]';
|
||||
}
|
||||
result.push(me);
|
||||
} else if (bizType === 12 || bizType === 22) {
|
||||
// Record
|
||||
result.push({
|
||||
type: 'record', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
mediaNode: {
|
||||
fileUuid: idx.fileUuid,
|
||||
storeId: idx.storeId,
|
||||
uploadTime: idx.uploadTime,
|
||||
ttl: idx.ttl,
|
||||
subType: idx.subType,
|
||||
info: {
|
||||
fileSize: fi.fileSize,
|
||||
fileHash: fi.fileHash,
|
||||
fileSha1: fi.fileSha1,
|
||||
fileName: fi.fileName,
|
||||
width: fi.width,
|
||||
height: fi.height,
|
||||
time: fi.time,
|
||||
original: fi.original,
|
||||
type: {
|
||||
type: fi.type?.type,
|
||||
picFormat: fi.type?.picFormat,
|
||||
videoFormat: fi.type?.videoFormat,
|
||||
voiceFormat: fi.type?.voiceFormat,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (bizType === 11 || bizType === 21) {
|
||||
// Video
|
||||
result.push({
|
||||
type: 'video', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
|
||||
duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
mediaNode: {
|
||||
fileUuid: idx.fileUuid,
|
||||
storeId: idx.storeId,
|
||||
uploadTime: idx.uploadTime,
|
||||
ttl: idx.ttl,
|
||||
subType: idx.subType,
|
||||
info: {
|
||||
fileSize: fi.fileSize,
|
||||
fileHash: fi.fileHash,
|
||||
fileSha1: fi.fileSha1,
|
||||
fileName: fi.fileName,
|
||||
width: fi.width,
|
||||
height: fi.height,
|
||||
time: fi.time,
|
||||
original: fi.original,
|
||||
type: {
|
||||
type: fi.type?.type,
|
||||
picFormat: fi.type?.picFormat,
|
||||
videoFormat: fi.type?.videoFormat,
|
||||
voiceFormat: fi.type?.voiceFormat,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (svcType === 33 && ce.pbElem) {
|
||||
// Small face
|
||||
const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
|
||||
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
|
||||
} else if (svcType === 37 && ce.pbElem) {
|
||||
// Big face
|
||||
const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
|
||||
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
|
||||
skipNext = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function extractRichtextExtras(
|
||||
rt: ProtoDecoded<typeof import('../proto/message').RichTextSchema>,
|
||||
elements: MessageElement[],
|
||||
isGroup = false
|
||||
): void {
|
||||
// Ptt (voice)
|
||||
if (rt.ptt) {
|
||||
const p = rt.ptt;
|
||||
const me: MessageElement = {
|
||||
type: 'record', fileName: p.fileName ?? '',
|
||||
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
|
||||
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
|
||||
};
|
||||
if (isGroup && (p.fileId ?? 0n) !== 0n) {
|
||||
me.fileId = p.groupFileKey ?? '';
|
||||
} else {
|
||||
if (p.fileUuid && p.fileUuid.length > 0) {
|
||||
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
|
||||
}
|
||||
}
|
||||
me.mediaNode = {
|
||||
fileUuid: me.fileId ?? '',
|
||||
info: {
|
||||
fileSize: p.fileSize ?? 0,
|
||||
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
|
||||
fileName: p.fileName ?? '',
|
||||
time: p.time ?? 0,
|
||||
type: {
|
||||
type: 3,
|
||||
voiceFormat: p.format ?? 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
elements.push(me);
|
||||
}
|
||||
|
||||
// NotOnlineFile (C2C file)
|
||||
if (rt.notOnlineFile) {
|
||||
const f = rt.notOnlineFile;
|
||||
elements.push({
|
||||
type: 'file', fileId: f.fileUuid ?? '',
|
||||
fileName: f.fileName ?? '',
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
fileHash: f.fileHash ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
|
||||
const extra = protoDecode(msgContent, FileExtraSchema);
|
||||
if (!extra?.file) return;
|
||||
const f = extra.file;
|
||||
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
|
||||
elements.push({
|
||||
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
|
||||
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||
fileHash: f.fileHash,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- Main handler ---
|
||||
|
||||
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] {
|
||||
if (pkt.body.length === 0) return [];
|
||||
|
||||
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
|
||||
if (!push?.message) return [];
|
||||
|
||||
const msg = push.message;
|
||||
if (!msg.contentHead) return [];
|
||||
|
||||
const head = msg.contentHead;
|
||||
const msgType = head.msgType ?? 0;
|
||||
const subType = head.subType ?? 0;
|
||||
const sequence = head.sequence ?? 0;
|
||||
const timestamp = head.timestamp ?? 0;
|
||||
const msgId = head.msgId ?? 0;
|
||||
|
||||
let fromUin = 0;
|
||||
let fromUid = '';
|
||||
if (msg.responseHead) {
|
||||
fromUin = msg.responseHead.fromUin ?? 0;
|
||||
fromUid = msg.responseHead.fromUid ?? '';
|
||||
}
|
||||
|
||||
let selfUin = 0;
|
||||
if (pkt.uin) {
|
||||
const n = parseInt(pkt.uin, 10);
|
||||
if (!isNaN(n)) selfUin = n;
|
||||
}
|
||||
|
||||
const content = (msg.body?.msgContent) ? msg.body.msgContent : new Uint8Array(0);
|
||||
|
||||
const buildElements = (isGroup: boolean): MessageElement[] => {
|
||||
const elements: MessageElement[] = [];
|
||||
if (msg.body?.richText) {
|
||||
const rt = msg.body.richText;
|
||||
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
|
||||
extractRichtextExtras(rt, elements, isGroup);
|
||||
}
|
||||
if (msg.body?.msgContent && msg.body.msgContent.length > 0) {
|
||||
extractMsgContent(msg.body.msgContent, elements);
|
||||
}
|
||||
return elements;
|
||||
};
|
||||
|
||||
// --- Switch on msgType ---
|
||||
|
||||
switch (msgType as PkgType) {
|
||||
case PkgType.GroupMemberIncreaseNotice: {
|
||||
const change = protoDecode(content, GroupChangeSchema);
|
||||
if (!change) return [];
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join', time: timestamp, selfUin,
|
||||
groupId: change.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
|
||||
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
|
||||
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
case PkgType.GroupMemberDecreaseNotice: {
|
||||
const change = protoDecode(content, GroupChangeSchema);
|
||||
if (!change) return [];
|
||||
const dt = change.decreaseType ?? 0;
|
||||
const ev: GroupMemberLeave = {
|
||||
kind: 'group_member_leave', time: timestamp, selfUin,
|
||||
groupId: change.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
|
||||
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
|
||||
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
|
||||
isKick: dt !== 0 && dt !== 130,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
case PkgType.GroupAdminChangedNotice: {
|
||||
const admin = protoDecode(content, GroupAdminSchema);
|
||||
if (!admin?.body) return [];
|
||||
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
|
||||
if (!extra) return [];
|
||||
const ev: GroupAdminEvent = {
|
||||
kind: 'group_admin', time: timestamp, selfUin,
|
||||
groupId: admin.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
|
||||
set: admin.body.extraEnable !== undefined,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
case PkgType.GroupRequestJoinNotice: {
|
||||
const join = protoDecode(content, GroupJoinSchema);
|
||||
if (!join) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: join.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
|
||||
subType: 'add', message: '',
|
||||
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
case PkgType.GroupRequestInvitationNotice: {
|
||||
const invitation = protoDecode(content, GroupInvitationSchema);
|
||||
if (!invitation?.info?.inner) return [];
|
||||
const inner = invitation.info.inner;
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: inner.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
|
||||
subType: 'invite', message: '',
|
||||
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
case PkgType.GroupInviteNotice: {
|
||||
const invite = protoDecode(content, GroupInviteSchema);
|
||||
if (!invite) return [];
|
||||
const ev: GroupInviteEvent = {
|
||||
kind: 'group_invite', time: timestamp, selfUin,
|
||||
groupId: invite.groupUin ?? 0,
|
||||
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
|
||||
subType: 'invite', message: '',
|
||||
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
case PkgType.Event0x210: {
|
||||
switch (subType as Event0x210SubType) {
|
||||
case Event0x210SubType.FriendRequestNotice: {
|
||||
const request = protoDecode(content, FriendRequestSchema);
|
||||
if (!request?.info) return [];
|
||||
const sourceUid = request.info.newSource || request.info.sourceUid || '';
|
||||
const ev: FriendRequestEvent = {
|
||||
kind: 'friend_request', time: timestamp, selfUin,
|
||||
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
|
||||
message: request.info.message ?? '', flag: sourceUid,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
case Event0x210SubType.FriendRecallNotice: {
|
||||
const recall = protoDecode(content, FriendRecallSchema);
|
||||
if (!recall?.info) return [];
|
||||
const ev: FriendRecall = {
|
||||
kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin,
|
||||
userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin),
|
||||
msgSeq: recall.info.clientSequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
case Event0x210SubType.FriendPokeNotice: {
|
||||
const grayTip = protoDecode(content, GeneralGrayTipInfoSchema);
|
||||
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: FriendPokeEvent = {
|
||||
kind: 'friend_poke', time: timestamp, selfUin,
|
||||
userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case PkgType.Event0x2DC: {
|
||||
switch (subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: {
|
||||
const mute = protoDecode(content, GroupMuteSchema);
|
||||
if (!mute?.data?.state) return [];
|
||||
const duration = mute.data.state.duration ?? 0;
|
||||
const ev: GroupMuteEvent = {
|
||||
kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin,
|
||||
groupId: mute.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
|
||||
userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
case Event0x2DCSubType.GroupRecallNotice: {
|
||||
const payload = unwrapGroupNotifyPayload(content);
|
||||
if (!payload) return [];
|
||||
const notify = protoDecode(payload, NotifyMessageBodySchema);
|
||||
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
|
||||
const recalled = notify.recall.recallMessages[0];
|
||||
const ev: GroupRecallEvent = {
|
||||
kind: 'group_recall', time: recalled.time ?? timestamp, selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0,
|
||||
notify.recall.operatorUid || notify.operatorUid || '', fromUin),
|
||||
authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
|
||||
msgSeq: recalled.sequence ?? 0,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: {
|
||||
const payload = unwrapGroupNotifyPayload(content);
|
||||
if (!payload) return [];
|
||||
const notify = protoDecode(payload, NotifyMessageBodySchema);
|
||||
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
|
||||
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
|
||||
const actor = findTemplateValue(templates, 'uin_str1');
|
||||
const target = findTemplateValue(templates, 'uin_str2');
|
||||
const ev: GroupPokeEvent = {
|
||||
kind: 'group_poke', time: timestamp, selfUin,
|
||||
groupId: notify.groupUin ?? 0,
|
||||
userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||
targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
case Event0x2DCSubType.GroupEssenceNotice: {
|
||||
const payload = unwrapGroupNotifyPayload(content);
|
||||
if (!payload) return [];
|
||||
const notify = protoDecode(payload, NotifyMessageBodySchema);
|
||||
if (!notify?.essenceMessage) return [];
|
||||
const essence = notify.essenceMessage;
|
||||
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
|
||||
const ev: GroupEssenceEvent = {
|
||||
kind: 'group_essence', time: essence.timestamp ?? timestamp, selfUin,
|
||||
groupId: essence.groupUin ?? notify.groupUin ?? 0,
|
||||
senderUin: essence.memberUin ?? 0,
|
||||
operatorUin: essence.operatorUin ?? fromUin,
|
||||
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
|
||||
random: essence.random ?? 0,
|
||||
set: setFlag === 1,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Message types ---
|
||||
|
||||
if (msgType === PkgType.GroupMessage) {
|
||||
const ev: GroupMessage = {
|
||||
kind: 'group_message', time: timestamp, selfUin,
|
||||
senderUin: fromUin, msgSeq: sequence,
|
||||
msgId: msgId & 0x7FFFFFFF,
|
||||
elements: buildElements(true),
|
||||
groupId: 0, senderNick: '', senderCard: '', senderRole: '',
|
||||
};
|
||||
if (msg.responseHead?.grp) {
|
||||
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = msg.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
const member = qqInfo.findGroupMember(ev.groupId, fromUin);
|
||||
if (member) {
|
||||
if (!ev.senderNick) ev.senderNick = member.nickname;
|
||||
ev.senderCard = member.card;
|
||||
ev.senderRole = member.role;
|
||||
}
|
||||
return [ev];
|
||||
}
|
||||
|
||||
if (msgType === PkgType.TempMessage) {
|
||||
const ev: TempMessage = {
|
||||
kind: 'temp_message', time: timestamp, selfUin,
|
||||
senderUin: fromUin, msgSeq: sequence,
|
||||
elements: buildElements(false),
|
||||
groupId: 0, senderNick: '',
|
||||
};
|
||||
if (msg.responseHead?.grp) {
|
||||
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = msg.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
if (!ev.senderNick) {
|
||||
const friend = qqInfo.findFriend(fromUin);
|
||||
if (friend) ev.senderNick = friend.nickname;
|
||||
}
|
||||
return [ev];
|
||||
}
|
||||
|
||||
if (msgType === PkgType.PrivateMessage ||
|
||||
msgType === PkgType.ForwardFakePrivateMessage ||
|
||||
msgType === PkgType.PrivateRecordMessage ||
|
||||
msgType === PkgType.PrivateFileMessage) {
|
||||
const ev: FriendMessage = {
|
||||
kind: 'friend_message', time: timestamp, selfUin,
|
||||
senderUin: fromUin, msgSeq: sequence,
|
||||
msgId: msgId & 0x7FFFFFFF,
|
||||
elements: buildElements(false),
|
||||
senderNick: '',
|
||||
};
|
||||
if (msg.responseHead?.forward?.friendName) {
|
||||
ev.senderNick = msg.responseHead.forward.friendName;
|
||||
}
|
||||
const friend = qqInfo.findFriend(fromUin);
|
||||
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48)));
|
||||
return [];
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
// Image upload pipeline: load image, OIDB upload request, highway upload, build message element.
|
||||
// Port of src/bridge/src/highway_upload_req.cpp + highway_client.cpp (image parts)
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { protoEncode, protoDecode } from '../../protobuf/decode';
|
||||
import { makeOidbBaseSchema } from '../proto/oidb';
|
||||
import {
|
||||
NTV2UploadRichMediaReqSchema,
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
EncodableMediaMsgInfoSchema,
|
||||
} from '../proto/highway';
|
||||
import {
|
||||
loadBinarySource, computeHashes, detectImageFormat,
|
||||
} from './utils';
|
||||
import {
|
||||
fetchHighwaySession, uploadHighwayHttp, buildHighwayExtend,
|
||||
PRIVATE_IMAGE_CMD_ID, GROUP_IMAGE_CMD_ID,
|
||||
} from './highway-client';
|
||||
|
||||
interface ImageData {
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
summary: string;
|
||||
subType: number;
|
||||
width: number;
|
||||
height: number;
|
||||
picFormat: number;
|
||||
}
|
||||
|
||||
function loadImage(element: MessageElement): Promise<ImageData> {
|
||||
return loadImageFromSource(
|
||||
element.url || element.fileId || '',
|
||||
element.fileName ?? '',
|
||||
element.subType ?? 0,
|
||||
element.summary ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
|
||||
const loaded = await loadBinarySource(source, 'image');
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fmt = detectImageFormat(loaded.bytes);
|
||||
|
||||
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
|
||||
const ext = extMap[fmt.format] ?? '.jpg';
|
||||
|
||||
let finalName = fileName || loaded.fileName;
|
||||
if (!finalName) finalName = hashes.md5Hex + ext;
|
||||
|
||||
return {
|
||||
bytes: loaded.bytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: finalName,
|
||||
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
|
||||
subType,
|
||||
width: fmt.width,
|
||||
height: fmt.height,
|
||||
picFormat: fmt.format,
|
||||
};
|
||||
}
|
||||
|
||||
async function startImageUpload(bridge: Bridge, isGroup: boolean, targetIdOrUid: string | number, image: ImageData): Promise<any> {
|
||||
const body: any = {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 1,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: image.bytes.length,
|
||||
fileHash: image.md5Hex,
|
||||
fileSha1: image.sha1Hex,
|
||||
fileName: image.fileName,
|
||||
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
time: 0,
|
||||
original: 1,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
tryFastUploadCompleted: true,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: BigInt(Math.floor(Math.random() * 0x7FFFFFFFFFFFFFFF)),
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
pic: {
|
||||
bizType: image.subType,
|
||||
textSummary: image.summary,
|
||||
...(isGroup
|
||||
? { reserveTroop: { subType: image.subType } }
|
||||
: { reserveC2c: { subType: image.subType } }),
|
||||
},
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array(0),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
bytesGeneralFlags: new Uint8Array(0),
|
||||
},
|
||||
},
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const oidbCmd = isGroup ? 0x11C4 : 0x11C5;
|
||||
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100';
|
||||
|
||||
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
|
||||
const request = protoEncode({
|
||||
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
|
||||
}, baseSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'image upload request failed');
|
||||
}
|
||||
|
||||
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
|
||||
const resp: any = protoDecode(result.responseData, respBaseSchema);
|
||||
if (!resp) throw new Error('failed to decode upload response');
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody = resp.body;
|
||||
if (!uploadBody) throw new Error('upload response body missing');
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
throw new Error(uploadBody.respHead.message ?? 'image upload failed');
|
||||
}
|
||||
return uploadBody.upload;
|
||||
}
|
||||
|
||||
function finalizeImageMsgInfo(upload: any, image: ImageData): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
|
||||
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
|
||||
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||
}));
|
||||
|
||||
const extBizInfo: any = {};
|
||||
if (upload.msgInfo.extBizInfo?.pic) {
|
||||
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
|
||||
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? image.subType;
|
||||
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? image.summary;
|
||||
} else {
|
||||
extBizInfo.pic = { bizType: image.subType, textSummary: image.summary };
|
||||
}
|
||||
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
|
||||
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
|
||||
if (upload.msgInfo.extBizInfo?.busiType !== undefined) extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
|
||||
|
||||
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image and return the encoded MsgInfo bytes to embed in a CommonElem.
|
||||
*/
|
||||
export async function uploadImageMsgInfo(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const image = await loadImage(element);
|
||||
const upload = await startImageUpload(bridge, isGroup, targetIdOrUid, image);
|
||||
|
||||
// Upload binary if uKey is present (not fast-uploaded)
|
||||
const uKey = upload?.uKey ?? '';
|
||||
if (uKey && upload?.msgInfo) {
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], image.sha1);
|
||||
const commandId = isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID;
|
||||
await uploadHighwayHttp(bridge, session, commandId, image.bytes, image.md5, extend);
|
||||
}
|
||||
|
||||
return finalizeImageMsgInfo(upload, image);
|
||||
}
|
||||
@@ -1,21 +1,13 @@
|
||||
// BridgeManager — manages per-UIN Bridge sessions.
|
||||
// Wires NtqqHandler packets to appropriate Bridge instances.
|
||||
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
|
||||
|
||||
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { Bridge } from './bridge';
|
||||
import { QQInfo } from './qq-info';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
export type BridgeEventCallback = (uin: string, event: QQEventVariant) => void;
|
||||
|
||||
interface QQSession {
|
||||
qqInfo: QQInfo;
|
||||
bridge: Bridge;
|
||||
}
|
||||
|
||||
@@ -28,15 +20,9 @@ export class BridgeManager {
|
||||
|
||||
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||
private onBridgeEvent_: BridgeEventCallback | null = null;
|
||||
|
||||
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||
setEventCallback(cb: BridgeEventCallback): void { this.onBridgeEvent_ = cb; }
|
||||
|
||||
bind(ntqq: NtqqHandler): void {
|
||||
ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt));
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
this.pidPacketClients_.delete(pid);
|
||||
@@ -52,6 +38,7 @@ export class BridgeManager {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||
session.bridge.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,12 +60,12 @@ export class BridgeManager {
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onPacket(pkt: PacketInfo): void {
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
|
||||
const uin = pkt.uin;
|
||||
|
||||
@@ -98,7 +85,7 @@ export class BridgeManager {
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,16 +97,13 @@ export class BridgeManager {
|
||||
let session = this.sessions_.get(uin);
|
||||
if (session) return { session, created: false };
|
||||
|
||||
const qqInfo = new QQInfo(uin);
|
||||
const bridge = new Bridge(qqInfo);
|
||||
session = { qqInfo, bridge };
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin));
|
||||
session = { bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Wire event callback
|
||||
bridge.setEventCallback((event) => {
|
||||
if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event);
|
||||
});
|
||||
|
||||
// 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 };
|
||||
}
|
||||
|
||||
@@ -127,7 +111,7 @@ export class BridgeManager {
|
||||
return this.sessions_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> {
|
||||
get sessions(): Map<string, { bridge: Bridge }> {
|
||||
return this.sessions_;
|
||||
}
|
||||
}
|
||||
@@ -1,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,354 +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;
|
||||
|
||||
export const NTV2PicReserveC2CSchema = {
|
||||
subType: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PicReserveTroopSchema = {
|
||||
subType: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PicExtBizInfoSchema = {
|
||||
bizType: { field: 1, type: 'uint32' as const },
|
||||
textSummary: { field: 2, type: 'string' as const },
|
||||
reserveC2c: { field: 11, type: 'message' as const, schema: NTV2PicReserveC2CSchema },
|
||||
reserveTroop: { field: 12, type: 'message' as const, schema: NTV2PicReserveTroopSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2VideoExtBizInfoSchema = {
|
||||
bytesPbReserve: { field: 3, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PttExtBizInfoSchema = {
|
||||
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 NTV2ExtBizInfoSchema = {
|
||||
pic: { field: 1, type: 'message' as const, schema: NTV2PicExtBizInfoSchema },
|
||||
video: { field: 2, type: 'message' as const, schema: NTV2VideoExtBizInfoSchema },
|
||||
ptt: { field: 3, type: 'message' as const, schema: NTV2PttExtBizInfoSchema },
|
||||
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;
|
||||
@@ -1,865 +0,0 @@
|
||||
// Proto schemas for OIDB action requests.
|
||||
// Port of src/bridge/include/bridge/proto/oidb.h (action-related structs)
|
||||
// and src/bridge/src/bridge.cpp (recall message structs)
|
||||
|
||||
import type { ProtoSchema } from '../../protobuf/decode';
|
||||
|
||||
// --- 0x1253_1: Mute group member ---
|
||||
|
||||
export const OidbMuteMemberBodySchema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
duration: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbMuteMemberSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
type: { field: 2, type: 'uint32' as const },
|
||||
body: { field: 3, type: 'message' as const, schema: OidbMuteMemberBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x89A_0: Mute group all ---
|
||||
|
||||
export const OidbMuteAllStateSchema = {
|
||||
state: { field: 17, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbMuteAllSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
muteState: { field: 2, type: 'message' as const, schema: OidbMuteAllStateSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x8A0_1: Kick group member ---
|
||||
|
||||
export const OidbKickMemberSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
targetUid: { field: 3, type: 'string' as const },
|
||||
rejectAddRequest:{ field: 4, type: 'bool' as const },
|
||||
reason: { field: 5, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x1097_1: Leave group ---
|
||||
|
||||
export const OidbLeaveGroupSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xB5D_44: Friend add request ---
|
||||
|
||||
export const OidbFriendRequestActionSchema = {
|
||||
accept: { field: 1, type: 'uint32' as const },
|
||||
targetUid: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x126B_0: Delete friend ---
|
||||
|
||||
export const OidbDeleteFriendField2Field3Schema = {
|
||||
field1: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbDeleteFriendField2Schema = {
|
||||
field1: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'message' as const, schema: OidbDeleteFriendField2Field3Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbDeleteFriendField1Schema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
field2: { field: 2, type: 'message' as const, schema: OidbDeleteFriendField2Schema },
|
||||
block: { field: 3, type: 'bool' as const },
|
||||
field4: { field: 4, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbDeleteFriendSchema = {
|
||||
field1: { field: 1, type: 'message' as const, schema: OidbDeleteFriendField1Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x10C8: Group request action ---
|
||||
|
||||
export const OidbGroupRequestBodySchema = {
|
||||
sequence: { field: 1, type: 'uint64' as const },
|
||||
eventType: { field: 2, type: 'uint32' as const },
|
||||
groupUin: { field: 3, type: 'uint32' as const },
|
||||
message: { field: 4, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupRequestActionSchema = {
|
||||
accept: { field: 1, type: 'uint32' as const },
|
||||
body: { field: 2, type: 'message' as const, schema: OidbGroupRequestBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xED3_1: Poke ---
|
||||
|
||||
export const OidbPokeSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
groupUin: { field: 2, type: 'uint32' as const },
|
||||
friendUin: { field: 5, type: 'uint32' as const },
|
||||
ext: { field: 6, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xEAC: Group essence ---
|
||||
|
||||
export const OidbEssenceSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
sequence: { field: 2, type: 'uint32' as const },
|
||||
random: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x1096_1: Set group admin ---
|
||||
|
||||
export const OidbSetAdminSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
isAdmin: { field: 3, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x8FC_3: Set group card (rename member) ---
|
||||
|
||||
export const OidbRenameMemberBodySchema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
targetName: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbRenameMemberSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
body: { field: 2, type: 'message' as const, schema: OidbRenameMemberBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x89A_15: Rename group ---
|
||||
|
||||
export const OidbRenameGroupBodySchema = {
|
||||
targetName: { field: 1, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbRenameGroupSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
body: { field: 2, type: 'message' as const, schema: OidbRenameGroupBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x8FC_2: Set group special title ---
|
||||
|
||||
export const OidbSpecialTitleBodySchema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
specialTitle:{ field: 5, type: 'string' as const },
|
||||
expireTime: { field: 6, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSpecialTitleSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
body: { field: 2, type: 'message' as const, schema: OidbSpecialTitleBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x7E5_104: Send like ---
|
||||
|
||||
export const OidbLikeSchema = {
|
||||
targetUin: { field: 1, type: 'uint32' as const },
|
||||
count: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x10C0_1 / 0x10C0_2: Group request list ---
|
||||
|
||||
export const OidbGroupRequestListSchema = {
|
||||
count: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xFE1_2: User profile info ---
|
||||
|
||||
export const OidbUserInfoKeySchema = {
|
||||
key: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbUserInfoRequestSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbTwoNumberSchema = {
|
||||
number1: { field: 1, type: 'uint32' as const },
|
||||
number2: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbBytePropertySchema = {
|
||||
code: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbUserInfoPropertySchema = {
|
||||
numberProperties: { field: 1, type: 'repeated_message' as const, schema: OidbTwoNumberSchema },
|
||||
bytesProperties: { field: 2, type: 'repeated_message' as const, schema: OidbBytePropertySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbUserInfoResponseBodySchema = {
|
||||
uid: { field: 1, type: 'string' as const },
|
||||
properties: { field: 2, type: 'message' as const, schema: OidbUserInfoPropertySchema },
|
||||
uin: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbUserInfoResponseSchema = {
|
||||
body: { field: 1, type: 'message' as const, schema: OidbUserInfoResponseBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const AvatarInfoSchema = {
|
||||
url: { field: 5, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- FD4_1: Friend list request body fields ---
|
||||
|
||||
export const OidbFriendListNumberSchema = {
|
||||
numbers: { field: 1, type: 'repeated_uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbFriendListBodyItemSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
number: { field: 2, type: 'message' as const, schema: OidbFriendListNumberSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbFriendListNextUinSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbFriendListRequestSchema = {
|
||||
friendCount: { field: 2, type: 'uint32' as const },
|
||||
field4: { field: 4, type: 'uint32' as const },
|
||||
nextUin: { field: 5, type: 'message' as const, schema: OidbFriendListNextUinSchema },
|
||||
field6: { field: 6, type: 'uint32' as const },
|
||||
field7: { field: 7, type: 'uint32' as const },
|
||||
body: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendListBodyItemSchema },
|
||||
field10002: { field: 10002, type: 'repeated_uint32' as const },
|
||||
field10003: { field: 10003, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- FE5_2: Group list request body (config fields) ---
|
||||
|
||||
export const OidbGroupListConfig1Schema = {
|
||||
groupOwner: { field: 1, type: 'bool' as const },
|
||||
field2: { field: 2, type: 'bool' as const },
|
||||
memberMax: { field: 3, type: 'bool' as const },
|
||||
memberCount: { field: 4, type: 'bool' as const },
|
||||
groupName: { field: 5, type: 'bool' as const },
|
||||
field8: { field: 8, type: 'bool' as const },
|
||||
field9: { field: 9, type: 'bool' as const },
|
||||
field10: { field: 10, type: 'bool' as const },
|
||||
field11: { field: 11, type: 'bool' as const },
|
||||
field12: { field: 12, type: 'bool' as const },
|
||||
field13: { field: 13, type: 'bool' as const },
|
||||
field14: { field: 14, type: 'bool' as const },
|
||||
field15: { field: 15, type: 'bool' as const },
|
||||
field16: { field: 16, type: 'bool' as const },
|
||||
field17: { field: 17, type: 'bool' as const },
|
||||
field18: { field: 18, type: 'bool' as const },
|
||||
question: { field: 19, type: 'bool' as const },
|
||||
field20: { field: 20, type: 'bool' as const },
|
||||
field22: { field: 22, type: 'bool' as const },
|
||||
field23: { field: 23, type: 'bool' as const },
|
||||
field24: { field: 24, type: 'bool' as const },
|
||||
field25: { field: 25, type: 'bool' as const },
|
||||
field26: { field: 26, type: 'bool' as const },
|
||||
field27: { field: 27, type: 'bool' as const },
|
||||
field28: { field: 28, type: 'bool' as const },
|
||||
field29: { field: 29, type: 'bool' as const },
|
||||
field30: { field: 30, type: 'bool' as const },
|
||||
field31: { field: 31, type: 'bool' as const },
|
||||
field32: { field: 32, type: 'bool' as const },
|
||||
field5001: { field: 5001, type: 'bool' as const },
|
||||
field5002: { field: 5002, type: 'bool' as const },
|
||||
field5003: { field: 5003, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupListConfig2Schema = {
|
||||
field1: { field: 1, type: 'bool' as const },
|
||||
field2: { field: 2, type: 'bool' as const },
|
||||
field3: { field: 3, type: 'bool' as const },
|
||||
field4: { field: 4, type: 'bool' as const },
|
||||
field5: { field: 5, type: 'bool' as const },
|
||||
field6: { field: 6, type: 'bool' as const },
|
||||
field7: { field: 7, type: 'bool' as const },
|
||||
field8: { field: 8, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupListConfig3Schema = {
|
||||
field5: { field: 5, type: 'bool' as const },
|
||||
field6: { field: 6, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupListConfigSchema = {
|
||||
config1: { field: 1, type: 'message' as const, schema: OidbGroupListConfig1Schema },
|
||||
config2: { field: 2, type: 'message' as const, schema: OidbGroupListConfig2Schema },
|
||||
config3: { field: 3, type: 'message' as const, schema: OidbGroupListConfig3Schema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupListRequestSchema = {
|
||||
config: { field: 1, type: 'message' as const, schema: OidbGroupListConfigSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- FE7_3: Group member list request body ---
|
||||
|
||||
export const OidbGroupMemberListBodySchema = {
|
||||
memberName: { field: 10, type: 'bool' as const },
|
||||
memberCard: { field: 11, type: 'bool' as const },
|
||||
level: { field: 12, type: 'bool' as const },
|
||||
field13: { field: 13, type: 'bool' as const },
|
||||
field16: { field: 16, type: 'bool' as const },
|
||||
specialTitle: { field: 17, type: 'bool' as const },
|
||||
field18: { field: 18, type: 'bool' as const },
|
||||
field20: { field: 20, type: 'bool' as const },
|
||||
field21: { field: 21, type: 'bool' as const },
|
||||
joinTimestamp: { field: 100, type: 'bool' as const },
|
||||
lastMsgTimestamp: { field: 101, type: 'bool' as const },
|
||||
shutUpTimestamp: { field: 102, type: 'bool' as const },
|
||||
field103: { field: 103, type: 'bool' as const },
|
||||
field104: { field: 104, type: 'bool' as const },
|
||||
field105: { field: 105, type: 'bool' as const },
|
||||
field106: { field: 106, type: 'bool' as const },
|
||||
permission: { field: 107, type: 'bool' as const },
|
||||
field200: { field: 200, type: 'bool' as const },
|
||||
field201: { field: 201, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupMemberListRequestSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
body: { field: 4, type: 'message' as const, schema: OidbGroupMemberListBodySchema },
|
||||
token: { field: 15, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) ---
|
||||
|
||||
export const GroupRecallInfoSchema = {
|
||||
sequence: { field: 1, type: 'uint32' as const },
|
||||
random: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupRecallSettingsSchema = {
|
||||
field1: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupRecallRequestSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
groupUin: { field: 2, type: 'uint32' as const },
|
||||
info: { field: 3, type: 'message' as const, schema: GroupRecallInfoSchema },
|
||||
settings: { field: 4, type: 'message' as const, schema: GroupRecallSettingsSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) ---
|
||||
|
||||
export const C2CRecallInfoSchema = {
|
||||
clientSequence: { field: 1, type: 'uint32' as const },
|
||||
random: { field: 2, type: 'uint32' as const },
|
||||
messageId: { field: 3, type: 'uint64' as const },
|
||||
timestamp: { field: 4, type: 'uint32' as const },
|
||||
field5: { field: 5, type: 'uint32' as const },
|
||||
messageSequence: { field: 6, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const C2CRecallSettingsSchema = {
|
||||
field1: { field: 1, type: 'bool' as const },
|
||||
field2: { field: 2, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const C2CRecallRequestSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
targetUid:{ field: 3, type: 'string' as const },
|
||||
info: { field: 4, type: 'message' as const, schema: C2CRecallInfoSchema },
|
||||
settings: { field: 5, type: 'message' as const, schema: C2CRecallSettingsSchema },
|
||||
field6: { field: 6, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x9082_1: Set group reaction ---
|
||||
|
||||
export const OidbGroupReactionSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
sequence: { field: 2, type: 'uint32' as const },
|
||||
code: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x6D8_1: Group file list ---
|
||||
|
||||
export const OidbGroupFileListReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
appId: { field: 2, type: 'uint32' as const },
|
||||
targetDirectory: { field: 3, type: 'string' as const },
|
||||
fileCount: { field: 5, type: 'uint32' as const },
|
||||
sortBy: { field: 9, type: 'uint32' as const },
|
||||
startIndex: { field: 13, type: 'uint32' as const },
|
||||
field17: { field: 17, type: 'uint32' as const },
|
||||
field18: { field: 18, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileViewReqSchema = {
|
||||
list: { field: 2, type: 'message' as const, schema: OidbGroupFileListReqSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileListFolderRespSchema = {
|
||||
folderId: { field: 1, type: 'string' as const },
|
||||
parentDirectoryId: { field: 2, type: 'string' as const },
|
||||
folderName: { field: 3, type: 'string' as const },
|
||||
createTime: { field: 4, type: 'uint32' as const },
|
||||
modifiedTime: { field: 5, type: 'uint32' as const },
|
||||
creatorUin: { field: 6, type: 'uint32' as const },
|
||||
creatorName: { field: 7, type: 'string' as const },
|
||||
totalFileCount: { field: 8, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileListFileRespSchema = {
|
||||
fileId: { field: 1, type: 'string' as const },
|
||||
fileName: { field: 2, type: 'string' as const },
|
||||
fileSize: { field: 3, type: 'uint64' as const },
|
||||
busId: { field: 4, type: 'uint32' as const },
|
||||
uploadedTime: { field: 6, type: 'uint32' as const },
|
||||
expireTime: { field: 7, type: 'uint32' as const },
|
||||
modifiedTime: { field: 8, type: 'uint32' as const },
|
||||
downloadedTimes: { field: 9, type: 'uint32' as const },
|
||||
uploaderName: { field: 14, type: 'string' as const },
|
||||
uploaderUin: { field: 15, type: 'uint32' as const },
|
||||
parentDirectory: { field: 16, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileListItemRespSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
folderInfo: { field: 2, type: 'message' as const, schema: OidbGroupFileListFolderRespSchema },
|
||||
fileInfo: { field: 3, type: 'message' as const, schema: OidbGroupFileListFileRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileListRespSchema = {
|
||||
retCode: { field: 1, type: 'uint32' as const },
|
||||
retMsg: { field: 2, type: 'string' as const },
|
||||
clientWording: { field: 3, type: 'string' as const },
|
||||
isEnd: { field: 4, type: 'bool' as const },
|
||||
items: { field: 5, type: 'repeated_message' as const, schema: OidbGroupFileListItemRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileViewRespSchema = {
|
||||
list: { field: 2, type: 'message' as const, schema: OidbGroupFileListRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x6D6_2 / 0x6D6_3: Group file url & delete ---
|
||||
|
||||
export const OidbGroupFileUploadReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
appId: { field: 2, type: 'uint32' as const },
|
||||
busId: { field: 3, type: 'uint32' as const },
|
||||
entrance: { field: 4, type: 'uint32' as const },
|
||||
targetDirectory: { field: 5, type: 'string' as const },
|
||||
fileName: { field: 6, type: 'string' as const },
|
||||
localDirectory: { field: 7, type: 'string' as const },
|
||||
fileSize: { field: 8, type: 'uint64' as const },
|
||||
fileSha1: { field: 9, type: 'bytes' as const },
|
||||
fileSha3: { field: 10, type: 'bytes' as const },
|
||||
fileMd5: { field: 11, type: 'bytes' as const },
|
||||
field15: { field: 15, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileDownloadReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
appId: { field: 2, type: 'uint32' as const },
|
||||
busId: { field: 3, type: 'uint32' as const },
|
||||
fileId: { field: 4, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileDeleteReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
busId: { field: 3, type: 'uint32' as const },
|
||||
fileId: { field: 5, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileMoveReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
appId: { field: 2, type: 'uint32' as const },
|
||||
busId: { field: 3, type: 'uint32' as const },
|
||||
fileId: { field: 4, type: 'string' as const },
|
||||
parentDirectory: { field: 5, type: 'string' as const },
|
||||
targetDirectory: { field: 6, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileReqSchema = {
|
||||
file: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadReqSchema },
|
||||
download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadReqSchema },
|
||||
delete: { field: 4, type: 'message' as const, schema: OidbGroupFileDeleteReqSchema },
|
||||
move: { field: 6, type: 'message' as const, schema: OidbGroupFileMoveReqSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileUploadRespSchema = {
|
||||
retCode: { field: 1, type: 'int32' as const },
|
||||
retMsg: { field: 2, type: 'string' as const },
|
||||
clientWording: { field: 3, type: 'string' as const },
|
||||
uploadIp: { field: 4, type: 'string' as const },
|
||||
serverDns: { field: 5, type: 'string' as const },
|
||||
busId: { field: 6, type: 'int32' as const },
|
||||
fileId: { field: 7, type: 'string' as const },
|
||||
checkKey: { field: 8, type: 'bytes' as const },
|
||||
fileKey: { field: 9, type: 'bytes' as const },
|
||||
boolFileExist: { field: 10, type: 'bool' as const },
|
||||
uploadPort: { field: 14, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileDownloadRespSchema = {
|
||||
retCode: { field: 1, type: 'uint32' as const },
|
||||
retMsg: { field: 2, type: 'string' as const },
|
||||
clientWording: { field: 3, type: 'string' as const },
|
||||
downloadIp: { field: 4, type: 'string' as const },
|
||||
downloadDns: { field: 5, type: 'string' as const },
|
||||
downloadUrl: { field: 6, type: 'bytes' as const },
|
||||
saveFileName: { field: 11, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileRetRespSchema = {
|
||||
retCode: { field: 1, type: 'uint32' as const },
|
||||
retMsg: { field: 2, type: 'string' as const },
|
||||
clientWording: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileRespSchema = {
|
||||
upload: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadRespSchema },
|
||||
download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadRespSchema },
|
||||
delete: { field: 4, type: 'message' as const, schema: OidbGroupFileRetRespSchema },
|
||||
move: { field: 6, type: 'message' as const, schema: OidbGroupFileRetRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops ---
|
||||
|
||||
export const OidbGroupFileCreateFolderReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
rootDirectory: { field: 3, type: 'string' as const },
|
||||
folderName: { field: 4, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileDeleteFolderReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
folderId: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileRenameFolderReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
folderId: { field: 3, type: 'string' as const },
|
||||
newFolderName: { field: 4, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileFolderReqSchema = {
|
||||
create: { field: 1, type: 'message' as const, schema: OidbGroupFileCreateFolderReqSchema },
|
||||
delete: { field: 2, type: 'message' as const, schema: OidbGroupFileDeleteFolderReqSchema },
|
||||
rename: { field: 3, type: 'message' as const, schema: OidbGroupFileRenameFolderReqSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileFolderRetRespSchema = {
|
||||
retcode: { field: 1, type: 'uint32' as const },
|
||||
retMsg: { field: 2, type: 'string' as const },
|
||||
clientWording: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileFolderRespSchema = {
|
||||
create: { field: 1, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
|
||||
delete: { field: 2, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
|
||||
rename: { field: 3, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xE37_1200: Private file download url ---
|
||||
|
||||
export const OidbPrivateFileDownloadReqBodySchema = {
|
||||
receiverUid: { field: 10, type: 'string' as const },
|
||||
fileUuid: { field: 20, type: 'string' as const },
|
||||
type: { field: 30, type: 'uint32' as const },
|
||||
fileHash: { field: 60, type: 'string' as const },
|
||||
t2: { field: 601, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileDownloadReqSchema = {
|
||||
subCommand: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadReqBodySchema },
|
||||
field101: { field: 101, type: 'uint32' as const },
|
||||
field102: { field: 102, type: 'uint32' as const },
|
||||
field200: { field: 200, type: 'uint32' as const },
|
||||
field99999: { field: 99999, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileDownloadRespResultSchema = {
|
||||
server: { field: 20, type: 'string' as const },
|
||||
port: { field: 40, type: 'uint32' as const },
|
||||
url: { field: 50, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileDownloadRespBodySchema = {
|
||||
state: { field: 20, type: 'string' as const },
|
||||
result: { field: 30, type: 'message' as const, schema: OidbPrivateFileDownloadRespResultSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileDownloadRespSchema = {
|
||||
body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadRespBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xE37_1700: Private file upload ---
|
||||
|
||||
export const OidbPrivateFileUploadReqBodySchema = {
|
||||
senderUid: { field: 10, type: 'string' as const },
|
||||
receiverUid: { field: 20, type: 'string' as const },
|
||||
fileSize: { field: 30, type: 'uint32' as const },
|
||||
fileName: { field: 40, type: 'string' as const },
|
||||
md510MCheckSum:{ field: 50, type: 'bytes' as const },
|
||||
sha1CheckSum: { field: 60, type: 'bytes' as const },
|
||||
localPath: { field: 70, type: 'string' as const },
|
||||
md5CheckSum: { field: 110, type: 'bytes' as const },
|
||||
sha3CheckSum: { field: 120, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileUploadReqSchema = {
|
||||
command: { field: 1, type: 'uint32' as const },
|
||||
seq: { field: 2, type: 'int32' as const },
|
||||
upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadReqBodySchema },
|
||||
businessId: { field: 101, type: 'int32' as const },
|
||||
clientType: { field: 102, type: 'int32' as const },
|
||||
flagSupportMediaPlatform: { field: 200, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileUploadRespBodySchema = {
|
||||
retCode: { field: 10, type: 'int32' as const },
|
||||
retMsg: { field: 20, type: 'string' as const },
|
||||
uploadIp: { field: 60, type: 'string' as const },
|
||||
uploadPort: { field: 80, type: 'uint32' as const },
|
||||
uuid: { field: 90, type: 'string' as const },
|
||||
uploadKey: { field: 100, type: 'bytes' as const },
|
||||
boolFileExist: { field: 110, type: 'bool' as const },
|
||||
fileAddon: { field: 200, type: 'string' as const },
|
||||
mediaPlatformUploadKey: { field: 220, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPrivateFileUploadRespSchema = {
|
||||
upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadRespBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- NTV2 Rich Media (0x9067_202): Download RKey ---
|
||||
|
||||
export const NTV2CommonHeadSchema = {
|
||||
requestId: { field: 1, type: 'uint32' as const },
|
||||
command: { field: 2, type: 'uint32' 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 NTV2SceneInfoSchema = {
|
||||
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 NTV2ClientMetaSchema = {
|
||||
agentType: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2ReqHeadSchema = {
|
||||
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||
scene: { field: 2, type: 'message' as const, schema: NTV2SceneInfoSchema },
|
||||
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2DownloadRKeyReqSchema = {
|
||||
types: { field: 1, type: 'repeated_uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
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 NTV2IndexNodeSchema = {
|
||||
info: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
|
||||
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 NTV2VideoDownloadExtSchema = {
|
||||
busiType: { field: 1, type: 'uint32' as const },
|
||||
sceneType: { field: 2, type: 'uint32' as const },
|
||||
subBusiType: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2DownloadExtSchema = {
|
||||
video: { field: 2, type: 'message' as const, schema: NTV2VideoDownloadExtSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2DownloadReqSchema = {
|
||||
node: { field: 1, type: 'message' as const, schema: NTV2IndexNodeSchema },
|
||||
download: { field: 2, type: 'message' as const, schema: NTV2DownloadExtSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2RichMediaReqSchema = {
|
||||
reqHead: { field: 1, type: 'message' as const, schema: NTV2ReqHeadSchema },
|
||||
download: { field: 3, type: 'message' as const, schema: NTV2DownloadReqSchema },
|
||||
downloadRkey: { field: 4, type: 'message' as const, schema: NTV2DownloadRKeyReqSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2RespHeadSchema = {
|
||||
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 NTV2RKeyInfoSchema = {
|
||||
rkey: { field: 1, type: 'string' as const },
|
||||
rkeyTtlSec: { field: 2, type: 'uint64' as const },
|
||||
storeId: { field: 3, type: 'uint32' as const },
|
||||
rkeyCreateTime:{ field: 4, type: 'uint32' as const },
|
||||
type: { field: 5, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2DownloadRKeyRespSchema = {
|
||||
rkeys: { field: 1, type: 'repeated_message' as const, schema: NTV2RKeyInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2MediaDownloadInfoSchema = {
|
||||
domain: { field: 1, type: 'string' as const },
|
||||
urlPath: { field: 2, type: 'string' as const },
|
||||
httpsPort: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2MediaDownloadRespSchema = {
|
||||
rKeyParam: { field: 1, type: 'string' as const },
|
||||
rKeyTtlSecond: { field: 2, type: 'uint32' as const },
|
||||
info: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadInfoSchema },
|
||||
rKeyCreateTime: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2RichMediaRespSchema = {
|
||||
respHead: { field: 1, type: 'message' as const, schema: NTV2RespHeadSchema },
|
||||
download: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadRespSchema },
|
||||
downloadRkey:{ field: 4, type: 'message' as const, schema: NTV2DownloadRKeyRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xB6E_2: Set friend remark ---
|
||||
|
||||
export const OidbSetFriendRemarkSchema = {
|
||||
targetUid: { field: 1, type: 'string' as const },
|
||||
remark: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x9082_2: Set group reaction (remove) — same schema as set ---
|
||||
// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema)
|
||||
|
||||
// --- Group file count (0x6D8_3) ---
|
||||
|
||||
export const OidbGroupFileCountReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
appId: { field: 2, type: 'uint32' as const },
|
||||
busId: { field: 3, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileCountRespSchema = {
|
||||
fileCount: { field: 1, type: 'uint32' as const },
|
||||
maxCount: { field: 2, type: 'uint32' as const },
|
||||
isEnd: { field: 3, type: 'bool' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileCountViewReqSchema = {
|
||||
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountReqSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGroupFileCountViewRespSchema = {
|
||||
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- trpc.msg.msg_svc.MsgService.SsoReadedReport ---
|
||||
|
||||
export const GroupReadedReportItemSchema = {
|
||||
groupUin: { field: 1, type: 'uint64' as const },
|
||||
lastReadSeq: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const C2CReadedReportItemSchema = {
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
lastReadTime: { field: 3, type: 'uint64' as const },
|
||||
lastReadSeq: { field: 4, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SsoReadedReportReqSchema = {
|
||||
groupList: { field: 1, type: 'repeated_message' as const, schema: GroupReadedReportItemSchema },
|
||||
c2cList: { field: 2, type: 'repeated_message' as const, schema: C2CReadedReportItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- 0x102A_1: Get Client Key ---
|
||||
|
||||
export const OidbClientKeyReqSchema = {
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbClientKeyRespSchema = {
|
||||
keyIndex: { field: 2, type: 'uint32' as const },
|
||||
clientKey: { field: 3, type: 'string' as const },
|
||||
expireTime: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- 0x102A_0: Get PSKey ---
|
||||
|
||||
export const OidbGetPskeyReqSchema = {
|
||||
domainList: { field: 1, type: 'repeated_string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPskeyItemSchema = {
|
||||
domain: { field: 1, type: 'string' as const },
|
||||
pskey: { field: 2, type: 'string' as const },
|
||||
expireTime: { field: 3, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGetPskeyRespSchema = {
|
||||
pskeyItems: { field: 1, type: 'repeated_message' as const, schema: OidbPskeyItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
export const SetStatusReqSchema = {
|
||||
status: { field: 1, type: 'int32' as const },
|
||||
extStatus: { field: 2, type: 'int32' as const },
|
||||
batteryStatus: { field: 3, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SetStatusRespSchema = {
|
||||
errCode: { field: 1, type: 'int32' as const }, // 盲猜字段 1 是错误码(虽然成功时没下发,默认 0)
|
||||
errMsg: { field: 2, type: 'string' as const }, // 返回的 "set status success"
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
export const OidbProfileStringItemSchema = {
|
||||
fieldId: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbProfileIntItemSchema = {
|
||||
fieldId: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSetProfileSchema = {
|
||||
uin: { field: 1, type: 'uint64' as const },
|
||||
stringProfiles: { field: 2, type: 'repeated_message' as const, schema: OidbProfileStringItemSchema },
|
||||
intProfiles: { field: 3, type: 'repeated_message' as const, schema: OidbProfileIntItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -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,205 +0,0 @@
|
||||
// QQ info store — per-UIN state for friends, groups, member lookup.
|
||||
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp
|
||||
|
||||
export interface UserProfileInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
qid: string;
|
||||
sex: string;
|
||||
age: number;
|
||||
sign: string;
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
export interface FriendInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface GroupMemberInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
card: string;
|
||||
role: string; // 'owner' | 'admin' | 'member'
|
||||
level: number;
|
||||
title: string;
|
||||
joinTime: number;
|
||||
lastSentTime: number;
|
||||
shutUpTime: number;
|
||||
}
|
||||
|
||||
export interface QQGroupInfo {
|
||||
groupId: number;
|
||||
groupName: string;
|
||||
remark: string;
|
||||
memberCount: number;
|
||||
memberMax: number;
|
||||
members: Map<number, GroupMemberInfo>;
|
||||
}
|
||||
|
||||
export interface GroupRequestInfo {
|
||||
groupId: number;
|
||||
groupName: string;
|
||||
targetUid: string;
|
||||
targetUin: number;
|
||||
targetName: string;
|
||||
invitorUid: string;
|
||||
invitorUin: number;
|
||||
invitorName: string;
|
||||
operatorUid: string;
|
||||
operatorUin: number;
|
||||
operatorName: string;
|
||||
sequence: number;
|
||||
state: number;
|
||||
eventType: number;
|
||||
comment: string;
|
||||
filtered: boolean;
|
||||
}
|
||||
|
||||
export class QQInfo {
|
||||
private uin_: string;
|
||||
private nickname_ = '';
|
||||
private selfProfile_: UserProfileInfo | null = null;
|
||||
private userProfiles_ = new Map<number, UserProfileInfo>();
|
||||
private friends_: FriendInfo[] = [];
|
||||
private groups_ = new Map<number, QQGroupInfo>();
|
||||
|
||||
constructor(uin: string) {
|
||||
this.uin_ = uin;
|
||||
}
|
||||
|
||||
get uin(): string { return this.uin_; }
|
||||
|
||||
get nickname(): string { return this.nickname_; }
|
||||
set nickname(v: string) { this.nickname_ = v; }
|
||||
|
||||
// --- Self profile ---
|
||||
|
||||
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
|
||||
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
|
||||
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
|
||||
|
||||
// --- User profiles ---
|
||||
|
||||
setUserProfile(info: UserProfileInfo): void {
|
||||
this.userProfiles_.set(info.uin, info);
|
||||
}
|
||||
|
||||
findUserProfile(uin: number): UserProfileInfo | null {
|
||||
return this.userProfiles_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
// --- Friends ---
|
||||
|
||||
setFriends(friends: FriendInfo[]): void { this.friends_ = friends; }
|
||||
get friends(): FriendInfo[] { return this.friends_; }
|
||||
|
||||
findFriend(uin: number): FriendInfo | null {
|
||||
return this.friends_.find(f => f.uin === uin) ?? null;
|
||||
}
|
||||
|
||||
// --- Groups ---
|
||||
|
||||
setGroups(groups: QQGroupInfo[]): void {
|
||||
this.groups_.clear();
|
||||
for (const g of groups) {
|
||||
this.groups_.set(g.groupId, g);
|
||||
}
|
||||
}
|
||||
|
||||
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
|
||||
|
||||
findGroup(groupId: number): QQGroupInfo | null {
|
||||
return this.groups_.get(groupId) ?? null;
|
||||
}
|
||||
|
||||
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
|
||||
return this.groups_.get(groupId)?.members.get(uin) ?? null;
|
||||
}
|
||||
|
||||
setGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.clear();
|
||||
for (const m of members) {
|
||||
g.members.set(m.uin, m);
|
||||
}
|
||||
}
|
||||
|
||||
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return;
|
||||
g.members.set(member.uin, member);
|
||||
}
|
||||
|
||||
// --- UID resolution ---
|
||||
|
||||
resolveUid(uid: string): number | null {
|
||||
// Check self
|
||||
if (this.selfProfile_?.uid === uid) {
|
||||
return this.selfProfile_.uin || parseInt(this.uin_, 10) || null;
|
||||
}
|
||||
// Check friends
|
||||
for (const f of this.friends_) {
|
||||
if (f.uid === uid) return f.uin;
|
||||
}
|
||||
// Check user profiles
|
||||
for (const [, p] of this.userProfiles_) {
|
||||
if (p.uid === uid) return p.uin;
|
||||
}
|
||||
// Check all group members
|
||||
for (const [, g] of this.groups_) {
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m.uin;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
resolveGroupMemberUid(groupId: number, uid: string): number | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uid === uid) return m.uin;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Reverse UID lookup (UIN → UID) ---
|
||||
|
||||
findUidByUin(uin: number): string | null {
|
||||
// Check self
|
||||
if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) {
|
||||
return this.selfProfile_.uid;
|
||||
}
|
||||
// Check friends
|
||||
for (const f of this.friends_) {
|
||||
if (f.uin === uin && f.uid) return f.uid;
|
||||
}
|
||||
// Check user profiles
|
||||
for (const [, p] of this.userProfiles_) {
|
||||
if (p.uin === uin && p.uid) return p.uid;
|
||||
}
|
||||
// Check all group members
|
||||
for (const [, g] of this.groups_) {
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uin === uin && m.uid) return m.uid;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
findUidByUinInGroup(groupId: number, uin: number): string | null {
|
||||
const g = this.groups_.get(groupId);
|
||||
if (!g) return null;
|
||||
for (const [, m] of g.members) {
|
||||
if (m.uin === uin && m.uid) return m.uid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
// Web API operations extracted from Bridge.
|
||||
|
||||
import type { Bridge } from './bridge';
|
||||
import { sendOidbAndDecode } from './bridge-oidb';
|
||||
import { resolveUserUid } from './bridge-oidb';
|
||||
import {
|
||||
OidbClientKeyRespSchema,
|
||||
OidbClientKeyReqSchema,
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema
|
||||
} from './proto/oidb-action';
|
||||
import { RequestUtil } from './web/request-util';
|
||||
import { getHonorListWebAPI, WebHonorType } from './web/group-honor';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from './web/group-essence';
|
||||
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI } from './web/group-notice';
|
||||
|
||||
export async function forceFetchClientKey(bridge: Bridge) {
|
||||
const resp = await sendOidbAndDecode<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_1',
|
||||
0x102A,
|
||||
1,
|
||||
{},
|
||||
OidbClientKeyReqSchema,
|
||||
OidbClientKeyRespSchema
|
||||
);
|
||||
|
||||
const clientKey = resp?.clientKey || '';
|
||||
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 sendOidbAndDecode<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_0',
|
||||
0x102A,
|
||||
0,
|
||||
{ domainList },
|
||||
OidbGetPskeyReqSchema,
|
||||
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);
|
||||
|
||||
// 构造 ptlogin2 跳转 URL
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
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 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;
|
||||
}
|
||||
|
||||
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.qqInfo.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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
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: [] } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
export async function sendGroupNotice(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // 未来如果要发图片,传路径进来
|
||||
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) {
|
||||
// const picInfo = await bridge.uploadGroupBulletinPic(groupCode, options.image);
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取的公共算法:根据 skey/p_skey 计算 bkn (也就是 token / csrf_token)
|
||||
*/
|
||||
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 (字符串格式)
|
||||
*/
|
||||
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)
|
||||
*/
|
||||
export async function getCsrfToken(bridge: Bridge): Promise<number> {
|
||||
|
||||
const skey = await getSKey(bridge);
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取凭证 (Cookies 字符串 + Token)
|
||||
*/
|
||||
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
|
||||
};
|
||||
}
|
||||
Loaded 100 of 449 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user